From 6b0dc24721b5b7850478a8802982cf49dd2814a0 Mon Sep 17 00:00:00 2001 From: Jannis Heydemann Date: Wed, 1 Apr 2026 22:50:03 +0200 Subject: [PATCH] refactored the voice update function to exclude users if their muted or afk and remade the commands --- db_management/db_management.go | 43 +++++- main.go | 248 +++++++++++++++++++++++++++++---- 2 files changed, 261 insertions(+), 30 deletions(-) diff --git a/db_management/db_management.go b/db_management/db_management.go index 6268a60..216b035 100644 --- a/db_management/db_management.go +++ b/db_management/db_management.go @@ -31,14 +31,18 @@ func InitDB() { } func SaveSession(userID string, seconds int) { - query := `INSERT INTO voice_sessions (user_id, seconds, created_at) VALUES (?, ?, ?)` + query := ` + INSERT INTO voice_sessions (user_id, seconds, created_at) + VALUES (?, ?, ?) + ` + DB.Exec(query, userID, seconds, time.Now()) } func GetUserStats(userID string) int { var total sql.NullInt64 // NullInt64 fängt NULL-Ergebnisse ab query := `SELECT SUM(seconds) FROM voice_sessions - WHERE user_id = ? AND created_at > date('now', '-30 days')` + WHERE user_id = ? AND created_at > datetime('now', '-30 days')` err := DB.QueryRow(query, userID).Scan(&total) if err != nil || !total.Valid { @@ -46,3 +50,38 @@ func GetUserStats(userID string) int { } return int(total.Int64) } + +type UserStats struct { + UserID string + Seconds int +} + +func GetTopUsers(limit int) []UserStats { + query := ` + SELECT user_id, SUM(seconds) as total + FROM voice_sessions + WHERE created_at > datetime('now', '-30 days') + GROUP BY user_id + ORDER BY total DESC + LIMIT ? + ` + + rows, err := DB.Query(query, limit) + if err != nil { + return nil + } + defer rows.Close() + + var result []UserStats + + for rows.Next() { + var u UserStats + err := rows.Scan(&u.UserID, &u.Seconds) + if err != nil { + continue + } + result = append(result, u) + } + + return result +} diff --git a/main.go b/main.go index 5ecfed3..3b64b32 100644 --- a/main.go +++ b/main.go @@ -11,14 +11,20 @@ import ( "github.com/bwmarrin/discordgo" "github.com/joho/godotenv" - // WICHTIG: Pfad entspricht deiner go.mod "heydeman/vc-stat-bot-discord/db_management" ) -var startTimes = make(map[string]time.Time) +var sessions = make(map[string]*Session) + +type Session struct { + Start time.Time + PausedAt *time.Time + Paused bool + Accum time.Duration +} func main() { - _ = godotenv.Load() // Ignoriert Fehler, falls keine .env existiert (nutzt dann System-Vars) + _ = godotenv.Load() db_management.InitDB() @@ -32,11 +38,12 @@ func main() { log.Fatal(err) } - discord.AddHandler(messageCreate) + // Handler + discord.AddHandler(interactionCreate) discord.AddHandler(voiceUpdate) - discord.Identify.Intents = discordgo.IntentsGuildMessages | - discordgo.IntentsMessageContent | + // Intents + discord.Identify.Intents = discordgo.IntentsGuilds | discordgo.IntentsGuildVoiceStates err = discord.Open() @@ -44,59 +51,244 @@ func main() { log.Fatal("Error opening connection:", err) } - fmt.Println("Bot läuft stabil auf Hetzner. Drücke CTRL+C zum Beenden.") + // Slash Commands registrieren + registerCommands(discord) + go autoSaveSessions() + fmt.Println("Bot läuft stabil. CTRL+C zum Beenden.") + + // Shutdown Handling stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) <-stop - // Graceful Shutdown: Alle aktuell aktiven Sessions noch schnell speichern - fmt.Println("Speichere aktive Sessions vor dem Beenden...") - for uid, start := range startTimes { - db_management.SaveSession(uid, int(time.Since(start).Seconds())) + fmt.Println("Speichere aktive Sessions...") + + // 🔥 NEUE Shutdown-Logik (wichtig!) + for uid, sess := range sessions { + + var total time.Duration + + // bereits gesammelte Zeit + total += sess.Accum + + // wenn NICHT pausiert → aktuelle Zeit dazu + if !sess.Paused { + total += time.Since(sess.Start) + } + + db_management.SaveSession(uid, int(total.Seconds())) } discord.Close() } -func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { - if m.Author.Bot { +func registerCommands(s *discordgo.Session) { + + // /stats + _, err := s.ApplicationCommandCreate(s.State.User.ID, "", &discordgo.ApplicationCommand{ + Name: "stats", + Description: "Zeigt die 30-Tage Statistik eines Users", + Options: []*discordgo.ApplicationCommandOption{ + { + Type: discordgo.ApplicationCommandOptionUser, + Name: "user", + Description: "Optional: anderer User", + Required: false, + }, + }, + }) + if err != nil { + log.Println("Fehler bei /stats:", err) + } + + // /top + _, err = s.ApplicationCommandCreate(s.State.User.ID, "", &discordgo.ApplicationCommand{ + Name: "top", + Description: "Top 10 User nach Zeit (30 Tage)", + }) + if err != nil { + log.Println("Fehler bei /top:", err) + } +} + +func interactionCreate(s *discordgo.Session, i *discordgo.InteractionCreate) { + + if i.Type != discordgo.InteractionApplicationCommand { return } - if m.Content == "!stats" { - totalSeconds := db_management.GetUserStats(m.Author.ID) + switch i.ApplicationCommandData().Name { + + // ===================== + // /stats + // ===================== + case "stats": + + user := i.Member.User + + if len(i.ApplicationCommandData().Options) > 0 { + opt := i.ApplicationCommandData().Options[0] + if opt.Name == "user" { + user = opt.UserValue(s) + } + } + + totalSeconds := db_management.GetUserStats(user.ID) duration := time.Duration(totalSeconds) * time.Second - msg := fmt.Sprintf("📊 **30-Tage Statistik für %s**\nVerbrachte Zeit: `%s`", - m.Author.GlobalName, formatDuration(duration)) - s.ChannelMessageSend(m.ChannelID, msg) + name := user.GlobalName + if name == "" { + name = user.Username + } + + msg := fmt.Sprintf( + "📊 **30-Tage Statistik für %s**\nZeit: `%s`", + name, + formatDuration(duration), + ) + + s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: msg, + }, + }) + + // ===================== + // /top + // ===================== + case "top": + + topUsers := db_management.GetTopUsers(10) + + if len(topUsers) == 0 { + s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: "Keine Daten vorhanden.", + }, + }) + return + } + + msg := "🏆 **Top 10 (30 Tage)**\n\n" + + for i, user := range topUsers { + duration := time.Duration(user.Seconds) * time.Second + + msg += fmt.Sprintf( + "**%d.** <@%s> — `%s`\n", + i+1, + user.UserID, + formatDuration(duration), + ) + } + + s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: msg, + }, + }) } } +const excludedChannelID = "1232031563391172649" + func voiceUpdate(s *discordgo.Session, v *discordgo.VoiceStateUpdate) { + uid := v.UserID - // User betritt Sprachkanal - if v.ChannelID != "" { - if _, ok := startTimes[uid]; !ok { - startTimes[uid] = time.Now() + // ========================= + // ❌ Pause Bedingungen + // ========================= + if v.ChannelID == excludedChannelID || v.SelfMute || v.Mute || v.SelfDeaf || v.Deaf { + + if sess, ok := sessions[uid]; ok && !sess.Paused { + + now := time.Now() + elapsed := now.Sub(sess.Start) + + sess.Accum += elapsed + sess.PausedAt = &now + sess.Paused = true } return } - // User verlässt Sprachkanal (v.ChannelID == "") - if v.ChannelID == "" { - if start, ok := startTimes[uid]; ok { - db_management.SaveSession(uid, int(time.Since(start).Seconds())) - delete(startTimes, uid) + // ========================= + // ▶ Resume (User wieder aktiv) + // ========================= + if v.ChannelID != "" { + + sess, ok := sessions[uid] + + if !ok { + // neue Session + sessions[uid] = &Session{ + Start: time.Now(), + Paused: false, + } + return } + + // wenn pausiert → weiterlaufen lassen + if sess.Paused { + sess.Start = time.Now() + sess.Paused = false + sess.PausedAt = nil + } + + return + } + + // ========================= + // ❌ User verlässt Voice + // ========================= + if sess, ok := sessions[uid]; ok { + + total := sess.Accum + + if !sess.Paused { + total += time.Since(sess.Start) + } + + db_management.SaveSession(uid, int(total.Seconds())) + delete(sessions, uid) } } - func formatDuration(d time.Duration) string { h := int(d.Hours()) m := int(d.Minutes()) % 60 s := int(d.Seconds()) % 60 return fmt.Sprintf("%dh %dm %ds", h, m, s) } + +func autoSaveSessions() { + + ticker := time.NewTicker(5 * time.Minute) // ⏱ Intervall anpassen + defer ticker.Stop() + + for range ticker.C { + + fmt.Println("🔄 Auto-Save: speichere Sessions...") + + for uid, sess := range sessions { + + var total time.Duration + + total += sess.Accum + + if !sess.Paused { + total += time.Since(sess.Start) + } + + // Zwischenspeichern (ADD statt replace!) + db_management.SaveSession(uid, int(total.Seconds())) + + // ⚠️ Wichtig: + // NICHT löschen → Session läuft weiter + } + } +}