OGBenT
OGBenT

Reputation: 53

How can I make my Discord bot recognize it when it is mentioned?

Im thinking about for example I have a command that gives bread and it gives bread to every user but I want to make that if someone tags the bot then it says a different message, so I made a different func for this, but unfortunately I cant figure it out how can I make my bot recognize that the user has tagged the bot or an user... Can anyone help?

client.on("message", function(message) {
  if (message.content === `give bread to <@${client.id}>`) {
    message.channel.send(`I cant give bread to my self...`) 
 }
  return;
});

Upvotes: 0

Views: 268

Answers (2)

Elitezen
Elitezen

Reputation: 6710

You can check message.mentions.users and use has() with the bot's ID which would be client.user.id since we want the bot's User object.

client.on("message", function(message) {
  if (message.content.startsWith('give bread to')) {
    
    const mentions = message.mentions.users;
    if (mentions.has(client.user.id)) {
       return message.channel.send(`I cant give bread to my self...`)
    } else {
       // Your code
    }
  }
  return;
});

Upvotes: 2

Itamar S
Itamar S

Reputation: 1565

First of all, the client object does not have an id property. I believe you're referring to the user object property of client, that returns a User object, from which you can get the client's id from.

A much more optimized route for doing your desired outcome is to check if the mentioned user (in your original function)'s ID is equal to the client id, and if so return a different output:

client.on('message', message => {
  if (!message.content.startsWith(`give bread to `) return
  const mentioned = message.mentions.users.first()
  if (!mentioned) return
  if (mentioned.id === client.user.id) return message.channel.send(`I cant give bread to my self...`)
})

Upvotes: 0

Related Questions