我目前正在使用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/