bot.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package discordbot
  2. import (
  3. "fmt"
  4. "os"
  5. "sync"
  6. "syscall"
  7. "time"
  8. "github.com/bwmarrin/discordgo"
  9. "github.com/sirupsen/logrus"
  10. )
  11. type Bot struct {
  12. token string
  13. session *discordgo.Session
  14. online bool
  15. running chan os.Signal
  16. slashRouter SlashRouter
  17. }
  18. var logHandler *logrus.Logger
  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) SetLegacyRouter(router *LegacyRouter) {
  29. bot.AddHandler(router.OnMessageCreate)
  30. }
  31. func (bot *Bot) SetSlashEventRouter(slashRouter *SlashRouter) {
  32. bot.slashRouter = *slashRouter
  33. }
  34. func (bot *Bot) Start(wg *sync.WaitGroup) error {
  35. err := bot.session.Open()
  36. if err != nil {
  37. return err
  38. }
  39. err = bot.slashRouter.GenerateCommands(bot.session)
  40. if err != nil {
  41. return err
  42. }
  43. logHandler.Info("The bot has started")
  44. bot.running = make(chan os.Signal, 1)
  45. bot.online = true
  46. go func() {
  47. for {
  48. select {
  49. case <-bot.running:
  50. logHandler.Info("Shutting down the bot")
  51. bot.slashRouter.CleanCommands(bot.session)
  52. bot.session.Close()
  53. logHandler.Info("The bot has gone offline")
  54. bot.online = false
  55. wg.Done()
  56. default:
  57. time.Sleep(time.Second * 1)
  58. }
  59. }
  60. }()
  61. return nil
  62. }
  63. func (bot *Bot) Stop() {
  64. if bot.online {
  65. bot.running <- syscall.SIGINT
  66. }
  67. }
  68. func NewBot(token string, log *logrus.Logger) (*Bot, error) {
  69. bot := &Bot{}
  70. bot.token = token
  71. logHandler = log
  72. var err error
  73. bot.session, err = discordgo.New("Bot " + bot.token)
  74. if err != nil {
  75. return bot, err
  76. }
  77. return bot, nil
  78. }