refactored the voice update function to exclude users if their muted or afk and remade the commands
This commit is contained in:
@@ -31,14 +31,18 @@ func InitDB() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func SaveSession(userID string, seconds int) {
|
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())
|
DB.Exec(query, userID, seconds, time.Now())
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetUserStats(userID string) int {
|
func GetUserStats(userID string) int {
|
||||||
var total sql.NullInt64 // NullInt64 fängt NULL-Ergebnisse ab
|
var total sql.NullInt64 // NullInt64 fängt NULL-Ergebnisse ab
|
||||||
query := `SELECT SUM(seconds) FROM voice_sessions
|
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)
|
err := DB.QueryRow(query, userID).Scan(&total)
|
||||||
if err != nil || !total.Valid {
|
if err != nil || !total.Valid {
|
||||||
@@ -46,3 +50,38 @@ func GetUserStats(userID string) int {
|
|||||||
}
|
}
|
||||||
return int(total.Int64)
|
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
|
||||||
|
}
|
||||||
|
|||||||
248
main.go
248
main.go
@@ -11,14 +11,20 @@ import (
|
|||||||
"github.com/bwmarrin/discordgo"
|
"github.com/bwmarrin/discordgo"
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
// WICHTIG: Pfad entspricht deiner go.mod
|
|
||||||
"heydeman/vc-stat-bot-discord/db_management"
|
"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() {
|
func main() {
|
||||||
_ = godotenv.Load() // Ignoriert Fehler, falls keine .env existiert (nutzt dann System-Vars)
|
_ = godotenv.Load()
|
||||||
|
|
||||||
db_management.InitDB()
|
db_management.InitDB()
|
||||||
|
|
||||||
@@ -32,11 +38,12 @@ func main() {
|
|||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
discord.AddHandler(messageCreate)
|
// Handler
|
||||||
|
discord.AddHandler(interactionCreate)
|
||||||
discord.AddHandler(voiceUpdate)
|
discord.AddHandler(voiceUpdate)
|
||||||
|
|
||||||
discord.Identify.Intents = discordgo.IntentsGuildMessages |
|
// Intents
|
||||||
discordgo.IntentsMessageContent |
|
discord.Identify.Intents = discordgo.IntentsGuilds |
|
||||||
discordgo.IntentsGuildVoiceStates
|
discordgo.IntentsGuildVoiceStates
|
||||||
|
|
||||||
err = discord.Open()
|
err = discord.Open()
|
||||||
@@ -44,59 +51,244 @@ func main() {
|
|||||||
log.Fatal("Error opening connection:", err)
|
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)
|
stop := make(chan os.Signal, 1)
|
||||||
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||||
<-stop
|
<-stop
|
||||||
|
|
||||||
// Graceful Shutdown: Alle aktuell aktiven Sessions noch schnell speichern
|
fmt.Println("Speichere aktive Sessions...")
|
||||||
fmt.Println("Speichere aktive Sessions vor dem Beenden...")
|
|
||||||
for uid, start := range startTimes {
|
// 🔥 NEUE Shutdown-Logik (wichtig!)
|
||||||
db_management.SaveSession(uid, int(time.Since(start).Seconds()))
|
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()
|
discord.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
|
func registerCommands(s *discordgo.Session) {
|
||||||
if m.Author.Bot {
|
|
||||||
|
// /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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.Content == "!stats" {
|
switch i.ApplicationCommandData().Name {
|
||||||
totalSeconds := db_management.GetUserStats(m.Author.ID)
|
|
||||||
|
// =====================
|
||||||
|
// /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
|
duration := time.Duration(totalSeconds) * time.Second
|
||||||
|
|
||||||
msg := fmt.Sprintf("📊 **30-Tage Statistik für %s**\nVerbrachte Zeit: `%s`",
|
name := user.GlobalName
|
||||||
m.Author.GlobalName, formatDuration(duration))
|
if name == "" {
|
||||||
s.ChannelMessageSend(m.ChannelID, msg)
|
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) {
|
func voiceUpdate(s *discordgo.Session, v *discordgo.VoiceStateUpdate) {
|
||||||
|
|
||||||
uid := v.UserID
|
uid := v.UserID
|
||||||
|
|
||||||
// User betritt Sprachkanal
|
// =========================
|
||||||
if v.ChannelID != "" {
|
// ❌ Pause Bedingungen
|
||||||
if _, ok := startTimes[uid]; !ok {
|
// =========================
|
||||||
startTimes[uid] = time.Now()
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// User verlässt Sprachkanal (v.ChannelID == "")
|
// =========================
|
||||||
if v.ChannelID == "" {
|
// ▶ Resume (User wieder aktiv)
|
||||||
if start, ok := startTimes[uid]; ok {
|
// =========================
|
||||||
db_management.SaveSession(uid, int(time.Since(start).Seconds()))
|
if v.ChannelID != "" {
|
||||||
delete(startTimes, uid)
|
|
||||||
|
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 {
|
func formatDuration(d time.Duration) string {
|
||||||
h := int(d.Hours())
|
h := int(d.Hours())
|
||||||
m := int(d.Minutes()) % 60
|
m := int(d.Minutes()) % 60
|
||||||
s := int(d.Seconds()) % 60
|
s := int(d.Seconds()) % 60
|
||||||
return fmt.Sprintf("%dh %dm %ds", h, m, s)
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user