机器人回复消息作者

Sha*_*bot 3 node.js discord discord.js

我已经创建了自己的 Node.js 机器人来在我的 Discord 服务器中工作。

我的机器人名为mybot.

我见过许多响应传入消息的示例 - 它们看起来像这样(并且工作正常)。

chatroom.on('message', function(msg){
    if(msg.content === 'ping'){
        msg.reply('pong');
    }
});
Run Code Online (Sandbox Code Playgroud)

每当有人在频道中只写“ping”时,上面的代码都会让机器人回复“pong”。

与大多数机器人一样,通常您会与他们交谈并要求他们提供类似的东西@mybot blahblahblah- 然后他们会回复。

我想做这个。我只想mybot在和他说话时回复。必须有一个msg.recipientListormsg.recipients捕获@mybot. 我浏览了 Discord.js 的文档,但很难找到这个结果。

Pet*_*r G 5

有几种不同的方法可以做到这一点,但我认为最“优雅”的方法是使用Message.isMentioned它作为参数的对象(类型为 User、GuildChannel、Role、string)来检查消息中是否有对象的 @reference . 你需要做的就是提供你的机器人的 User 对象(基类的存储对象是一个 ClientUser 实例,但 User 是它的超类)。

// 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');
  }
});
Run Code Online (Sandbox Code Playgroud)