12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 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
- }
|