我一直在编写一个Discord机器人,根据需要参考教程,因为我是新手,但是我遇到了一个问题,尽管听起来很简单,但我似乎无法解决。我正在尝试绘制一个排行榜,并且对于排行榜上的每个位置,我想获取用户的头像来绘制到排行榜上。为了做到这一点,我希望能够仅通过用户ID获取用户。然而,我正在一个单独的斜杠命令中完成所有这些操作。下面是一个非常简化的示例,以提供一些背景和/或更好的解释:
const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js'); // ... some functions and what not go here module.exports = { //... lines for setting up the command go here async execute(interaction){ const data = fetchData(); //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary // ... a bunch of stuff, ordering my data, etc. data.forEach(async (userData, index) => { // And here begins my issue. The line below is just what I have attempted to do const target = interaction.guild.members.cache.get(userData.UserId); }); }; }
我已经进行了相当多的研究,而我找到的唯一可行的解决方案(你可以在上面的示例代码中看到)是使用 const target = interaction.guild.members.cache.get("User_ID"); 然而,尽管我可以在控制台中记录返回值,但如果我尝试执行类似 "target.user" 的操作,它会显示 target 未定义。如果有帮助的话,是的,我在我的意图中包含了 GuildMembers。
P粉0293277112023-07-19 15:38:14
如果你只想获取运行斜杠命令的用户的ID,你可以使用 interaction.user.id。
要通过ID获取用户,你可以运行以下代码:
//Inside the execute function of the slash command
interaction.guild.members.cache.get("user_id").then(function(user){
//Do something with user
}
P粉0069779562023-07-19 12:06:11
你需要使用 members.fetch,因为它是异步的,所以你需要将你的 forEach 改为 for...of,因为 forEach 是同步的。
const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
// ... some functions and what not go here
module.exports = {
//... lines for setting up the command go here
async execute(interaction) {
const data = fetchData(); //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary
// ... a bunch of stuff, ordering my data, etc.
for (const userData of data) {
const target = await interaction.guild.members.fetch(userData.UserId)
}
};
}