message.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package mux
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. "git.mgmcomp.net/thisnthat/discordgo"
  7. "github.com/Sirupsen/logrus"
  8. )
  9. // OnMessageCreate is a DiscordGo Event Handler function. This must be
  10. // registered using the DiscordGo.Session.AddHandler function. This function
  11. // will receive all Discord messages and parse them for matches to registered
  12. // routes.
  13. func (r *Router) OnMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
  14. logrus.Info("Got message")
  15. var err error
  16. // Ignore all messages created by the Bot account itself
  17. if m.Author.ID == s.State.User.ID {
  18. return
  19. }
  20. // Start building the command context
  21. ctx := &Context{
  22. Content: strings.TrimSpace(m.Content),
  23. }
  24. var channel *discordgo.Channel
  25. channel, err = s.State.Channel(m.ChannelID)
  26. if err != nil {
  27. channel, err = s.Channel(m.ChannelID)
  28. if err != nil {
  29. logrus.Warnf("Failed to get the channel for message: %s", err)
  30. } else {
  31. err = s.State.ChannelAdd(channel)
  32. if err != nil {
  33. logrus.Warnf("Failed to add the channel to the session state: %s", err)
  34. }
  35. }
  36. }
  37. var isDirectMessage bool // The message was received in a direct message
  38. var isCommand bool // The message is intended as a command to the bot
  39. if channel != nil {
  40. if channel.Type == discordgo.ChannelTypeDM {
  41. isDirectMessage = true
  42. isCommand = true
  43. ctx.Method = DirectMethod
  44. }
  45. }
  46. if !isDirectMessage {
  47. reg := regexp.MustCompile(fmt.Sprintf("<@!?(%s)>", s.State.User.ID))
  48. for _, mention := range m.Mentions {
  49. if mention.ID == s.State.User.ID {
  50. // Was the @mention the first part of the string?
  51. if reg.FindStringIndex(ctx.Content)[0] == 0 {
  52. isCommand = true
  53. ctx.Method = MentionMethod
  54. }
  55. ctx.Content = reg.ReplaceAllString(ctx.Content, "")
  56. }
  57. }
  58. // Check to see if the context string starts with the command prefix
  59. if len(r.prefix) > 0 {
  60. // If the content start with the command prefix, then this is intended as a command
  61. if strings.HasPrefix(ctx.Content, r.prefix) {
  62. isCommand = true
  63. ctx.Method = PrefixMethod
  64. // Strip off the command prefix
  65. ctx.Content = strings.TrimPrefix(ctx.Content, r.prefix)
  66. }
  67. }
  68. }
  69. // If this is not a command do nothing
  70. if !isCommand {
  71. return
  72. }
  73. route, fields := r.findRoute(ctx.Content, MessageRoute)
  74. if route != nil {
  75. ctx.Fields = fields
  76. route.Run(s, m.Message, ctx)
  77. return
  78. }
  79. r.helpRoute.Run(s, m.Message, ctx)
  80. }