bot.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package discord
  2. import (
  3. "fmt"
  4. "os"
  5. "os/signal"
  6. "sync"
  7. "syscall"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/thisnthat-dev/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) Start(wg *sync.WaitGroup) error {
  27. defer wg.Done()
  28. err := bot.session.Open()
  29. if err != nil {
  30. return err
  31. }
  32. logrus.Info("Discord bot has connected")
  33. bot.running = make(chan os.Signal, 1)
  34. bot.online = true
  35. signal.Notify(bot.running, syscall.SIGINT, os.Kill)
  36. <-bot.running
  37. bot.session.Close()
  38. bot.online = false
  39. logrus.Info("Discord bot has been disconnected")
  40. return nil
  41. }
  42. func (bot *Bot) Stop() {
  43. if bot.online {
  44. logrus.Infof("Shutting down Bot")
  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. }