himbot/lib/cooldowns.go

68 lines
1.1 KiB
Go
Raw Normal View History

2024-01-03 14:32:37 -07:00
package lib
import (
"sync"
"time"
)
2024-01-10 00:28:31 -07:00
var (
mu sync.Mutex
instance *CooldownManager
)
2024-01-03 14:32:37 -07:00
type CooldownManager struct {
cooldowns map[string]time.Time
mu sync.Mutex
}
func NewCooldownManager() *CooldownManager {
return &CooldownManager{
cooldowns: make(map[string]time.Time),
}
}
2024-01-10 00:28:31 -07:00
func GetInstance() *CooldownManager {
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &CooldownManager{
cooldowns: make(map[string]time.Time),
}
}
return instance
}
func (m *CooldownManager) StartCooldown(userID string, key string, duration time.Duration) {
2024-01-03 14:32:37 -07:00
m.mu.Lock()
defer m.mu.Unlock()
2024-01-10 00:28:31 -07:00
m.cooldowns[userID+":"+key] = time.Now().Add(duration)
2024-01-03 14:32:37 -07:00
}
2024-01-10 00:28:31 -07:00
func (m *CooldownManager) IsOnCooldown(userID string, key string) bool {
2024-01-03 14:32:37 -07:00
m.mu.Lock()
defer m.mu.Unlock()
2024-01-10 00:28:31 -07:00
cooldownEnd, exists := m.cooldowns[userID+":"+key]
2024-01-03 14:32:37 -07:00
if !exists {
return false
}
if time.Now().After(cooldownEnd) {
2024-01-10 00:28:31 -07:00
delete(m.cooldowns, userID+":"+key)
2024-01-03 14:32:37 -07:00
return false
}
return true
}
2024-01-10 00:28:31 -07:00
func CancelCooldown(userID string, key string) {
manager := GetInstance()
manager.mu.Lock()
defer manager.mu.Unlock()
delete(manager.cooldowns, userID+":"+key)
}