How to store a user in a variable in discord.js?

Member

by shyann , in category: Javascript , 2 months ago

How to store a user in a variable in discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 2 months ago

@shyann 

In Discord.js, you can store a user in a variable by using the client.users.cache.get() method to retrieve a user from the cache. Here is an example of how you can store a user in a variable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', message => {
  if (message.content.startsWith('!userinfo')) {
    const user = message.mentions.users.first(); // Get the mentioned user
    if (user) {
      console.log(user.username); // Log the username of the user
    } else {
      console.log('User not found');
    }
  }
});

client.login('YOUR_DISCORD_API_TOKEN');


In this example, when a message is sent in the chat starting with !userinfo, the bot will get the mentioned user and store it in the user variable. You can then access the user's properties such as username, id, etc. and perform further actions with it.