【问题标题】:How do I make my Discord Bot reply a same answer for similar messages? JavaScript如何让我的 Discord Bot 对类似消息回复相同的答案? JavaScript
【发布时间】:2021-12-17 22:36:08
【问题描述】:

我一直在研究 Discord 机器人。对于这样的问题,我需要一个解决方案:Who are youwho are you

上述句子可能看起来相似,但区分大小写,我希望我的机器人对上面显示的几个类似问题回复相同的答案。这是我尝试过的:

import Discord from 'discord.js'
import { Client, Intents } from 'discord.js'

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.on("ready", () => {
  console.log("Log In Successful!!")
})

client.on("message", msg => {
  if (msg.content === 'hello', 'hey') {
    msg.reply("hi");
  }
})

client.login(process.env.TOKEN)

但是当我运行它并编写命令时,它会重复多次回复。

有解决这个问题的想法吗?

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    导致多次回复的行是这一行:

    if (msg.content === 'hello', 'hey'){
    

    您的语法略有偏差,并且“嘿”不是您想要的语句的一部分。 “嘿”的计算结果为 true,这会再次触发 if 语句的代码。

    要修复它,您可能需要一个响应数组,并检查用户的消息是否在数组中 (注意.toLowerCase() 表示您不必担心大写字母):

    greetings = ['hello', 'hey', 'hi']
    if (greentings.indexOf(msg.content.toLowerCase()) > -1) {
        // the message is in the array - run your code here
    }
    

    【讨论】:

    • .indexOf(x) > -1 并不是真正需要的,只需使用 .includes(x)
    【解决方案2】:

    您可以将类似的问题分组到一个数组中,然后使用Array#includes 检查问题是否在该数组中。您还可以使用toLowerCase 使其不区分大小写。像这样的:

    client.on("message", (msg) => {
      const group = [
        'how are you',
        'how you doin',
        'you alright',
      ]
      if (group.includes(msg.content.toLowerCase())) {
        msg.reply('hi');
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 2021-07-04
      • 2021-08-23
      • 2019-03-23
      • 2023-04-10
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多