This repository has been archived by the owner on Nov 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgourd.go
294 lines (242 loc) · 6.69 KB
/
gourd.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package gourd
import (
"github.com/andersfylling/disgord"
"github.com/salmonllama/gourd/internal"
"strings"
)
type Gourd struct {
client *disgord.Client // TODO: Embedded type? BOOK
defaultPrefix string
handler *Handler
ownerId string
keywords map[string]string
}
// Takes a message and decides if it should be treated as a command or not
func (bot *Gourd) processCommand(_ disgord.Session, evt *disgord.MessageCreate) {
msg := evt.Message
messageContent := msg.Content
// Ignore bot users
if msg.Author.Bot {
return
}
// Blacklist checks go here
// Check validity and find the prefix that was used
valid, usedPrefix := usesPrefix(msg, bot.defaultPrefix)
if !valid {
return
}
// Trim the prefix from the message
trimmedMessage := trimPrefix(messageContent, usedPrefix)
// Split the trimmed message into command and command args
commandString, args := separateCommand(trimmedMessage)
// Check that it's actually a command
if len(msg.Content) == 1 {
return
}
// Check if it's an existing command
for _, cmd := range bot.handler.Commands {
for _, alias := range cmd.Aliases {
if alias == strings.ToLower(commandString) {
// Create the command's context
ctx := CommandContext{
Command: cmd,
Prefix: usedPrefix,
Args: args,
CommandString: commandString,
Message: msg,
Client: bot.client,
Gourd: bot,
}
// Check for DM allowance
if cmd.Private == false && ctx.IsPrivate() {
ctx.Reply("This command cannot be used in a DM")
return
}
// Handle argument parsing
// Check if the supplied arguments match the command's required arguments
// TODO: Complete argument parsing. It's not ready, and will be available in a future release.
//isValidArgs, err := parseArgs(args, cmd)
//if err != nil {
// Console.Err(err.Error())
// return
//}
// Check if the user has permission to pass inhibition
if !hasPermission(&ctx) {
// Prevent usage
return
}
// Run the command
cmd.Run(ctx)
}
}
}
}
// usesPrefix checks to see if the message starts with a registered prefix and therefore will trigger the command
func usesPrefix(msg *disgord.Message, prefix string) (bool, string) {
if strings.HasPrefix(msg.Content, prefix) {
return true, prefix
} else {
return false, ""
}
}
// trimPrefix returns the message without the prefix
func trimPrefix(message string, usedPrefix string) string {
m := 0
n := len(usedPrefix)
for i := range message {
if m >= n {
return message[i:]
}
m++
}
return message[:n]
}
// separateCommand splits the message into a command and a slice of command arguments, if present
func separateCommand(message string) (command string, args []string) {
split := strings.Split(message, " ")
command = split[0]
args = removeSpaces(split[1:])
return
}
// parseArgs parses through given arguments for validity
func parseArgs(args []string, command *Command) (bool, error) {
requiredArgs := command.Arguments
if len(requiredArgs) == 0 {
return true, nil
}
if len(args) == 0 && len(requiredArgs) != 0 {
return false, &ArgumentError{Arguments: requiredArgs}
}
for i, reqArg := range requiredArgs {
if reqArg.IsOptional { // Ignore it if the reqArg is optional
continue
}
if reqArg.UseRemainder {
// Remainder must be string? break and return?
return true, nil
}
if reqArg.IsQuoted {
// handle quoted arguments, planned for a later update.
}
if !internal.IsSet(args, i) { // Might need to args[len(args) +1] to add as last element; may overwrite elements
args[i] = reqArg.Default
}
// Parse the types now, I guess
switch reqArg.Type {
case TextArg:
continue
case NumericArg:
if !internal.IsNumeric(args[i]) {
return false, &ArgumentError{Arguments: requiredArgs}
}
case EmojiArg:
// EmojiArg is not implemented yet, and kind of a low priority
}
}
return true, nil
}
func removeSpaces(slice []string) (ret []string) {
for i, s := range slice {
if s != "" {
ret = append(ret, slice[i])
}
}
return
}
func hasPermission(ctx *CommandContext) bool {
inhibitor := ctx.Command.Inhibitor
switch i := inhibitor.(type) {
case NilInhibitor:
return true
case RoleInhibitor:
if ctx.IsPrivate() {
return false
}
r := i.handle(ctx.AuthorMember().Roles)
if r == false && i.Response != nil {
ctx.Reply(i.Response)
}
return r
case PermissionInhibitor:
if ctx.IsPrivate() {
return false
}
guild, err := ctx.Guild()
if err != nil {
Console.Err(err)
}
userPerms, err := ctx.Client.Guild(guild.ID).Member(ctx.Author().ID).GetPermissions()
if err != nil {
Console.Err(err)
}
r := i.handle(userPerms)
if r == false && i.Response != nil {
ctx.Reply(i.Response)
}
return r
case KeywordInhibitor:
r := ctx.Gourd.HasKeyword(ctx.Author().ID.String(), i.Value)
if r == false && i.Response != nil {
ctx.Reply(i.Response)
}
return r
case OwnerInhibitor:
r := ctx.IsAuthorOwner()
if r == false && i.Response != nil {
ctx.Reply(i.Response)
}
return r
default:
return false
}
}
// TODO: Disabled until listener implementation
func registerListeners(client *disgord.Client, listeners ...*Listener) {
panic("Listener modules have not been implemented yet!")
/*for _, l := range listeners {
if len(l.Middlewares) == 0 {
client.On(l.Type, l.OnEvent)
} else {
client.On(l.Type, l.OnEvent)
}
}*/
}
func (bot *Gourd) AddModule(mdl *Module) *Gourd {
bot.handler.AddModule(mdl)
return bot
}
func (bot *Gourd) AddModules(modules ...*Module) *Gourd {
bot.handler.Modules = append(bot.handler.Modules, modules...)
return bot
}
// AddKeyword adds a keyword permission to the given user.
// This keyword is stored in runtime memory and used in the KeywordInhibitor
func (bot *Gourd) AddKeyword(userId string, keyword string) {
bot.keywords[userId] = keyword
}
// HasKeyword checks if the user has the given keyword.
// This is automatically checked by the KeywordInhibitor.
func (bot *Gourd) HasKeyword(userId string, keyword string) bool {
return bot.keywords[userId] == keyword
}
// Connect opens the connection to discord
func (bot *Gourd) Connect() error { // TODO: Add a prefix middleware.
defer bot.client.Gateway().StayConnectedUntilInterrupted()
return nil
}
// New creates a new instance of Gourd
func New(token string, ownerId string, defaultPrefix string) *Gourd {
client := disgord.New(disgord.Config{
BotToken: token,
})
handler := Handler{}
gourd := &Gourd{
client: client,
defaultPrefix: defaultPrefix,
handler: &handler,
ownerId: ownerId,
keywords: make(map[string]string, 0),
}
client.Gateway().MessageCreate(gourd.processCommand)
return gourd
}