12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package discord
- import (
- "fmt"
- "os"
- "os/signal"
- "sync"
- "syscall"
- "git.mgmcomp.net/thisnthat/discord/bot/event/mux"
- "git.mgmcomp.net/thisnthat/discordgo"
- "github.com/sirupsen/logrus"
- )
- type Bot struct {
- token string
- session *discordgo.Session
- online bool
- running chan os.Signal
- }
- 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) Start(wg *sync.WaitGroup) error {
- defer wg.Done()
- err := bot.session.Open()
- 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.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
- }
|