Files
thoughtful-dcbot/commands/commands.go

85 lines
2.4 KiB
Go

package commands
import (
"fmt"
"log"
"strings"
"github.com/bwmarrin/discordgo"
)
type Cmd struct {
Command *discordgo.ApplicationCommand
Handler func(s *discordgo.Session, ic *discordgo.InteractionCreate)
AutocompleteHandler func(s *discordgo.Session, ic *discordgo.InteractionCreate)
}
var (
commandHandlers = map[string]func(s *discordgo.Session, ic *discordgo.InteractionCreate){}
autocompleteHandlers = map[string]func(s *discordgo.Session, ic *discordgo.InteractionCreate){}
)
func getAllCommands() []*Cmd {
return []*Cmd{
newSetupCommand(),
newLogoutCommand(),
newListCommand(),
newDeleteCommand(),
newIdeashowCommand(),
}
}
// RegisterAll registers the application commands with Discord and stores handlers.
func RegisterAll(s *discordgo.Session) error {
// Clean up old commands (optional, but good for dev)
// existing, _ := s.ApplicationCommands(s.State.User.ID, "")
// for _, v := range existing {
// s.ApplicationCommandDelete(s.State.User.ID, "", v.ID)
// }
for _, c := range getAllCommands() {
_, err := s.ApplicationCommandCreate(s.State.User.ID, "", c.Command)
if err != nil {
return fmt.Errorf("creating command %s: %w", c.Command.Name, err)
}
commandHandlers[c.Command.Name] = c.Handler
if c.AutocompleteHandler != nil {
autocompleteHandlers[c.Command.Name] = c.AutocompleteHandler
}
}
log.Println("Commands registered.")
return nil
}
// HandleInteraction routes incoming interaction events to the right handler.
func HandleInteraction(s *discordgo.Session, ic *discordgo.InteractionCreate) {
switch ic.Type {
case discordgo.InteractionApplicationCommand:
name := ic.ApplicationCommandData().Name
if h, ok := commandHandlers[name]; ok {
h(s, ic)
}
case discordgo.InteractionApplicationCommandAutocomplete:
name := ic.ApplicationCommandData().Name
if h, ok := autocompleteHandlers[name]; ok {
h(s, ic)
}
case discordgo.InteractionModalSubmit:
data := ic.ModalSubmitData()
if data.CustomID == "setup_modal" {
handleSetupSubmit(s, ic)
} else if strings.HasPrefix(data.CustomID, "ideashow_add_todo_modal_") {
handleAddTodoSubmit(s, ic)
}
case discordgo.InteractionMessageComponent:
handleComponent(s, ic)
}
}
func handleComponent(s *discordgo.Session, ic *discordgo.InteractionCreate) {
data := ic.MessageComponentData()
if strings.HasPrefix(data.CustomID, "ideashow_") {
handleIdeashowComponent(s, ic)
}
}