himbot/lib/cooldown.go

67 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-03-27 12:23:45 -06:00
package lib
import (
2024-10-22 12:24:02 -06:00
"fmt"
2024-03-27 12:23:45 -06:00
"sync"
"time"
2024-10-22 12:24:02 -06:00
"github.com/bwmarrin/discordgo"
2024-03-27 12:23:45 -06:00
)
var (
2024-10-22 12:24:02 -06:00
once sync.Once
instance *CooldownManager
2024-03-27 12:23:45 -06:00
)
2024-10-22 12:24:02 -06:00
type CooldownManager struct {
cooldowns map[string]time.Time
mu sync.Mutex
2024-03-27 12:23:45 -06:00
}
2024-10-22 12:24:02 -06:00
func GetCooldownManager() *CooldownManager {
once.Do(func() {
instance = &CooldownManager{
cooldowns: make(map[string]time.Time),
2024-03-27 12:23:45 -06:00
}
2024-10-22 12:24:02 -06:00
})
2024-03-27 12:23:45 -06:00
return instance
}
2024-10-22 12:24:02 -06:00
func (cm *CooldownManager) SetCooldown(userID, commandName string, duration time.Duration) {
cm.mu.Lock()
defer cm.mu.Unlock()
cm.cooldowns[userID+":"+commandName] = time.Now().Add(duration)
2024-03-27 12:23:45 -06:00
}
2024-10-22 12:24:02 -06:00
func (cm *CooldownManager) CheckCooldown(userID, commandName string) (bool, time.Duration) {
cm.mu.Lock()
defer cm.mu.Unlock()
2024-03-27 12:23:45 -06:00
2024-10-22 12:24:02 -06:00
key := userID + ":" + commandName
if cooldownEnd, exists := cm.cooldowns[key]; exists {
if time.Now().Before(cooldownEnd) {
return false, time.Until(cooldownEnd)
}
delete(cm.cooldowns, key)
2024-03-27 12:23:45 -06:00
}
2024-10-22 12:24:02 -06:00
return true, 0
2024-03-27 12:23:45 -06:00
}
2024-10-22 12:24:02 -06:00
func CheckAndApplyCooldown(s *discordgo.Session, i *discordgo.InteractionCreate, commandName string, duration time.Duration) bool {
2024-10-22 16:19:31 -06:00
cooldownManager := GetCooldownManager()
user, err := GetUser(i)
if err != nil {
RespondWithError(s, i, "Error processing command: "+err.Error())
return false
}
2024-10-22 12:24:02 -06:00
2024-10-22 16:19:31 -06:00
canUse, remaining := cooldownManager.CheckCooldown(user.ID, commandName)
if !canUse {
RespondWithError(s, i, fmt.Sprintf("You can use this command again in %v", remaining.Round(time.Second)))
return false
}
2024-10-22 12:24:02 -06:00
2024-10-22 16:19:31 -06:00
cooldownManager.SetCooldown(user.ID, commandName, duration)
return true
2024-03-27 12:23:45 -06:00
}