slashRouter.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package mux
  2. import (
  3. "github.com/bwmarrin/discordgo"
  4. "github.com/sirupsen/logrus"
  5. )
  6. type SlashRouter struct {
  7. registeredCommands []*discordgo.ApplicationCommand
  8. commands []*discordgo.ApplicationCommand
  9. commandHandlers map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)
  10. guildIDs []string
  11. }
  12. type SlashRouteOptions struct {
  13. Name string // match name that should trigger this route handler
  14. Description string // short description of this route
  15. Callback SlashHandler
  16. Options []*discordgo.ApplicationCommandOption // Array of application command options for the command
  17. }
  18. // Handler is the function signature required for a message route handler.
  19. type SlashHandler func(s *discordgo.Session, i *discordgo.InteractionCreate)
  20. func NewSlashRouter() *SlashRouter {
  21. r := &SlashRouter{}
  22. r.commandHandlers = make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate))
  23. return r
  24. }
  25. func (r *SlashRouter) RegisterGuild(guildID string) {
  26. r.guildIDs = append(r.guildIDs, guildID)
  27. }
  28. func (r *SlashRouter) Register(name string, options SlashRouteOptions) error {
  29. if name == "" {
  30. return ErrRegisterRouteNameRequired
  31. }
  32. if options.Callback == nil {
  33. return ErrRegisterCallbackRequired
  34. }
  35. command := discordgo.ApplicationCommand{
  36. Name: name,
  37. Description: options.Description,
  38. Options: options.Options,
  39. }
  40. r.commands = append(r.commands, &command)
  41. r.commandHandlers[name] = options.Callback
  42. return nil
  43. }
  44. func (r *SlashRouter) GenerateCommands(s *discordgo.Session) error {
  45. r.registeredCommands = make([]*discordgo.ApplicationCommand, len(r.commands))
  46. s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  47. if h, ok := r.commandHandlers[i.ApplicationCommandData().Name]; ok {
  48. h(s, i)
  49. }
  50. })
  51. for _, guildID := range r.guildIDs {
  52. for i, v := range r.commands {
  53. logrus.Info(v)
  54. cmd, err := s.ApplicationCommandCreate(s.State.User.ID, guildID, v)
  55. if err != nil {
  56. logrus.Errorf("Cannot create '%v' command: %v", v.Name, err)
  57. return err
  58. }
  59. r.registeredCommands[i] = cmd
  60. }
  61. }
  62. return nil
  63. }
  64. func (r *SlashRouter) CleanCommands(s *discordgo.Session) error {
  65. for _, guildID := range r.guildIDs {
  66. for _, v := range r.registeredCommands {
  67. err := s.ApplicationCommandDelete(s.State.User.ID, guildID, v.ID)
  68. if err != nil {
  69. logrus.Errorf("Cannot delete '%v' command: %v", v.Name, err)
  70. return err
  71. }
  72. }
  73. }
  74. return nil
  75. }