legacyMessageHandler.go 2.3 KB

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