Bot reply to message author

13,438

There are a few different ways to do this, but I think the most "elegant" way is to use Message.isMentioned which takes as argument an object (of type User, GuildChannel, Role, string) to check the message for an @reference to the object. All you need to do is provide your bot's User object (the base class's stored object is a ClientUser instance but User is its superclass).

// I'm assuming chatroom is your bot's DiscordClient instance,
// if it isn't then replace the "chatroom" in chatroom.user with the bot's 
// DiscordClient.
chatroom.on('message', msg => {
  if (msg.isMentioned(chatroom.user)) {
    msg.reply('pong');
  }
});
Share:
13,438
Shazboticus S Shazbot
Author by

Shazboticus S Shazbot

I smell like bacon.

Updated on August 21, 2022

Comments

  • Shazboticus S Shazbot
    Shazboticus S Shazbot almost 2 years

    I've created my own Node.js bot to work in my discord server.

    My bot is named mybot.

    I've seen numerous examples of responding to incoming messages - they look like this (and work just fine).

    chatroom.on('message', function(msg){
        if(msg.content === 'ping'){
            msg.reply('pong');
        }
    });
    

    The code above will have the bot reply with "pong" whenever anyone writes just "ping" in the channel.

    As with most bots, generally you speak to them and ask them for something like @mybot blahblahblah - and then they reply.

    I want to do this. I want mybot to only reply when he is spoken to. There must be a msg.recipientList or msg.recipients that captures the @mybot. I've looked through Discord.js's docs and I'm having a hard time finding this result.