I am developing a discord.js bot and I want to make a cooldown for a command.
I saw a lot of tutorials on how to do it on Google, but all those tutorials do it for all the commands (so when a user type !mycmd all the users have to wait X minutes/seconds until it can be typed again).
But I want to do it for each user (when a user type !mycmd , ONLY this user have to wait X minutes/seconds until THE USER can type it again).
Is it possible?
Thanks!
3 Answers
Yes it is easy and possible.
Add this at the top of your JS file:
// First, this must be at the top level of your code, **NOT** in any event!
const talkedRecently = new Set();Now in the command event add this:
if (talkedRecently.has(msg.author.id)) { msg.channel.send("Wait 1 minute before getting typing this again. - " + msg.author); } else { // the user can type the command ... your command code goes here :) // Adds the user to the set so that they can't talk for a minute talkedRecently.add(msg.author.id); setTimeout(() => { // Removes the user from the set after a minute talkedRecently.delete(msg.author.id); }, 60000); } 3 You can use the package quick.db in case you want to keep track of cooldowns, even after a restart.
let cooldown = 43200000; // 12 hours in ms let lastDaily = await db.fetch(`daily_${message.author.id}`); if (lastDaily !== null && cooldown - (Date.now() - lastDaily) > 0) { // If user still has a cooldown let timeObj = ms(cooldown - (Date.now() - lastDaily)); // timeObj.hours = 12
} else { // Otherwise they'll get their daily } You can use wokcommands or discord.js-commando they're a very useful package for easy command and event handling. It has a built-in cooldown which you can use. A per user cooldown and a global cooldown. Also, commando has throttling, like rate-limiting. It's like allowing a user to use the command 4 times or whatever you input and after that the cooldown will execute.
In case you want to keep track on your cooldown when the bot restarts, Wokcommands supports mongodb and has a built in collection for cooldown.
1