-
Notifications
You must be signed in to change notification settings - Fork 59
/
messageCooldown.ts
75 lines (62 loc) · 2.04 KB
/
messageCooldown.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { Message } from 'discord.js'
import { StickyMessage } from '@prisma/client'
import { Environment } from '@/config'
import { getCache, saveCache } from '@/utils/cache'
import { getCounter } from './messageCounter'
import { STICKY_COOLDOWN_PREFIX, pushMessageToBottom } from './stickyMessages'
const channelCooldown: Map<string, NodeJS.Timeout> = new Map()
/**
* Set the channel status to cooldown
*
* @param {string} channelId - the id of channel that want to lock
*
*/
function cooldown(channelId: string): void {
saveCache(`${STICKY_COOLDOWN_PREFIX}-${channelId}`, true)
}
/**
* Set the channel status to available
*
* @param {string} channelId - the id of channel that want to unlock
*
*/
function available(channelId: string): void {
saveCache(`${STICKY_COOLDOWN_PREFIX}-${channelId}`, false)
}
/**
* Check the channel status is lock
*
* @param {string} channelId - the id of channel that want to check
* @returns cooldown status (default) if available flag is true return channel available status
*
*/
export function isCooldown(channelId: string): boolean {
return getCache(`${STICKY_COOLDOWN_PREFIX}-${channelId}`) === true
}
/**
* Set the cooldown of the channel.
*
* @param {Message} message - The message object associated with the channel.
* @param {StickyMessage} stickyMessage - The sticky message associated with the channel.
* @returns {Promise<void>} A Promise that resolves once the cooldown is set.
*/
export async function resetCooldown(
message: Message,
stickyMessage: StickyMessage,
): Promise<void> {
// mark channel is cooldown
cooldown(message.channelId)
const timeout = channelCooldown.get(message.channelId)
// is has saved timeout -> clear it
if (timeout) {
clearTimeout(timeout)
}
const timeoutId = setTimeout(() => {
// mark channel is available
available(message.channelId)
if (getCounter(message.channelId) > 1) {
pushMessageToBottom(message, stickyMessage)
}
}, Environment.MESSAGE_COOLDOWN_SEC * 1000)
channelCooldown.set(message.channelId, timeoutId)
}