javascript - 从用户ID获取用户头像

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

它会在没有图像的情况下正常发送嵌入内容,但之后每隔几秒就会抛出一个抛出错误

最佳答案

Client.fetchUser()返回 Promise 。本质上,您必须等待它返回一个值。您可以使用关键字 await 来执行此操作或附上 then()方法的 promise 。但是,如果使用 catch() 拒绝 promise ,您还应该捕获任何错误。方法或try...catch声明。

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

示例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因为如果用户没有设置头像 URL,它将返回默认头像 URL。

关于javascript - 从用户ID获取用户头像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56637052/

相关文章:

javascript - 使用 FontSelector 更改字体系列

discord - 如何获得在线成员(member)数量?

javascript - 类型错误 : Cannot read property 'id' of undefined when trying to make discord bot

javascript 用超链接替换 ​​[] 中的文本

javascript - 通过ajax存储数据然后访问该URL

javascript - 无法将数据 append 到 Div 并重定向页面

node.js - 使用请求模块在 Node.js 中发送 URL 编码的参数

node.js - Mongoose:获取最新记录,然后按另一个字段对它们进行排序

javascript - 如何使用护照本地 Mongoose 更改密码?

javascript - 订单不和谐 js 中的 react