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