Rob
Rob

Reputation: 17

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

Upvotes: 0

Views: 200

Answers (1)

SomePerson
SomePerson

Reputation: 1309

Please, use Discord.JS v12 compared to v11

And please read this: When you post a question, be sure to strip out discord.gg invites OR invalidate them! This applies for any sensitive info!

Discord v11 Version

So, the fetchUser function returns a user wrapped inside a promise. If your for code is inside a function, make it asynchronous and make:

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

INTO:

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

You can also do this, which doesn't need async/await:

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

Discord v12 Version

Use v12, its updated but the fetchUser method is no longer there. You have to use this:

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

You could use the cache, but this is for users the bot sees, or has interacted with:

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

Upvotes: 1

Related Questions