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