package mux import ( "github.com/bwmarrin/discordgo" "github.com/sirupsen/logrus" ) type SlashRouter struct { registeredCommands []*discordgo.ApplicationCommand commands []*discordgo.ApplicationCommand commandHandlers map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate) guildIDs []string } type SlashRouteOptions struct { Name string // match name that should trigger this route handler Description string // short description of this route Callback SlashHandler Options []*discordgo.ApplicationCommandOption // Array of application command options for the command } // Handler is the function signature required for a message route handler. type SlashHandler func(s *discordgo.Session, i *discordgo.InteractionCreate) func NewSlashRouter() *SlashRouter { r := &SlashRouter{} r.commandHandlers = make(map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate)) return r } func (r *SlashRouter) RegisterGuild(guildID string) { r.guildIDs = append(r.guildIDs, guildID) } func (r *SlashRouter) Register(name string, options SlashRouteOptions) error { if name == "" { return ErrRegisterRouteNameRequired } if options.Callback == nil { return ErrRegisterCallbackRequired } command := discordgo.ApplicationCommand{ Name: name, Description: options.Description, Options: options.Options, } r.commands = append(r.commands, &command) r.commandHandlers[name] = options.Callback return nil } func (r *SlashRouter) GenerateCommands(s *discordgo.Session) error { r.registeredCommands = make([]*discordgo.ApplicationCommand, len(r.commands)) s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) { if h, ok := r.commandHandlers[i.ApplicationCommandData().Name]; ok { h(s, i) } }) for _, guildID := range r.guildIDs { for i, v := range r.commands { logrus.Info(v) cmd, err := s.ApplicationCommandCreate(s.State.User.ID, guildID, v) if err != nil { logrus.Errorf("Cannot create '%v' command: %v", v.Name, err) return err } r.registeredCommands[i] = cmd } } return nil } func (r *SlashRouter) CleanCommands(s *discordgo.Session) error { for _, guildID := range r.guildIDs { for _, v := range r.registeredCommands { err := s.ApplicationCommandDelete(s.State.User.ID, guildID, v.ID) if err != nil { logrus.Errorf("Cannot delete '%v' command: %v", v.Name, err) return err } } } return nil }