简体   繁体   中英

Get user avatar from user ID

I'm currently developing a birthday announcing bot using discord.js. I wanted to show the avatar of the user, using their Discord user ID to then be used in an embed.

Using client.fetchUser('[userID]').avatarURL currently isn't working.

const exampleEmbed = new Discord.RichEmbed()
    .setColor('#0099ff')
    .setAuthor('🎂 Birthday Announcement:')
    .setThumbnail(cleint.fetchUser('[userID]').avatarURL)
    .setDescription('🎉 Happy day of birth [user ID]! 🎁')
    .setFooter('May 25');

client.on('message', message => {
    if (message.content.toLowerCase().startsWith('f.test')) {
        message.channel.send(exampleEmbed);
    }
});

It will send the embed alright without the image, but it will give a throw er every few seconds afterwards.

Client.fetchUser() returns a Promise . Essentially, you have to wait for it to return a value. You can do so using the keyword await or by attaching a then() method to the promise. However, you also should catch any errors in the event of a rejected promise with a catch() method or try...catch statement.

I'd suggest reading up on this MDN documentation for more about asynchronous programming in JavaScript.

Example 1:

// This needs to be inside of an async function to use 'await'
const { displayAvatarURL } = await client.fetchUser('id')
  .catch(console.error);

embed.setThumbnail(displayAvatarURL);

Example 2:

client.fetchUser('id')
  .then(user => {
    const embed = new Discord.RichEmbed()
      .setThumbnail(user.displayAvatarURL);
  })
  .catch(console.error);

In these examples, I'm using displayAvatarURL because it will return a default avatar URL if the user doesn't have theirs set.

After trying many solutions, I managed to make this code for my own use.

const client = new Discord.Client();
let thanos = client.users.fetch('IDHERE');
thanos.then(function(result1) {
    //put your code that uses the result1 (the user object) here
    //for example, you could do var imgURL = result1.displayAvatarURL();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM