From 80fafd72cf6f84c6197035048520ce570b736d76 Mon Sep 17 00:00:00 2001 From: Priyanshu Jain Date: Sun, 29 Jan 2023 19:05:48 +0530 Subject: [PATCH] Added Cooldowns Added Cooldowns to Slash Commands --- Events/Guild/interactionCreate.js | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Events/Guild/interactionCreate.js b/Events/Guild/interactionCreate.js index 51a9512..2ff1389 100644 --- a/Events/Guild/interactionCreate.js +++ b/Events/Guild/interactionCreate.js @@ -1,5 +1,7 @@ const client = require('../../index'); const { EmbedBuilder, Collection, PermissionsBitField } = require(`discord.js`); +const cooldowns = new Map(); +const ms = require('ms'); client.on('interactionCreate', async interaction => { if (interaction.isContextMenuCommand()){ @@ -44,6 +46,38 @@ client.on('interactionCreate', async interaction => { } if(!interaction.member) interaction.member = await interaction.guild.members.fetch(interaction.user.id); + + const command = cmd; + if(command){ + //registering command in map to get cooldowns + if(!cooldowns.has(command.name)){ + cooldowns.set(command.name, new Collection()); + } + + const current_time = Date.now(); + const time_stamps = cooldowns.get(command.name); + const cooldown_amount = (command.cooldown) * 1000; + + //If time_stamps has a key with the author's id then check the expiration time to send a message to a user. + if(time_stamps.has(interaction.user.id)){ + const expiration_time = time_stamps.get(interaction.user.id) + cooldown_amount; + + if(current_time < expiration_time){ + const time_left = (expiration_time - current_time); + + return interaction.reply({embeds: [ + new EmbedBuilder() + .setDescription(`**You are on a cooldown of \`${ms(cooldown_amount)}\`.\n\nCooldown Ends: **`) + .setColor(interaction.guild.members.me.displayHexColor) + ]}); + } + } + + //If the author's id is not in time_stamps then add them with the current time. + time_stamps.set(interaction.user.id, current_time); + //Delete the user's id once the cooldown is over. + setTimeout(() => time_stamps.delete(interaction.user.id), cooldown_amount); + } cmd.execute(client, interaction, args); });