How do I get the avatar of a specific user using his user id with discord,py

Viewed 9012

I used discord.py to make a bot that stores the user ids in its database to identify them but I can't figure out how to get the avatar of a specific user just by using his id. I searched around and found about something like this - Client.get_user() but it doesn't work for me as I couldn't understand it's working from the documentation. Is there any way I can pick up a user id string from my database and pass it through a function to get that user's avatar and use that in an embed?

I found another question on StackOverflow like mine but the solution in that one doesn't work for me as well.

2 Answers

According to the article, you get the user's id and request the avatar data of the user. It looks like string. Here is the sample JSON response from the request:

{
  "id": "80351110224678912",
  "username": "Nelly",
  "discriminator": "1337",
  "avatar": "8342729096ea3675442027381ff50dfe",
  "verified": true,
  "email": "nelly@discord.com",
  "flags": 64,
  "premium_type": 1,
  "public_flags": 64
}

Now when you get this: "avatar": "8342729096ea3675442027381ff50dfe", you know that the avatar data is 8342729096ea3675442027381ff50dfe. After that, you will use Image Base Url for images: https://cdn.discordapp.com/.
To request an image you have to chose format (jpg, gif, png etc...). So your final request should be:

https://cdn.discordapp.com/avatars/{user_id}/{user_avatar}.png

where user_id and user_avatar are variables to be changed. For example:

https://cdn.discordapp.com/avatars/80351110224678912/8342729096ea3675442027381ff50dfe.png

You can use user = discord.utils.get(ctx.guild.members, id='id that you get from database(must be integer)') then you can get the avatar with user.avatar_url. Here is an example do this:

user_id = "get the user id from database"
user = discord.utils.get(ctx.guild.members, id=int(user_id))
avatar = user.avatar_url
Related