Bob joe12
Bob joe12

Reputation: 125

How to fetch user's tag with id discord.js in variable

I am making a leaderboard system for my bot, and want to display the user's tag along with their amount of money.

Here is the code

        const lb = users
                  .slice(0)
                  .sort(({ Bobux: a }, { Bobux: b }) => b - a)
                  .map(
                    
                    ({ User, Bobux }, pos) => `${pos + 1}. ${(client.users.cache.get(User)).tag} - ${commaNumber(Bobux)} Bobux`,
                  );
    
              const newnew =     lb.slice(0, 30)
                  const embed = new Discord.MessageEmbed()
                  .setTitle('Global Leaderboard For Most Bobux - Top 30')
                  .setDescription(newnew)

Over here, I map it, and attempt to get the user's tag with their id (User is the user's id in the database)

User looks like this '43908439084329084'

                  .map(
                    
                    ({ User, Bobux }, pos) => `${pos + 1}. ${(client.users.cache.get(User)).tag} - ${commaNumber(Bobux)} Bobux`,
                  );

When I do this, I get the error

0|index  | TypeError: Cannot read properties of undefined (reading 'tag')

How do I fetch the user's tag with their id.

Upvotes: 0

Views: 2435

Answers (1)

Twilight
Twilight

Reputation: 370

You can fetch the user via UserManager#fetch method. The following code will check if the user is cached, if not it will fetch that user from Discord.

const user = await client.users.fetch(UserId).catch(() => null);
if (!user) console.log("That user is not available");
else console.log(user.tag);

Documentation: https://discord.js.org/#/docs/discord.js/stable/class/UserManager

Upvotes: 1

Related Questions