-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommand_handler.go
70 lines (59 loc) · 2.21 KB
/
command_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"github.com/bwmarrin/discordgo"
"github.com/lukasl-dev/octave/command"
)
// commandHandler is responsible for handling slash-commands.
type commandHandler struct {
// commands is a map of all the commands that can be called using
// slash-commands.
commands map[string]command.Command
appCmds []*discordgo.ApplicationCommand
}
// newCommandHandler returns a new command handler that is responsible for
// routing slash-commands to the given commands.
func newCommandHandler() *commandHandler {
return &commandHandler{commands: make(map[string]command.Command)}
}
// add registers the given command in the handler.
func (c *commandHandler) add(cmd command.Command) {
c.commands[cmd.Name] = cmd
c.appCmds = append(c.appCmds, &cmd.ApplicationCommand)
}
// create creates all registered commands on the guild whose id is given.
func (c *commandHandler) create(s *discordgo.Session, gID string) error {
_, err := s.ApplicationCommandBulkOverwrite(s.State.User.ID, gID, c.appCmds)
return err
}
// handle processes incoming interaction create events and calls the appropriate
// command.
func (c *commandHandler) handle(s *discordgo.Session, evt *discordgo.InteractionCreate) {
cmd := c.commands[evt.ApplicationCommandData().Name]
if cmd.Name == "" {
return
}
switch {
case evt.Type == discordgo.InteractionApplicationCommandAutocomplete:
c.handleAutocomplete(s, evt, cmd)
case evt.Type == discordgo.InteractionApplicationCommand:
c.handleCommand(s, evt, cmd)
}
}
func (c *commandHandler) handleAutocomplete(s *discordgo.Session, evt *discordgo.InteractionCreate, cmd command.Command) {
var data *discordgo.InteractionResponseData
if cmd.Autocomplete != nil {
data = cmd.Autocomplete(s, evt)
} else {
data = new(discordgo.InteractionResponseData)
}
_ = s.InteractionRespond(evt.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionApplicationCommandAutocompleteResult,
Data: data,
})
}
func (c *commandHandler) handleCommand(s *discordgo.Session, evt *discordgo.InteractionCreate, cmd command.Command) {
_ = s.InteractionRespond(evt.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: cmd.Command(s, evt),
})
}