Search code examples
discorddiscord.pyhttpwebrequesturllibwebrequest

HTTP Error 403: Forbidden on urllib when I'm trying to get profile pic of a new member with my discord bot


I'm coding a discord.py discord BOT. Now I'm writing the "on_member_join", and I'm trying to get the new member profile pic to make a custom image of welcome. Here's the issue. When I start the program, and a member join the server, the request is correctly send, but I receive the HTTP Error 403: Forbidden error.

My code:

import discord
from PIL import Image,ImageDraw,ImageFont
import urllib.request

@client.event
async def on_member_join(member):

    url = f"{member.avatar_url}"

    name = "profile.png"

    urllib.request.urlretrieve(url, name)

Remember that I need to download the image because I have to customize it with the "Pillow library"


Solution

  • discord.Member.avatar_url (I am linking to the User equivalent as the docs redirect there anyway) returns an Asset that you can call await read() on. This will give you a byte representation of the avatar that you can directly read into a Pillow Image like so:

    from io import BytesIO
    from PIL import Image
    
    avatar_bytes = await member.avatar_url.read()
    im = Image.open(BytesIO(avatar_bytes))
    

    If you need to save the original avatar to disk, you can use save() instead of read()