bot.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. )
  11. type Bot struct {
  12. token string
  13. session *discordgo.Session
  14. online bool
  15. running chan os.Signal
  16. }
  17. func (bot *Bot) AddHandler(handler interface{}) error {
  18. // If the bot is online, we can not add a handler
  19. if bot.online {
  20. err := fmt.Errorf("Unable to add handler to a bot that is already online")
  21. return err
  22. }
  23. bot.session.AddHandler(handler)
  24. return nil
  25. }
  26. func (bot *Bot) SetEventRouter(router *mux.Router) {
  27. bot.AddHandler(router.OnMessageCreate)
  28. }
  29. func (bot *Bot) Start(wg *sync.WaitGroup) error {
  30. defer wg.Done()
  31. err := bot.session.Open()
  32. if err != nil {
  33. return err
  34. }
  35. bot.running = make(chan os.Signal, 1)
  36. bot.online = true
  37. signal.Notify(bot.running, syscall.SIGINT, os.Kill)
  38. <-bot.running
  39. bot.session.Close()
  40. bot.online = false
  41. return nil
  42. }
  43. func (bot *Bot) Stop() {
  44. if bot.online {
  45. bot.running <- syscall.SIGINT
  46. }
  47. }
  48. func NewBot(token string) (*Bot, error) {
  49. bot := &Bot{}
  50. bot.token = token
  51. var err error
  52. bot.session, err = discordgo.New("Bot " + bot.token)
  53. if err != nil {
  54. return bot, err
  55. }
  56. return bot, nil
  57. }