bot.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. "github.com/bwmarrin/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. slashRouter *mux.SlashRouter
  18. }
  19. func (bot *Bot) AddHandler(handler interface{}) error {
  20. // If the bot is online, we can not add a handler
  21. if bot.online {
  22. err := fmt.Errorf("unable to add handler to a bot that is already online")
  23. return err
  24. }
  25. bot.session.AddHandler(handler)
  26. return nil
  27. }
  28. func (bot *Bot) SetEventRouter(router *mux.Router) {
  29. bot.AddHandler(router.OnMessageCreate)
  30. }
  31. func (bot *Bot) SetSlashEventRouter(slashRouter *mux.SlashRouter) {
  32. bot.slashRouter = slashRouter
  33. }
  34. func (bot *Bot) Start(wg *sync.WaitGroup) error {
  35. defer wg.Done()
  36. err := bot.session.Open()
  37. if err != nil {
  38. return err
  39. }
  40. err = bot.slashRouter.GenerateCommands(bot.session)
  41. if err != nil {
  42. return err
  43. }
  44. go logrus.Info("The bot has started")
  45. bot.running = make(chan os.Signal, 1)
  46. bot.online = true
  47. signal.Notify(bot.running, syscall.SIGINT, syscall.SIGTERM)
  48. <-bot.running
  49. bot.slashRouter.CleanCommands(bot.session)
  50. bot.session.Close()
  51. go logrus.Info("The bot has gone offline")
  52. bot.online = false
  53. return nil
  54. }
  55. func (bot *Bot) Stop() {
  56. if bot.online {
  57. bot.running <- syscall.SIGINT
  58. }
  59. }
  60. func NewBot(token string) (*Bot, error) {
  61. bot := &Bot{}
  62. bot.token = token
  63. var err error
  64. bot.session, err = discordgo.New("Bot " + bot.token)
  65. if err != nil {
  66. return bot, err
  67. }
  68. return bot, nil
  69. }