package discord import ( "fmt" "os" "os/signal" "sync" "syscall" "git.mgmcomp.net/thisnthat/discord-bot/bot/event/mux" "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" ) type Bot struct { token string session *discordgo.Session online bool running chan os.Signal slashRouter *mux.SlashRouter } func (bot *Bot) AddHandler(handler interface{}) error { // If the bot is online, we can not add a handler if bot.online { err := fmt.Errorf("unable to add handler to a bot that is already online") return err } bot.session.AddHandler(handler) return nil } func (bot *Bot) SetEventRouter(router *mux.Router) { bot.AddHandler(router.OnMessageCreate) } func (bot *Bot) SetSlashEventRouter(slashRouter *mux.SlashRouter) { bot.slashRouter = slashRouter } func (bot *Bot) Start(wg *sync.WaitGroup) error { defer wg.Done() err := bot.session.Open() if err != nil { return err } err = bot.slashRouter.GenerateCommands(bot.session) if err != nil { return err } go logrus.Info("The bot has started") bot.running = make(chan os.Signal, 1) bot.online = true signal.Notify(bot.running, syscall.SIGINT, syscall.SIGTERM) <-bot.running bot.slashRouter.CleanCommands(bot.session) bot.session.Close() go logrus.Info("The bot has gone offline") bot.online = false return nil } func (bot *Bot) Stop() { if bot.online { bot.running <- syscall.SIGINT } } func NewBot(token string) (*Bot, error) { bot := &Bot{} bot.token = token var err error bot.session, err = discordgo.New("Bot " + bot.token) if err != nil { return bot, err } return bot, nil }