我一直在研究一个不和谐的机器人。对于这样的问题,我需要一个解决方案:Who are you或who 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)但当我运行它并编写命令时,它会重复几次回复。
有什么办法来解决这个问题吗?
发布于 2021-11-03 14:40:10
导致多个回复的行如下所示:
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
}发布于 2021-11-03 14:42:11
您可以将类似的问题分组到一个数组中,并使用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');
}
})https://stackoverflow.com/questions/69826698
复制相似问题