Xanar
Xanar

Reputation: 15

Get avatar of an user in discord.js that doesn't share the same server

I have a small problem with my bot. For developing my bot, I made a new dev-bot which shares the same code as my normal bot, but has it's own token. However, I ran into a small issue while developing.

I use this code, to get someones' avatar:

client.users.get(event.user.uid).avatarURL

This works fine on my normal but, however on my Dev-Bot I get this error message:

Error getting documents TypeError: Cannot read property 'AvatarURL' of undefined

I think it's due to the fact, that my Bot can't access the avatar of the user, because it doesn't share the same server/guild as this user.

Is there any workaround I could use?

Upvotes: 0

Views: 21896

Answers (1)

FireController1847
FireController1847

Reputation: 1912

Due to Discord.js and their way of caching, not all users are going to be cached in the bot. While there is a small possibility of it actually not knowing anything about the user, there is a large chance that the Discord API will still allow you to get information from it.

To fix this issue with caching in the latest master, we have to use Client.users, which returns a UserStore. Within the UserStore, we can use a method called fetch to get information about a user.

To fix this issue in the latest stable, we have to use a method called Client.fetchUser, which does the same thing but returns a User instead of a UserStore.

Please note this is only available using a bot account. Here's an example of its usage:

// Using Discord.js Stable
bot.fetchUser(theUsersID).then(myUser => {
    console.log(myUser.avatarURL); // My user's avatar is here!
});

// Using Discord.js Master
bot.users.fetch(theUsersID).then(myUser => {
    console.log(myUser.avatarURL()); // My user's avatar is here!
});

If there is an error fetching the user (say, a DiscordAPI Permissions Error), this means that there is no way for your bot to get the user's avatar without knowing who the user is first (or sharing a Guild with the user). Happy coding!

Upvotes: 2

Related Questions