message.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. err = s.State.ChannelAdd(channel)
  29. if err != nil {
  30. }
  31. }
  32. }
  33. var isDirectMessage bool // The message was received in a direct message
  34. var isCommand bool // The message is intended as a command to the bot
  35. if channel != nil {
  36. if channel.Type == discordgo.ChannelTypeDM {
  37. isDirectMessage = true
  38. isCommand = true
  39. ctx.Method = DirectMethod
  40. }
  41. }
  42. if !isDirectMessage {
  43. reg := regexp.MustCompile(fmt.Sprintf("<@!?(%s)>", s.State.User.ID))
  44. for _, mention := range m.Mentions {
  45. if mention.ID == s.State.User.ID {
  46. // Was the @mention the first part of the string?
  47. if reg.FindStringIndex(ctx.Content)[0] == 0 {
  48. isCommand = true
  49. ctx.Method = MentionMethod
  50. }
  51. ctx.Content = reg.ReplaceAllString(ctx.Content, "")
  52. }
  53. }
  54. // Check to see if the context string starts with the command prefix
  55. if len(r.prefix) > 0 {
  56. // If the content start with the command prefix, then this is intended as a command
  57. if strings.HasPrefix(ctx.Content, r.prefix) {
  58. isCommand = true
  59. ctx.Method = PrefixMethod
  60. // Strip off the command prefix
  61. ctx.Content = strings.TrimPrefix(ctx.Content, r.prefix)
  62. }
  63. }
  64. }
  65. // If this is not a command do nothing
  66. if !isCommand {
  67. return
  68. }
  69. route, fields, args := r.findRoute(ctx.Content, MessageRoute)
  70. if route != nil {
  71. ctx.Fields = fields
  72. ctx.Args = args
  73. route.Run(s, m.Message, ctx)
  74. return
  75. }
  76. r.helpRoute.Run(s, m.Message, ctx)
  77. }