From ce43bd58648f27a923468d7458b92a5a3b5ce7af Mon Sep 17 00:00:00 2001 From: Luther Wen Xu Date: Sun, 31 May 2020 11:09:58 +0800 Subject: [PATCH] fix: Keep calm and report panics This prevents random crashes within Milen's code. --- commands/commands.go | 13 +++++++++++++ level/listener.go | 13 +++++++++++++ reactrole/listener.go | 24 ++++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/commands/commands.go b/commands/commands.go index b91776e..bf10f7f 100644 --- a/commands/commands.go +++ b/commands/commands.go @@ -1,6 +1,7 @@ package commands import ( + "fmt" "strings" "github.com/bwmarrin/discordgo" @@ -26,6 +27,18 @@ func Event(dg *discordgo.Session, m *discordgo.MessageCreate) { if m.Author.Bot { return } + + defer func() { + if r := recover(); r != nil { + // Oh crap. We recovered from a panic. + if val, ok := r.(error); ok { + util.ReportError(dg, val) + } else { + util.ReportError(dg, fmt.Errorf("%T: %v", r, r)) + } + } + }() + split := strings.Split(m.Content, " ") prefix := strings.ToLower(split[0]) diff --git a/level/listener.go b/level/listener.go index 8782501..0793255 100644 --- a/level/listener.go +++ b/level/listener.go @@ -1,6 +1,8 @@ package level import ( + "fmt" + "github.com/bwmarrin/discordgo" "gitea.teamortix.com/chanbakjsd/Milen/db" @@ -14,6 +16,17 @@ func Event(dg *discordgo.Session, m *discordgo.MessageCreate) { return } + defer func() { + if r := recover(); r != nil { + // Oh crap. We recovered from a panic. + if val, ok := r.(error); ok { + util.ReportError(dg, val) + } else { + util.ReportError(dg, fmt.Errorf("%T: %v", r, r)) + } + } + }() + prevTime := db.GetLastActive(m.Author.ID) nextTime, err := discordgo.SnowflakeTimestamp(m.ID) if err != nil { diff --git a/reactrole/listener.go b/reactrole/listener.go index 577eb49..2d12cda 100644 --- a/reactrole/listener.go +++ b/reactrole/listener.go @@ -1,6 +1,8 @@ package reactrole import ( + "fmt" + "github.com/bwmarrin/discordgo" "gitea.teamortix.com/chanbakjsd/Milen/db" @@ -8,6 +10,17 @@ import ( ) func EventAdd(dg *discordgo.Session, r *discordgo.MessageReactionAdd) { + defer func() { + if r := recover(); r != nil { + // Oh crap. We recovered from a panic. + if val, ok := r.(error); ok { + util.ReportError(dg, val) + } else { + util.ReportError(dg, fmt.Errorf("%T: %v", r, r)) + } + } + }() + member, err := util.GetMember(dg, r.GuildID, r.UserID) if err != nil { util.ReportError(dg, err) @@ -27,6 +40,17 @@ func EventAdd(dg *discordgo.Session, r *discordgo.MessageReactionAdd) { } func EventRemove(dg *discordgo.Session, r *discordgo.MessageReactionRemove) { + defer func() { + if r := recover(); r != nil { + // Oh crap. We recovered from a panic. + if val, ok := r.(error); ok { + util.ReportError(dg, val) + } else { + util.ReportError(dg, fmt.Errorf("%T: %v", r, r)) + } + } + }() + member, err := util.GetMember(dg, r.GuildID, r.UserID) if err != nil { util.ReportError(dg, err)