/
CommandMap.go
107 lines (91 loc) · 2.64 KB
/
CommandMap.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package commandMap
import (
"github.com/Jviguy/SpeedyCmds/command"
"github.com/Jviguy/SpeedyCmds/command/commandGroup"
"github.com/Jviguy/SpeedyCmds/command/ctx"
"github.com/Jviguy/SpeedyCmds/utils"
"github.com/bwmarrin/discordgo"
"strings"
)
type Map struct {
commands map[string]command.Command
groups map[string]commandGroup.Group
}
func (m *Map) RegisterCommandGroup(name string,group commandGroup.Group) {
if !m.DoesGroupExist(name) && m.CanRegisterGroup(name) {
m.groups[name] = group
}
}
func (m *Map) GetGroups() map[string]commandGroup.Group {
return m.groups
}
func (m *Map) GetGroup(name string) commandGroup.Group {
if m.DoesGroupExist(name) {
return m.groups[name]
}
return nil
}
func (m *Map) CanRegisterGroup(name string) bool {
return m.commands[name] == nil && m.GetGroup(name) == nil
}
func (m *Map) DoesGroupExist(name string) bool {
_,b := m.groups[name]
return b
}
func (m *Map) Execute(command string,c ctx.Ctx,s *discordgo.Session) error {
switch true {
case m.CanExecute(command):
return m.commands[strings.ToLower(command)].Execute(c,s)
case m.DoesGroupExist(command):
if len(c.GetArgs()) > 0 {
args,cmd := shift(c.GetArgs(),0)
if m.GetGroup(command).CanExecute(cmd) {
ct := ctx.New(args, c.GetMessage(), s)
//custom ctx for the custom args needed
return m.GetGroup(command).Execute(cmd, ct, s)
}
}
fallthrough
default:
em := discordgo.MessageEmbed{}
em.Title = "Unknown Command: " + command
em.Description = "You might have Meant: " + utils.FindClosest(command, utils.GetAllKeysCommands(m.GetAllCommands()))
_,_ = s.ChannelMessageSendEmbed(c.GetChannel().ID,&em)
return nil
}
}
func (m *Map) GetAllCommands() map[string]command.Command {
cs := m.GetCommands()
for k,g := range m.GetGroups(){
for name,cmd := range g.GetCommands(){
cs[k+" "+name] = cmd
}
}
return cs
}
func (m *Map) RegisterCommand(name string,command command.Command, override bool) {
if m.CanRegisterCommand(name) || override {
m.commands[strings.ToLower(name)] = command
}
}
func (m *Map) CanRegisterCommand(name string) bool {
return m.commands[name] == nil && m.GetGroup(name) == nil
}
func (m *Map) GetCommands() map[string]command.Command {
return m.commands
}
//noinspection ALL
func New() *Map {
return &Map{commands: map[string]command.Command{},groups: map[string]commandGroup.Group{}}
}
func (m *Map) CanExecute(name string) bool {
_, ok := m.commands[name]
return ok
}
func shift(a []string,i int) ([]string,string) {
b := a[i]
copy(a[i:], a[i+1:]) // Shift a[i+1:] left one index.
a[len(a)-1] = "" // Erase last element (write zero value).
a = a[:len(a)-1] // Truncate slice.
return a,b
}