2024-11-08 16:26:05 -08:00
|
|
|
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)
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-08 13:40:11 -08:00
|
|
|
registerCommands(session.s)
|
|
|
|
|
|
2024-11-08 16:26:05 -08:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func Close() {
|
2025-01-08 13:40:11 -08:00
|
|
|
deregisterCommands(session.s)
|
2024-11-08 16:26:05 -08:00
|
|
|
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 {
|
2024-11-08 16:33:49 -08:00
|
|
|
return session != nil && session.connected
|
2024-11-08 16:26:05 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func User(uid string) (*discordgo.User, error) {
|
|
|
|
|
if !Connected() {
|
|
|
|
|
return nil, ErrNotConnected
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return session.s.User(uid)
|
|
|
|
|
}
|