-
Notifications
You must be signed in to change notification settings - Fork 0
/
basecommand.go
100 lines (81 loc) · 1.91 KB
/
basecommand.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package basecommand
import (
"sync"
"time"
)
type User interface {
GetID() string
}
type Command struct {
cooldownMutex *sync.RWMutex
userCooldowns map[string]bool
globalCooldown bool
UserCooldown int
GlobalCooldown int
Description string
}
func New() Command {
return Command{
cooldownMutex: &sync.RWMutex{},
userCooldowns: make(map[string]bool),
UserCooldown: 15,
GlobalCooldown: 5,
}
}
func (c *Command) addCooldown(userID string) {
c.cooldownMutex.Lock()
c.userCooldowns[userID] = true
c.globalCooldown = true
c.cooldownMutex.Unlock()
}
func (c *Command) removeGlobalCooldown() {
c.cooldownMutex.Lock()
c.globalCooldown = false
c.cooldownMutex.Unlock()
}
func (c *Command) removeCooldown(userID string) {
c.cooldownMutex.Lock()
delete(c.userCooldowns, userID)
c.cooldownMutex.Unlock()
}
func (c *Command) hasCooldown(userID string) (ok bool) {
c.cooldownMutex.RLock()
if c.globalCooldown {
ok = true
} else {
_, ok = c.userCooldowns[userID]
}
c.cooldownMutex.RUnlock()
return ok
}
func (c *Command) HasCooldown(user User) bool {
return c.hasCooldown(user.GetID())
}
func (c *Command) HasUserIDCooldown(userID string) bool {
return c.hasCooldown(userID)
}
func (c *Command) AddCooldown(user User) {
c.addCooldown(user.GetID())
time.AfterFunc(time.Duration(c.UserCooldown)*time.Second, func() {
c.removeCooldown(user.GetID())
})
time.AfterFunc(time.Duration(c.GlobalCooldown)*time.Second, func() {
c.removeGlobalCooldown()
})
}
func (c *Command) AddUserIDCooldown(userID string) {
c.cooldownMutex.Lock()
c.userCooldowns[userID] = true
c.cooldownMutex.Unlock()
time.AfterFunc(time.Duration(c.UserCooldown)*time.Second, func() {
c.removeCooldown(userID)
})
}
func (c *Command) AddGlobalCooldown() {
c.cooldownMutex.Lock()
c.globalCooldown = true
c.cooldownMutex.Unlock()
time.AfterFunc(time.Duration(c.GlobalCooldown)*time.Second, func() {
c.removeGlobalCooldown()
})
}