bot.go 1.4 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. logrus.Info("Discord bot has connected")
  37. bot.running = make(chan os.Signal, 1)
  38. bot.online = true
  39. signal.Notify(bot.running, syscall.SIGINT, os.Kill)
  40. <-bot.running
  41. bot.session.Close()
  42. bot.online = false
  43. logrus.Info("Discord bot has been disconnected")
  44. return nil
  45. }
  46. func (bot *Bot) Stop() {
  47. if bot.online {
  48. logrus.Infof("Shutting down Bot")
  49. bot.running <- syscall.SIGINT
  50. }
  51. }
  52. func NewBot(token string) (*Bot, error) {
  53. bot := &Bot{}
  54. bot.token = token
  55. var err error
  56. bot.session, err = discordgo.New("Bot " + bot.token)
  57. if err != nil {
  58. return bot, err
  59. }
  60. return bot, nil
  61. }