Skip to content
This repository was archived by the owner on Oct 10, 2024. It is now read-only.

Commit b6a5570

Browse files
luckspteddiejaoudeBOLT04
authored
feat(cooldowns): restrict user to a command every 2 seconds. (#283)
* refactor: Abstract cooldowns * refactor: make isCooled function return only bool * style: lint fixes #283 Co-authored-by: Eddie Jaoude <[email protected]> Co-authored-by: David <[email protected]>
1 parent 2532c46 commit b6a5570

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

src/commands.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Message } from 'discord.js';
22

33
import commandList, { fallback } from './commandHandlers';
44
import config from './config';
5+
import cooldown from './cooldown';
56

67
const { COMMAND_PREFIX, defaultEmbed } = config;
78

@@ -10,6 +11,13 @@ export const commands = async (message: Message) => {
1011
return;
1112
}
1213

14+
if (cooldown.isCooled(message.author.id)) {
15+
message.channel.send(
16+
`:clock1: Too fast! Only **1** command each **${config.COOLDOWN_SECONDS}** seconds.`
17+
);
18+
return;
19+
}
20+
1321
const args = message.content.slice(COMMAND_PREFIX.length);
1422
const command = args.split(/ +/).shift()!.toLowerCase();
1523

@@ -25,5 +33,6 @@ export const commands = async (message: Message) => {
2533
message.channel.send(
2634
await matching.command(args.slice(command.length + 1), embed, message)
2735
);
36+
cooldown.setCool(message.author.id);
2837
}
2938
};

src/config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export default {
1818
'delete',
1919
],
2020
COMMAND_PREFIX: process.env.COMMAND_PREFIX || '$',
21+
COOLDOWN_SECONDS: 2,
2122
INTRO_CHANNEL: 'introductions',
2223
GENERAL_CHANNEL: 'general',
2324
BOT_CHANNEL_ID: process.env.DISCORD_BOT_CHANNEL_ID,

src/cooldown.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { Collection, Snowflake } from 'discord.js';
2+
import config from './config';
3+
4+
const collection = new Collection<Snowflake, number>();
5+
6+
export default {
7+
isCooled: (id: Snowflake): boolean => {
8+
const nextCommand = collection.get(id);
9+
return !!nextCommand && nextCommand > Date.now();
10+
},
11+
setCool: (id: Snowflake): void => {
12+
collection.set(id, Date.now() + config.COOLDOWN_SECONDS * 1000);
13+
},
14+
};

0 commit comments

Comments
 (0)