Deps + Made "cooldown" lib more generic as a timer lib

This commit is contained in:
2024-03-19 14:31:40 -06:00
parent 3ac076709e
commit f672ff8763
6 changed files with 10 additions and 80 deletions

View File

@ -1,72 +0,0 @@
package lib
import (
"sync"
"time"
)
var (
mu sync.Mutex
instance *CooldownManager
)
type CooldownManager struct {
cooldowns map[string]time.Time
mu sync.Mutex
}
func NewCooldownManager() *CooldownManager {
return &CooldownManager{
cooldowns: make(map[string]time.Time),
}
}
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) {
m.mu.Lock()
defer m.mu.Unlock()
m.cooldowns[userID+":"+key] = time.Now().Add(duration)
}
func (m *CooldownManager) IsOnCooldown(userID string, key string) (bool, time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
cooldownEnd, exists := m.cooldowns[userID+":"+key]
if !exists {
return false, 0
}
if time.Now().After(cooldownEnd) {
delete(m.cooldowns, userID+":"+key)
return false, 0
}
return true, time.Until(cooldownEnd)
}
func CancelCooldown(userID string, key string) {
manager := GetInstance()
// Handle non-existent keys gracefully
if _, exists := manager.cooldowns[userID+":"+key]; !exists {
return
}
manager.mu.Lock()
defer manager.mu.Unlock()
delete(manager.cooldowns, userID+":"+key)
}

View File

@ -9,7 +9,7 @@ import (
"github.com/diamondburned/arikawa/v3/discord"
)
var manager = NewCooldownManager()
var manager = NewTimerManager()
// Userish is an interface that captures the common methods you may want to call
// on either a discord.Member or discord.User, including a display name.
@ -79,11 +79,11 @@ func CooldownHandler(event discord.InteractionEvent, key string, duration time.D
}
}
isOnCooldown, remaining := manager.IsOnCooldown(user.ID().String(), key)
isOnCooldown, remaining := manager.TimerRunning(user.ID().String(), key)
if isOnCooldown {
return false, fmt.Sprintf("You are on cooldown. Please wait for %v", remaining)
}
manager.StartCooldown(user.ID().String(), key, duration)
manager.StartTimer(user.ID().String(), key, duration)
return true, ""
}