diff --git a/bolt.go b/bolt.go index b1c80e9..f1a032c 100644 --- a/bolt.go +++ b/bolt.go @@ -4,8 +4,10 @@ import ( "fmt" "log" "os" + "os/signal" "slices" "strings" + "syscall" "time" dg "github.com/bwmarrin/discordgo" @@ -30,7 +32,7 @@ type bolt struct { type Bolt interface { Start() error - Stop() error + stop() error AddCommands(cmd Command) messageHandler(s *dg.Session, msg *dg.MessageCreate) createReply(content, message, channel, guild string) *dg.MessageSend @@ -68,16 +70,32 @@ func New(opts ...Option) *bolt { return b } -// adds command handler and starts the bot +// adds command handler and starts the bot, this is a BLOCKING CALL + +// starts the bot, commands are added and the connection to Discord is opened, this is a BLOCKING +// call and handles safe shutdown of the bot func (b *bolt) Start() error { //register commands and open connection b.AddHandler(b.messageHandler) - return b.Open() + err := b.Open() + if err != nil { + return err + } + + sigChannel := make(chan os.Signal, 1) + signal.Notify(sigChannel, syscall.SIGINT) + <-sigChannel + + if err := b.stop(); err != nil { + return err + } + + return nil } // stops the bot -func (b *bolt) Stop() error { +func (b *bolt) stop() error { return b.Close() }