I’m working on a Discord bot using JavaScript and having trouble with user mentions. When someone types a command with a user mention, I want the bot to respond by mentioning that same user with a message.
For example:
User: hey coolness @SomeUser
Bot: @SomeUser is 75% cool!
I’m confused about how to handle the mentioned user in the code. Should I use member objects or display names? Here’s what I tried:
client.on('message', msg => {
if (msg.content.startsWith('hey coolness')) {
if (msg.content === @user) {
msg.channel.send(@user + ' is ' + (Math.floor(Math.random() * 100) + 1) + '% cool!')
}
}
})
The bot doesn’t respond at all. I think the issue is with how I’m checking for the mentioned user. The random number generation works fine in other parts of my code.
Your condition check is the problem - msg.content === @user isn’t valid JavaScript and won’t work. You need to grab the mentioned users from the message object properly.
Here’s the fix:
client.on('message', msg => {
if (msg.content.startsWith('hey coolness')) {
if (msg.mentions.users.size > 0) {
const mentionedUser = msg.mentions.users.first();
msg.channel.send(`${mentionedUser} is ${Math.floor(Math.random() * 100) + 1}% cool!`);
}
}
})
Use msg.mentions.users to get all mentioned users, then grab the first one. I switched to template literals too since they’re cleaner for string formatting. This’ll properly detect when someone mentions a user in the command.
the issue is you’re using @user which doesn’t exist in javascript. try msg.mentions.users.first() instead and check if there’s actually a mention before doing anything. your random math works fine - it’s just the mention parsing that’s broken.
Your condition has a syntax error. You can’t use @user like that in JavaScript - it’s not defined, and the === comparison with msg.content will never work since the content has more than just the mention. You need to check if mentions exist first, then grab the user ID or user object. Here’s how:
client.on('message', msg => {
if (msg.content.startsWith('hey coolness') && msg.mentions.users.size > 0) {
const user = msg.mentions.users.first();
const coolness = Math.floor(Math.random() * 100) + 1;
msg.channel.send(user.toString() + ' is ' + coolness + '% cool!');
}
})
user.toString() gives you the proper mention format. Combining the conditions is more efficient too - it won’t check for mentions unless the command prefix matches.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.