How to get user by user id in slash command?
P粉368878176
P粉368878176 2023-07-18 15:47:02
0
2
550

I've been writing a Discord bot, referring to tutorials as needed since I'm new to it, but I've run into a problem that, although it sounds simple, I can't seem to solve. I'm trying to draw a leaderboard, and for each position on the leaderboard, I want to get the user's avatar to draw onto the leaderboard. In order to do this, I want to be able to get the user by just their user ID. However, I'm doing all of this in a single slash command. Here's a very simplified example to provide some context and/or better explanation:

const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
// ... some functions and what not go here
module.exports = {
   //... lines for setting up the command go here

   async execute(interaction){
       const data = fetchData();  //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary
       // ... a bunch of stuff, ordering my data, etc.
       data.forEach(async (userData, index) => {
          // And here begins my issue. The line below is just what I have attempted to do
          const target = interaction.guild.members.cache.get(userData.UserId); 
       });
   };
}

I've done quite a bit of research and the only working solution I've found (which you can see in the sample code above) is to use const target = interaction.guild.members.cache.get("User_ID "); However, although I can log the return value in the console, if I try to do something like "target.user" it says target is undefined. If it helps, yes, I'm including GuildMembers in my intent.

P粉368878176
P粉368878176

reply all(2)
P粉029327711

If you just want to get the ID of the user who ran the slash command, you can use interaction.user.id.

To get the user by ID, you can run the following code:

//Inside the execute function of the slash command

interaction.guild.members.cache.get("user_id").then(function(user){
    //Do something with user
} 
P粉006977956

You need to use members.fetch because it is asynchronous, so you need to change your forEach to for...of because forEach is synchronous.

const { SlashCommandBuilder, AttachmentBuilder } = require('discord.js');
// ... some functions and what not go here
module.exports = {
   //... lines for setting up the command go here

   async execute(interaction) {
       const data = fetchData();  //A function that gets the whole list of data; did not put it in the codeblock to save on space since it's not necessary
       // ... a bunch of stuff, ordering my data, etc.
       for (const userData of data) {
         const target = await interaction.guild.members.fetch(userData.UserId)
       }
   };
} 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template