From 18d8b6eee23e723da6b862887c2c2b74dbd6e4b9 Mon Sep 17 00:00:00 2001 From: ION606 Date: Tue, 8 Apr 2025 18:48:34 -0400 Subject: [PATCH] added enhanced DB functions --- Bot/Commands/suggest.go | 6 ++++++ Bot/Helpers/suggestion_db.go | 23 +++++++++++++++++++++++ Bot/bot.go | 15 +++++++++++++++ main.go | 1 + 4 files changed, 45 insertions(+) diff --git a/Bot/Commands/suggest.go b/Bot/Commands/suggest.go index 6bef0ba..99d4a53 100644 --- a/Bot/Commands/suggest.go +++ b/Bot/Commands/suggest.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "io" + "log" "net/http" "os" "strings" @@ -45,6 +46,11 @@ func HandleSuggest(s *discordgo.Session, i *discordgo.InteractionCreate) { return } + err = helpers.RemoveUserSubmittions(userID); + if err != nil { + log.Default().Println(fmt.Sprintf("%s", err.Error())) + } + // Store new submission time if err := helpers.SetLastSubmission(userID); err != nil { helpers.HandleError(s, i, fmt.Errorf("failed to update cooldown: %w", err)) diff --git a/Bot/Helpers/suggestion_db.go b/Bot/Helpers/suggestion_db.go index 19a3e4b..c7bfcde 100644 --- a/Bot/Helpers/suggestion_db.go +++ b/Bot/Helpers/suggestion_db.go @@ -2,6 +2,7 @@ package helpers import ( "database/sql" + "fmt" "os" "path/filepath" "sync" @@ -62,6 +63,28 @@ func SetLastSubmission(userID string) error { return err } +func RemoveUserSubmittions(userId string) error { + _, err := db.Exec(` + DELETE FROM suggestion_cooldowns WHERE user_id = ? + `, userId) + + return err +} + +func SweepExpiredSubmissions(expiration time.Duration) error { + cutoff := time.Now().Add(-expiration) + result, err := db.Exec("DELETE FROM suggestion_cooldowns WHERE last_submission <= ?", cutoff) + + if err != nil { + return fmt.Errorf("failed to sweep expired submissions: %w", err) + } + + rowsDeleted, _ := result.RowsAffected() + fmt.Printf("Swept %d expired entries from suggestion_cooldowns\n", rowsDeleted) + + return nil +} + func CloseDB() error { if db != nil { return db.Close() diff --git a/Bot/bot.go b/Bot/bot.go index fc8ae1a..4fd24a7 100644 --- a/Bot/bot.go +++ b/Bot/bot.go @@ -5,6 +5,7 @@ import ( "os" "os/signal" "strings" + "time" commands "ion606_bot/Bot/Commands" helpers "ion606_bot/Bot/Helpers" @@ -51,6 +52,20 @@ func Run() { log.Printf("Failed to initialize suggestion DB: %v", err) } + go func() { + ticker := time.NewTicker(5 * time.Minute) // adjust interval as needed + defer ticker.Stop() + for { + select { + case <-ticker.C: + // For example, sweep entries older than 5 minutes: + if err := helpers.SweepExpiredSubmissions(5 * time.Minute); err != nil { + log.Printf("Error sweeping expired submissions: %v", err) + } + } + } + }() + RegisterCommands(discord, "") log.Println("Bot running....") diff --git a/main.go b/main.go index 457b860..54930a4 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,7 @@ import ( "github.com/joho/godotenv" ) + func main() { // Attempt to load .env, but don't fail if not found. _ = godotenv.Load()