Create discord package and connect/disconnect handlers
This change moves the discord session singleton to the internal/discord package, and implements basic Connect/Disconnect handlers.
This commit is contained in:
parent
5e4662c8b0
commit
bbcf6ef6cf
5 changed files with 93 additions and 24 deletions
64
internal/discord/discord.go
Normal file
64
internal/discord/discord.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package discord
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"gitlab.com/whom/bingobot/internal/logging"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
connected bool
|
||||
s *discordgo.Session
|
||||
}
|
||||
|
||||
var (
|
||||
session *Session
|
||||
|
||||
ErrNotConnected = errors.New("session not connected")
|
||||
)
|
||||
|
||||
func Connect(token string) error {
|
||||
// throw away err because discordgo.New() actually can't return an error.
|
||||
// https://github.com/bwmarrin/discordgo/blob/da9e191069d09e1b467145f5758d9b11cb9cca0d/discord.go#L32
|
||||
s, _ := discordgo.New("Bot " + token)
|
||||
|
||||
session = &Session{
|
||||
s: s,
|
||||
}
|
||||
|
||||
addHandlers()
|
||||
|
||||
err := session.s.Open()
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open discord session: %s", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Close() {
|
||||
err := session.s.Close()
|
||||
|
||||
if err != nil {
|
||||
// don't bubble up this error because we can't do anything about it and
|
||||
// the bot is exiting anyway.
|
||||
logging.Error("could not close discord session gracefully", "type", "error", "error", err)
|
||||
}
|
||||
|
||||
session.connected = false
|
||||
}
|
||||
|
||||
func Connected() bool {
|
||||
return session.connected
|
||||
}
|
||||
|
||||
func User(uid string) (*discordgo.User, error) {
|
||||
if !Connected() {
|
||||
return nil, ErrNotConnected
|
||||
}
|
||||
|
||||
return session.s.User(uid)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue