Lallu
Lallu

Reputation: 168

Discord.js bot responds when mentioned

I'm trying to make my discord.js bot send a message when it is pinged. I was unsure how to do this so I referred to this code:

client.on('message', message => {
    if (message.content === '<@745648345216712825>') {
        message.channel.send('Message Here');
    }
});

However, this doesn't work.

Also, is it possible that my bot responds when a person mentions a specific user for example if I am mentioned by the user anywhere in a message the bot responds? If yes, can you show me how to do it?

Upvotes: 2

Views: 16544

Answers (3)

Legendary Emoji
Legendary Emoji

Reputation: 228

One of the best ways to check if only your bot is mentioned in the entire message is, regex. You can use this regular expression to check if only the client is mentioned:

/^<@!?${<client>.user.id}>( |)$/

You can check message by using the match method of String. In our case, String is message.content:

if (message.content.match(/^<@!?${client.user.id}>( |)$/)) {
  return message.channel.send("Thanks for mentioning me! my prefix is ...");
};

Upvotes: 0

Jakye
Jakye

Reputation: 6625

Message has a property called mentions, which contains all the channels, members, roles, and users mentioned in the message. You can use the method .has(data, [options]) of MessageMentions to see if your bot was mentioned.


client.on("messageCreate", (message) => {
    if (message.author.bot) return false;

    if (message.content.includes("@here") || message.content.includes("@everyone") || message.type == "REPLY") return false;

    if (message.mentions.has(client.user.id)) {
        message.channel.send("Hello there!");
    }
});

The message event has been renamed to messageCreate in Discord.JS v13. Using message will still work, but you'll receive a deprecation warning until you switch over.

Upvotes: 11

Filippo menghi
Filippo menghi

Reputation: 11

discord.js just got updated you can use

client.on('message', message => {
    if (message.mentions.has(client.user)) {
        message.channel.send('your message');
    }
});

Upvotes: 1

Related Questions