Ian Swift
Ian Swift

Reputation: 69

How to get values from client.users.fetch(id) in discord.js

I have a bot that takes a mention and returns some user information:

bot.on('message', async message => {
    let usr = bot.users.fetch(message.replace('<@!', '').replace('>', ''));
    message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});

However, the bot returns undefined for both values. I have logged the user object, and revieved

Promise {
    User { 
        id: '',
        username: '',
        bot: false,
        discriminator: '',
        avatar: '',
        lastMessageId: '',
        LastMessage: '',
    }
}

The values are different, but the objects are the same. I tried using usr.Promise.User.value, usr.User.value, and usr.Promise.value with no luck. Is there some way to do this?

Upvotes: 0

Views: 7158

Answers (2)

Androz2091
Androz2091

Reputation: 3005

You can also use message.mentions.users.first():

bot.on('message', async message => {
    let usr = message.mentions.users.first();
    message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});

It's a totally different way to do what you want and it's better. It also avoids your "promise" problem so it's not really an answer.

Upvotes: 1

Androz2091
Androz2091

Reputation: 3005

It returns a Promise so you need to use await or .then to get its resolved value:

bot.on('message', async message => {
    let usr = await bot.users.fetch(message.replace('<@!', '').replace('>', ''));
    message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
});

OR:

bot.on('message', async message => {
    bot.users.fetch(message.replace('<@!', '').replace('>', '')).then((usr) => {
        message.channel.send(`id: ${usr.id}\nname: ${usr.username}`);
    });
});

You can read this to learn more about promises.

Upvotes: 2

Related Questions