I've been working on a Discord bot. I needed a solution for questions like this: Who are you
or 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?
CodePudding user response:
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.
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):
greetings = ['hello', 'hey', 'hi']
if (greentings.indexOf(msg.content.toLowerCase()) > -1) {
// the message is in the array - run your code here
}
CodePudding user response:
You can group similar questions in an array and use Array#includes
to check if the question is in that array. You can also make it case-insensitive by using 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');
}
})