-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
67 lines (58 loc) · 1.8 KB
/
command.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
package main
import (
"fmt"
"log"
"github.com/bwmarrin/discordgo"
)
type commandElement struct {
*discordgo.ApplicationCommand
Handler func(*discordgo.Session, *discordgo.InteractionCreate)
}
func NewCommandElement(command *discordgo.ApplicationCommand, handler func(*discordgo.Session, *discordgo.InteractionCreate)) *commandElement {
return &commandElement{
ApplicationCommand: command,
Handler: handler,
}
}
type CommandSet map[string]*commandElement
func NewCommandSet() CommandSet {
return make(map[string]*commandElement)
}
func (c *CommandSet) ResisterCommand(s *discordgo.Session, command *discordgo.ApplicationCommand, handler func(*discordgo.Session, *discordgo.InteractionCreate)) error {
cmd, err := s.ApplicationCommandCreate(s.State.User.ID, "", command)
if err != nil {
return fmt.Errorf("error register command(%s): %w", command.Name, err)
}
if cmd == nil {
return fmt.Errorf("can't register command(%s)", command.Name)
}
log.Println("create cmd:", cmd.Name)
(*c)[cmd.Name] = NewCommandElement(cmd, handler)
return nil
}
func (c *CommandSet) DeleteCommands(s *discordgo.Session) error {
log.Println("removing commands...")
var errs []error
for name, cmd := range *c {
log.Println(cmd.ID, cmd.Name)
err := s.ApplicationCommandDelete(s.State.User.ID, "", cmd.ID)
if err != nil {
errs = append(errs, fmt.Errorf("error delete command(%s): %w", name, err))
}
}
if errs != nil {
err := fmt.Errorf("error delete commands")
for _, e := range errs {
err = fmt.Errorf("%w : %w", err, e)
}
return err
}
return nil
}
func (c *CommandSet) ReturnHandler() func(*discordgo.Session, *discordgo.InteractionCreate) {
return func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if cmd, ok := (*c)[i.ApplicationCommandData().Name]; ok {
cmd.Handler(s, i)
}
}
}