message.go 2.2 KB

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