/
cmd.go
77 lines (63 loc) · 1.61 KB
/
cmd.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
71
72
73
74
75
76
77
package command
import (
"errors"
"github.com/bwmarrin/discordgo"
)
var (
ErrCommandNotFound = errors.New("command not found")
ErrCommandAlreadyExists = errors.New("command already exists")
ErrCommandDoesNotExist = errors.New("command does not exist")
)
type Cmd interface {
Name() string
Match(path []string) bool
Execute(s *discordgo.Session, m *discordgo.MessageCreate, path []string) error
}
type Command struct {
NameCmd func() string
MatchCmd func(path []string) bool
ExecuteCmd func(s *discordgo.Session, m *discordgo.MessageCreate, path []string) error
}
func (c *Command) Name() string {
return c.NameCmd()
}
func (c *Command) Match(path []string) bool {
return c.MatchCmd(path)
}
func (c *Command) Execute(s *discordgo.Session, m *discordgo.MessageCreate, path []string) error {
return c.ExecuteCmd(s, m, path)
}
type CommandGroup struct {
Commands map[string]Cmd
DefaultComnmnd Cmd
MatchCmd func(path []string) bool
NameCmd func() string
}
func (c *CommandGroup) Name() string {
return c.NameCmd()
}
func (c *CommandGroup) Match(path []string) bool {
return c.MatchCmd(path)
}
func (c *CommandGroup) Execute(s *discordgo.Session, m *discordgo.MessageCreate, path []string) error {
next := ""
if len(path) != 0 {
next = path[0]
}
if cmd, ok := c.Commands[next]; ok && cmd != nil {
if cmd.Match(path) {
if len(path) != 0 {
path = path[1:]
}
return cmd.Execute(s, m, path)
}
} else if c.DefaultComnmnd != nil {
if c.DefaultComnmnd.Match(path) {
if len(path) != 0 {
path = path[1:]
}
return cmd.Execute(s, m, path)
}
}
return nil
}