[英]How do I make my Discord Bot reply a same answer for similar messages? JavaScript
I've been working on a Discord bot.我一直在研究一个 Discord 机器人。 I needed a solution for questions like this:
Who are you
or who are you
.对于这样的问题,我需要一个解决方案:
Who are you
或Who are you
who are you
。
The above sentences may seem similar but are case sensitive, and I want my bot to reply the same answer to a few similar questions like I showed above.上面的句子可能看起来相似但区分大小写,我希望我的机器人对我上面展示的几个类似问题做出相同的回答。 This is What I tried:
这是我尝试过的:
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)
But when I run it and write the command, it repeats the reply several times.但是当我运行它并编写命令时,它会重复多次回复。
Any ideas to fix this?任何想法来解决这个问题?
The line that is causing the multiple replies is this one:导致多个回复的行是这样的:
if (msg.content === 'hello', 'hey'){
Your syntax is slightly off and the 'hey' is not part of the statement like you want it to be.您的语法略有偏差,并且“嘿”不是您希望的语句的一部分。 The 'hey' evaluates to
true
which triggers the if statement's code a second time. 'hey' 的计算结果为
true
,这将再次触发 if 语句的代码。
To fix it, you may want to have an array of responses, and check if the user's message is in the array (note the .toLowerCase()
means you don't have to worry about capital letters):要修复它,您可能需要一个响应数组,并检查用户的消息是否在数组中(注意
.toLowerCase()
意味着您不必担心大写字母):
greetings = ['hello', 'hey', 'hi']
if (greentings.indexOf(msg.content.toLowerCase()) > -1) {
// the message is in the array - run your code here
}
You can group similar questions in an array and use Array#includes
to check if the question is in that array.您可以将类似的问题分组到一个数组中,并使用
Array#includes
来检查问题是否在该数组中。 You can also make it case-insensitive by using toLowerCase
.您还可以使用
toLowerCase
使其不区分大小写。 Something like this:像这样的东西:
client.on("message", (msg) => {
const group = [
'how are you',
'how you doin',
'you alright',
]
if (group.includes(msg.content.toLowerCase())) {
msg.reply('hi');
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.