I'm currently working on a bot that replies on the word "frog" and "yarr" with "Word1" or "Word2" (50%/50% chance with cooldown included).
const rG = ["Word1", "Word2"]
const randomMessage = rG[Math.floor(Math.random() * rG.length)];
let myFrog = /frog/i;
let myYarr = /yarr/i;
client.on("message", message => {
if (message.author.bot) return;
if (
myYarr.test(message.content) ||
myFrog.test(message.content)
)
if (userCooldown[message.author.id]) return;
userCooldown[message.author.id] = true;
message.reply(randomMessage);
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000); //5 sec cooldown
})
The problem is that it doesn't matter what the user sends, it just replies and skips the cooldown too. Plus somehow it's not random for some reason, it depends if I change the first number of the cooldown, but no idea how it is connected.
If you indent your code properly, you can see that the only line inside your first if statement is if (userCooldown[message.author.id]) return. The rest of the code runs regardless of your tests:
client.on('message', (message) => {
if (message.author.bot) return;
if (myYarr.test(message.content) || myFrog.test(message.content))
if (userCooldown[message.author.id]) return;
// => it's outside of the myYarr.tests
userCooldown[message.author.id] = true;
message.reply(randomMessage);
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000); //5 sec cooldown
});
You need to make sure that you use curly braces ({}) if you only want to execute the rest of your code when one of the regex tests are true.
Also, you could probably create a new array with the words you're expecting and check if the user-submitted message is one of these words. You can use Array#includes for this. This way it's easier to add new words and you only need to update your code on a single line.
client.on('message', (message) => {
if (message.author.bot) return;
const replies = ['Word1', 'Word2'];
const randomMessage = replies[Math.floor(Math.random() * replies.length)];
const wordList = ['frog', 'yarr'];
if (wordList.includes(message.content.toLowerCase())) {
if (userCooldown[message.author.id])
return;
userCooldown[message.author.id] = true;
message.reply(randomMessage);
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000);
}
});