How do you set a cooldown on a Slash command?
I recently started working on Discord JS v13 with Slash commands and I was wondering, how can I set cooldowns to the commands? And if it's possible, could you please show me an example?
This is my test code:
const { Permissions, MessageEmbed, MessageActionRow, MessageButton } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName("test")
.setDescription("Test command."),
async run (client, interaction, message){
interaction.reply({ content: "What is this uwu", ephemeral: true })
}
}
Solution 1:
First, create a discord.js collection to store users' cooldown and set cooldown time.
// index.js
client.cooldowns = new Discord.Collection();
client.COOLDOWN_SECONDS = 10; // replace with desired cooldown time in seconds
When a user executes a command, check if the user exists in the cooldown. If so, notify it to the user. If not, run the comnand and set cooldown. After the time you specified, remove it.
// command file
async run(client, interaction, message) {
if (client.cooldowns.has(interaction.user.id)) {
// cooldown not ended
interaction.reply({ content: "Please wait for cooldown to end", ephemeral: true });
} else {
// no cooldown
// do something here
//now, set cooldown
client.cooldowns.set(interaction.user.id, true);
// After the time you specified, remove the cooldown
setTimeout(() => {
client.cooldowns.delete(interaction.user.id);
}, client.COOLDOWN_SECONDS * 1000);
}
}
Solution 2:
Here is the code which I used and it worked:
First you have to create a Set
const cooldown = new Set();
///This is 1 minute, you can change it to whatever value
const cooldownTime = 60000;
Then this is the code:
if (cooldown.has(interaction.user.id)) {
/// If the cooldown did not end
interaction.reply({ content: "Please wait for the cooldown to end", ephemeral: true });
} else {
/// Else give the reply
interaction.reply({ content: "What is this uwu", ephemeral: true });
//now, set cooldown
cooldown.add(interaction.user.id);
setTimeout(() => {
// Removes the user from the set after 1 minute
cooldown.delete(interaction.user.id);
}, cooldownTime);
}