不和谐机器人 JS 有人可以解释发生了什么以及如何预防它吗?



当代码为:

client.on('message', msg => {
  const args = msg.content;
  const command = args.toLowerCase()
  if (command === 'frick'){
    msg.reply('Sorry Sir this is a Christian server so no swearing! >:(');
  }
});

消息正常发送

当我在其中添加"狗屎"时

client.on('message', msg => {
  const args = msg.content;
  const command = args.toLowerCase()
  if (command === 'frick' || 'shit'){
    msg.reply('Sorry Sir this is a Christian server so no swearing! >:(');
  }
});

这是一个结果 它只是循环

我知道我可以添加一行忽略机器人,但我希望它也对机器人有效

  1. 你的if语句的计算结果总是为 true,因为你本质上是在检查 if ('shit') ,这是真实的,因为它的长度大于 0。
  2. 您不会忽略机器人消息。所以你正在创建一个无限循环,其中bot sends message -> bot receives own message -> bot sends message -> bot receives own message -> ....

要修复 1,请确保正确编写 if 语句:

if (command === 'frick' || command === 'shit') {

要修复 2,您可以在消息处理程序的开头添加一个简单的if,以检查作者是否是机器人:

if (msg.author.bot) {
  return;
}

要使其更短,您可以执行以下操作:

if (command === ('frick' || 'shit')) {

相关内容

最新更新