pepster/commands.go

98 lines
2.4 KiB
Go
Raw Normal View History

2021-07-19 22:06:54 +00:00
package main
import (
"log"
"github.com/bwmarrin/discordgo"
)
const (
DEV_GUILD_ID = "665066008507187220"
)
type Command struct {
Name string
Description string
Options []*CommandOption
Handler CommandHandler
}
type CommandHandler = func(*discordgo.Session, *discordgo.InteractionCreate)
type CommandOption struct {
Type CommandOptionType
Name string
Description string
Required bool
}
type CommandOptionType uint8
const (
CommandOptionSubCommand CommandOptionType = 1
CommandOptionSubCommandGroup CommandOptionType = 2
CommandOptionString CommandOptionType = 3
CommandOptionInteger CommandOptionType = 4
CommandOptionBoolean CommandOptionType = 5
CommandOptionUser CommandOptionType = 6
CommandOptionChannel CommandOptionType = 7
CommandOptionRole CommandOptionType = 8
CommandOptionMentionable CommandOptionType = 9
)
func guildID(global bool) string {
if global {
return ""
} else {
return DEV_GUILD_ID
}
}
func (p *Pepster) registerCommands(commands []Command, global bool) {
handlers := make(map[string]CommandHandler, len(commands))
for _, command := range commands {
convertedOptions := make([]*discordgo.ApplicationCommandOption, len(command.Options))
for i, option := range command.Options {
convertedOptions[i] = &discordgo.ApplicationCommandOption{
Name: option.Name,
Description: option.Description,
Type: discordgo.ApplicationCommandOptionType(option.Type),
Required: option.Required,
}
}
_, err := p.discord.ApplicationCommandCreate(p.config.AppID, guildID(global), &discordgo.ApplicationCommand{
Name: command.Name,
Description: command.Description,
Options: convertedOptions,
})
if err != nil {
log.Println("could not register command", command.Name, ":", err)
continue
}
handlers[command.Name] = command.Handler
}
p.discord.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if handler, ok := handlers[i.ApplicationCommandData().Name]; ok {
handler(s, i)
}
})
}
func (p *Pepster) unregisterAllCommands(global bool) {
commands, _ := p.discord.ApplicationCommands(p.config.AppID, guildID(global))
for _, command := range commands {
p.discord.ApplicationCommandDelete(p.config.AppID, guildID(global), command.ID)
}
}
func (p *Pepster) commandsList() []Command {
return []Command{
p.commandLink(),
}
}