bot.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package discord
  2. import (
  3. "fmt"
  4. "os"
  5. "os/signal"
  6. "sync"
  7. "syscall"
  8. "git.mgmcomp.net/thisnthat/discord/bot/event/mux"
  9. "git.mgmcomp.net/thisnthat/discordgo"
  10. "github.com/sirupsen/logrus"
  11. )
  12. type Bot struct {
  13. token string
  14. session *discordgo.Session
  15. online bool
  16. running chan os.Signal
  17. }
  18. func (bot *Bot) AddHandler(handler interface{}) error {
  19. // If the bot is online, we can not add a handler
  20. if bot.online {
  21. err := fmt.Errorf("unable to add handler to a bot that is already online")
  22. return err
  23. }
  24. bot.session.AddHandler(handler)
  25. return nil
  26. }
  27. func (bot *Bot) SetEventRouter(router *mux.Router) {
  28. bot.AddHandler(router.OnMessageCreate)
  29. }
  30. func (bot *Bot) Start(wg *sync.WaitGroup) error {
  31. defer wg.Done()
  32. err := bot.session.Open()
  33. if err != nil {
  34. return err
  35. }
  36. go logrus.Info("The bot has started")
  37. bot.running = make(chan os.Signal, 1)
  38. bot.online = true
  39. signal.Notify(bot.running, syscall.SIGINT, syscall.SIGTERM)
  40. <-bot.running
  41. bot.session.Close()
  42. go logrus.Info("The bot has gone offline")
  43. bot.online = false
  44. return nil
  45. }
  46. func (bot *Bot) Stop() {
  47. if bot.online {
  48. bot.running <- syscall.SIGINT
  49. }
  50. }
  51. func NewBot(token string) (*Bot, error) {
  52. bot := &Bot{}
  53. bot.token = token
  54. var err error
  55. bot.session, err = discordgo.New("Bot " + bot.token)
  56. if err != nil {
  57. return bot, err
  58. }
  59. return bot, nil
  60. }