added enhanced DB functions

This commit is contained in:
2025-04-08 18:48:34 -04:00
parent 7599665e4c
commit 18d8b6eee2
4 changed files with 45 additions and 0 deletions
+6
View File
@@ -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))
+23
View File
@@ -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()
+15
View File
@@ -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....")
+1
View File
@@ -9,6 +9,7 @@ import (
"github.com/joho/godotenv"
)
func main() {
// Attempt to load .env, but don't fail if not found.
_ = godotenv.Load()