Discord Js gives null avatarURL for server members that have the default avatar
Asked Answered
N

4

5

Here is my code that is trying to access the user's avatar:

Client.on("guildMemberAdd", newMember => {
    console.log("Welcomed member avatar: " + newMember.user.avatar);
    console.log("Welcomed member avatarURL: " + newMember.user.avatarURL);
});

Above code works fine if its a user that has just joined the server and has setup an avatar which is different from discord's default avatar. But for users that have the discord's default avatar, both avatar and avatarURL is null.

So how do I get this working for such users?

BTW this is possible because bots like https://welcomer.fun/ are doing it already.

Nonmaterial answered 6/2, 2019 at 15:5 Comment(0)
F
13

If a user has no avatar, their default avatar will be their discriminator modulo 5. The avatar endpoint would be https://cdn.discordapp.com/embed/avatars/0.png with 0 being the value.

Foin answered 7/2, 2019 at 9:13 Comment(0)
W
6

You can use the displayAvatarURL which (according to the docs) gives the avatarURL if the user has one set, and if not, will return the default avatar URL. Example code:

Client.on("guildMemberAdd", newMember => {
    console.log("Welcomed member avatarURL: " + newMember.user.displayAvatarURL);
});

For the avatar property, I don't think there is a displayAvatar property or something similar. I have checked the docs but couldn't find anything related to it

Whereunto answered 6/2, 2019 at 15:15 Comment(1)
Off-topic, but what would the equivalent in discord.py be? =)Quite
O
4

As of 3 May 2023, Discord has started using a new username system, which removes discriminators from usernames.

The default avatar endpoint is https://cdn.discordapp.com/embed/avatars/index.png, where the value for index depends on whether the user is migrated to the new username system.


For users on the new username system, index will be (user_id >> 22) % 6. If you are using JavaScript, the 'user_id' needs to be converted to a BigInt value. To calculate the value for index, you can use the following method:

(BigInt(user_id) >> 22n) % 6n

For users still on the legacy username system, index will be discriminator % 5.

Documentation: https://discord.com/developers/docs/reference#image-formatting-cdn-endpoints

Outcry answered 6/7, 2023 at 1:7 Comment(0)
D
0

I think it's normal, no avatar no url If avatarURL is null then handle this case and take a url of a generic image instead

Dogfish answered 6/2, 2019 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.