简体   繁体   中英

Bot reply to message author

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.

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');
  }
});

You may also use if(message.content.startsWith(prefix)) or if(message.content.indexOf("what you are looking in message") != -1) . First is for when you want the message to start with prefix and second is when you want sth to be in message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM