From 4b0fcc7b3671279c77a9d86edf5527cc7e707f78 Mon Sep 17 00:00:00 2001 From: Supositware Date: Sun, 14 Aug 2022 23:28:24 +0200 Subject: [PATCH] Add ratelimit and cooldowns --- commands/fun/tweet.js | 2 ++ events/client/interactionCreate.js | 30 ++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/commands/fun/tweet.js b/commands/fun/tweet.js index c90ceece..556e82d5 100644 --- a/commands/fun/tweet.js +++ b/commands/fun/tweet.js @@ -25,6 +25,8 @@ export default { option.setName('image') .setDescription('Optional attachment (Image only.)') .setRequired(false)), + ratelimit: 3, + cooldown: 3600, async execute(interaction) { await interaction.deferReply({ ephemeral: false }); const client = interaction.client; diff --git a/events/client/interactionCreate.js b/events/client/interactionCreate.js index a691de7c..b52735b8 100644 --- a/events/client/interactionCreate.js +++ b/events/client/interactionCreate.js @@ -1,4 +1,5 @@ import db from '../../models/index.js'; +const ratelimit = {}; export default { name: 'interactionCreate', async execute(interaction) { @@ -14,13 +15,38 @@ export default { return interaction.reply({ content: 'You are blacklisted.', ephemeral: true }); } - const command = client.commands.get(interaction.commandName); + const userTag = interaction.user.tag; + const userID = interaction.user.id; + const commandName = interaction.commandName; - console.log(`\x1b[33m${interaction.user.tag} (${interaction.user.id})\x1b[0m launched command \x1b[33m${interaction.commandName}\x1b[0m`); + const command = client.commands.get(commandName); + console.log(`\x1b[33m${userTag} (${userID})\x1b[0m launched command \x1b[33m${commandName}\x1b[0m`); if (!command) return; try { + const date = new Date(); + if (ratelimit[userID]) { + if (ratelimit[userID].cooldown) { + if (commandName === ratelimit[userID].command && date > ratelimit[userID].cooldown) { + ratelimit[userID].limit = 0; + ratelimit[userID].cooldown = undefined; + } + } + + if (commandName === ratelimit[userID].command && command.ratelimit === ratelimit[userID].limit) { + return await interaction.reply({ content: `You are being rate limited. You can try again in ${Math.floor((ratelimit[userID].cooldown - date) / 1000)} seconds.`, ephemeral: true }); + + } + } + if (command.ratelimit) { + ratelimit[userID] = { command: commandName, limit: ratelimit[userID] ? ratelimit[userID].limit + 1 : 1 }; + if (command.ratelimit === ratelimit[userID].limit) { + date.setSeconds(date.getSeconds() + command.cooldown); + + ratelimit[userID] = { command: commandName, limit: ratelimit[userID].limit, cooldown: date }; + } + } await command.execute(interaction); } catch (error) {