首页 > 解决方案 > How get usernames from IDs in discord.js

问题描述

i stored ids or nicknames(string only because are not discord users). Now i want to get the usernames from users that are part of discord. Tho i get a [promise object] and i cant access. I read something about .then but not success. I dont know how the structure would be in this case:

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

标签: node.jsdiscord.js

解决方案


请使用 Discord.JS v12 与 v11 相比

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

不和谐 v11 版本

因此,该fetchUser函数返回一个包装在承诺中的用户。如果您的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.

推荐阅读