从用户ID获取用户头像

时间:2019-06-17 18:37:32

标签: javascript node.js discord discord.js

我目前正在使用discord.js开发一个生日宣布机器人。我想通过使用他们的Discord用户ID来显示用户的化身,然后将其用于嵌入。

当前无法使用client.fetchUser('[userID]').avatarURL

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);
    }
});

它将自动发送没有图片的嵌入内容,但此后每隔几秒钟会给出throw er

2 个答案:

答案 0 :(得分:1)

在尝试了很多解决方案之后,我设法制作了这段代码供我自己使用。

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();
});

答案 1 :(得分:0)

Client.fetchUser()返回一个Promise。本质上,您必须等待它返回值。您可以使用关键字await或通过将then()方法附加到Promise来做到这一点。但是,如果使用catch()方法或try...catch语句来拒绝诺言,您还应该捕获任何错误。

我建议阅读this MDN文档,以获取有关JavaScript异步编程的更多信息。

示例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);

示例2:

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

在这些示例中,我使用的是displayAvatarURL,因为如果未设置用户的头像,它将返回默认的头像网址。

相关问题