I’m working on a Discord bot command that should display the username of a mentioned user in an embed message. However, the bot isn’t showing the actual username - it just displays [object Object] instead.
client.on('messageCreate', (message) => {
if (message.content.startsWith('!attack')) {
const embedMessage = new Discord.MessageEmbed();
const sender = message.author.username;
const mentionedUser = message.mentions.members.first();
embedMessage.setTitle(`**TIME TO ATTACK ${mentionedUser}**`);
embedMessage.setImage('https://example.com/attack.gif');
embedMessage.setColor('RED');
embedMessage.setFooter('Attack initiated');
message.channel.send({ embeds: [embedMessage] });
}
});
I also tried using const mentionedUser = message.mentions.members.first().username; but that doesn’t work either. The bot runs without errors but the embed shows the object reference instead of the actual username. What’s the correct way to extract and display the mentioned user’s name?
totally get what you’re saying! that happened to me too - the [object Object] thing is from trying to use the whole member obj in a string. just do message.mentions.members.first().user.username and it’ll work. also, def check if a user was mentioned, or the bot will crash.
You’re passing the whole GuildMember object to the embed title instead of just the username. message.mentions.members.first().username doesn’t work because GuildMember objects don’t have a username property - you need to go through the user object. Try this: const mentionedUser = message.mentions.members.first().user.username; or use message.mentions.members.first().displayName for their server nickname. Also, add some error handling. Your bot will crash if someone runs the command without mentioning anyone. Just check message.mentions.members.size > 0 first and you’ll save yourself the headache.
You’re getting that error because you’re trying to concatenate a GuildMember object directly into a string. message.mentions.members.first() returns a GuildMember object, not a string. Use message.mentions.members.first().user.username for their basic username, or message.mentions.members.first().displayName for their server nickname (it’ll fall back to username if they don’t have one). Don’t forget to check if someone actually mentioned a user first - your bot will crash if they run the command without mentioning anyone. Just check if mentionedUser exists before accessing its properties.