message.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 r.forcePrefixMethod && ctx.Method != PrefixMethod {
  64. return
  65. }
  66. // If this is not a command do nothing
  67. if !isCommand {
  68. return
  69. }
  70. route, fields, args := r.findRoute(ctx.Content, MessageRoute)
  71. if route != nil {
  72. ctx.Fields = fields
  73. ctx.Args = args
  74. route.Run(s, m.Message, ctx)
  75. return
  76. }
  77. r.helpRoute.Run(s, m.Message, ctx)
  78. }