【问题标题】:How get usernames from IDs in discord.js如何从 discord.js 中的 ID 获取用户名
【发布时间】:2021-08-11 19:17:47
【问题描述】:

我存储了 ID 或昵称(字符串只是因为不是不和谐的用户)。现在我想从不和谐的用户那里获取用户名。我得到了一个 [promise object] 并且我无法访问。我读了一些关于 .then 但没有成功的东西。我不知道这种情况下的结构如何:

for (var i = 0; i < ids.length; i++){

    let tag = client.fetchUser(ids[i]);

    if(tag.username){
            //if exist put his username
            title.push(tag.username);
            info += icons[i] + ' = ' + tag.username + ' \n';
         }else{
             //if not exist, means we saved the nickname only (string)
            title.push(size[i]);
            info += icons[i] + ' = ' + size[i] + ' \n';
    }
}

const embed = new Discord.RichEmbed()
    .setTitle(title.join(' - '))
    .setColor(0x00AE86)
    .setDescription(info)
    .setFooter("none")
    .setTimestamp()
    .setURL("https://discord.gg/sHanmsPX")
    .addField("-", "-", true);

【问题讨论】:

  • 您使用的是v11,DJS不支持11版本,请更新到v12。请注意changes,因为它们非常重要。

标签: node.js discord.js


【解决方案1】:

请使用 Discord.JS v12 对比 v11

请阅读以下内容:当您发布问题时,请务必删除 discord.gg 邀请或使其无效!这适用于任何敏感信息!

不和谐 v11 版本

因此,fetchUser 函数返回一个封装在 Promise 中的用户。如果您的 for 代码在函数内,请将其设为 asynchronous 并生成:

let tag = client.fetchUser(ids[i]);

进入:

let tag = await client.fetchUser(ids[i]);

你也可以这样做,不需要 async/await:

let tag = client.fetchUser(ids[i]).then(u=>{
    // your code here...
});

不和谐 v12 版本

使用 v12,它已更新,但 fetchUser 方法不再存在。你必须使用这个:

let tag = client.users.fetch(ids[i]);
// this is a promise! Use async/await or .then after.

您可以使用缓存,但这是针对机器人看到的或与之交互的用户:

let tag = client.users.cache.get(ids[i]);
// this is not a promise.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 2020-07-05
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2021-01-08
    相关资源
    最近更新 更多