This repository has been archived by the owner on Mar 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
arg.go
617 lines (508 loc) · 12.7 KB
/
arg.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
package dcmd
import (
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"github.com/jonas747/dutil"
"strconv"
"strings"
)
// ArgDef represents a argument definition, either a switch or plain arg
type ArgDef struct {
Name string
Switch string
Type ArgType
Help string
Default interface{}
}
type ParsedArg struct {
Def *ArgDef
Value interface{}
Raw *RawArg
}
func (p *ParsedArg) Str() string {
if p.Value == nil {
return ""
}
switch t := p.Value.(type) {
case string:
return t
case int, int32, int64, uint, uint32, uint64:
return strconv.FormatInt(p.Int64(), 10)
default:
return ""
}
}
// TODO: GO-Generate the number ones
func (p *ParsedArg) Int() int {
if p.Value == nil {
return 0
}
switch t := p.Value.(type) {
case int:
return t
case uint:
return int(t)
case int32:
return int(t)
case int64:
return int(t)
case uint32:
return int(t)
case uint64:
return int(t)
default:
return 0
}
}
func (p *ParsedArg) Int64() int64 {
if p.Value == nil {
return 0
}
switch t := p.Value.(type) {
case int:
return int64(t)
case uint:
return int64(t)
case int32:
return int64(t)
case int64:
return t
case uint32:
return int64(t)
case uint64:
return int64(t)
default:
return 0
}
}
func (p *ParsedArg) Bool() bool {
if p.Value == nil {
return false
}
switch t := p.Value.(type) {
case bool:
return t
case int, int32, int64, uint, uint32, uint64:
return p.Int64() > 0
case string:
return t != ""
}
return false
}
func (p *ParsedArg) MemberState() *dstate.MemberState {
if p.Value == nil {
return nil
}
switch t := p.Value.(type) {
case *dstate.MemberState:
return t
case *AdvUserMatch:
return t.Member
}
return nil
}
func (p *ParsedArg) User() *discordgo.User {
if p.Value == nil {
return nil
}
switch t := p.Value.(type) {
case *dstate.MemberState:
return t.DGoUser()
case *AdvUserMatch:
return t.User
}
return nil
}
func (p *ParsedArg) AdvUser() *AdvUserMatch {
if p.Value == nil {
return nil
}
switch t := p.Value.(type) {
case *AdvUserMatch:
return t
}
return nil
}
// NewParsedArgs creates a new ParsedArg slice from defs passed, also filling default values
func NewParsedArgs(defs []*ArgDef) []*ParsedArg {
out := make([]*ParsedArg, len(defs))
for k, _ := range out {
out[k] = &ParsedArg{
Def: defs[k],
Value: defs[k].Default,
}
}
return out
}
// ArgType is the interface argument types has to implement,
type ArgType interface {
// Return true if this argument part matches this type
Matches(def *ArgDef, part string) bool
// Attempt to parse it, returning any error if one occured.
Parse(def *ArgDef, part string, data *Data) (val interface{}, err error)
// Name as shown in help
HelpName() string
}
var (
// Create some convenience instances
Int = &IntArg{}
Float = &FloatArg{}
String = &StringArg{}
User = &UserArg{}
UserReqMention = &UserArg{RequireMention: true}
UserID = &UserIDArg{}
Channel = &ChannelArg{}
AdvUser = &AdvUserArg{EnableUserID: true, EnableUsernameSearch: true, RequireMembership: true}
AdvUserNoMember = &AdvUserArg{EnableUserID: true, EnableUsernameSearch: true}
)
// IntArg matches and parses integer arguments
// If min and max are not equal then the value has to be within min and max or else it will fail parsing
type IntArg struct {
Min, Max int64
}
func (i *IntArg) Matches(def *ArgDef, part string) bool {
_, err := strconv.ParseInt(part, 10, 64)
return err == nil
}
func (i *IntArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
v, err := strconv.ParseInt(part, 10, 64)
if err != nil {
return nil, &InvalidInt{part}
}
// A valid range has been specified
if i.Max != i.Min {
if i.Max < v || i.Min > v {
return nil, &OutOfRangeError{ArgName: def.Name, Got: v, Min: i.Min, Max: i.Max}
}
}
return v, nil
}
func (i *IntArg) HelpName() string {
return "Whole number"
}
// FloatArg matches and parses float arguments
// If min and max are not equal then the value has to be within min and max or else it will fail parsing
type FloatArg struct {
Min, Max float64
}
func (f *FloatArg) Matches(def *ArgDef, part string) bool {
_, err := strconv.ParseFloat(part, 64)
return err == nil
}
func (f *FloatArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
v, err := strconv.ParseFloat(part, 64)
if err != nil {
return nil, &InvalidFloat{part}
}
// A valid range has been specified
if f.Max != f.Min {
if f.Max < v || f.Min > v {
return nil, &OutOfRangeError{ArgName: def.Name, Got: v, Min: f.Min, Max: f.Max, Float: true}
}
}
return v, nil
}
func (f *FloatArg) HelpName() string {
return "Decimal number"
}
// StringArg matches and parses float arguments
type StringArg struct{}
func (s *StringArg) Matches(def *ArgDef, part string) bool { return true }
func (s *StringArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) { return part, nil }
func (s *StringArg) HelpName() string {
return "Text"
}
// UserArg matches and parses user argument, optionally searching for the member if RequireMention is false
type UserArg struct {
RequireMention bool
}
func (u *UserArg) Matches(def *ArgDef, part string) bool {
if u.RequireMention {
return strings.HasPrefix(part, "<@") && strings.HasSuffix(part, ">")
}
// username searches are enabled, any string can be used
return true
}
func (u *UserArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
if strings.HasPrefix(part, "<@") && len(part) > 3 {
// Direct mention
id := part[2 : len(part)-1]
if id[0] == '!' {
// Nickname mention
id = id[1:]
}
parsed, _ := strconv.ParseInt(id, 10, 64)
for _, v := range data.Msg.Mentions {
if parsed == v.ID {
return v, nil
}
}
return nil, &ImproperMention{part}
} else if !u.RequireMention && data.GS != nil {
// Search for username
m, err := FindDiscordMemberByName(data.GS, part)
if m != nil {
return m.DGoUser(), nil
}
return nil, err
}
return nil, &ImproperMention{part}
}
func (u *UserArg) HelpName() string {
if u.RequireMention {
return "User Mention"
}
return "User"
}
func FindDiscordMemberByName(gs *dstate.GuildState, str string) (*dstate.MemberState, error) {
gs.RLock()
defer gs.RUnlock()
lowerIn := strings.ToLower(str)
partialMatches := make([]*dstate.MemberState, 0, 5)
fullMatches := make([]*dstate.MemberState, 0, 5)
for _, v := range gs.Members {
if v == nil {
continue
}
if v.Username == "" {
continue
}
if strings.EqualFold(str, v.Username) || strings.EqualFold(str, v.Nick) {
fullMatches = append(fullMatches, v.Copy())
if len(fullMatches) >= 5 {
break
}
} else if len(partialMatches) < 5 {
if strings.Contains(strings.ToLower(v.Username), lowerIn) {
partialMatches = append(partialMatches, v)
}
}
}
if len(fullMatches) == 1 {
return fullMatches[0].Copy(), nil
}
if len(fullMatches) == 0 && len(partialMatches) == 0 {
return nil, &UserNotFound{dutil.EscapeEveryoneMention(str)}
}
out := ""
for _, v := range fullMatches {
if out != "" {
out += ", "
}
out += "`" + v.Username + "`"
}
for _, v := range partialMatches {
if out != "" {
out += ", "
}
out += "`" + v.Username + "`"
}
if len(fullMatches) > 1 {
return nil, NewSimpleUserError("Too many users with that name, " + out + ". Please re-run the command with a narrower search, mention or ID.")
}
return nil, NewSimpleUserError("Did you mean one of these? " + out + ". Please re-run the command with a narrower search, mention or ID")
}
// UserIDArg matches a mention or a plain id, the user does not have to be a part of the server
// The type of the ID is parsed into a int64
type UserIDArg struct{}
func (u *UserIDArg) Matches(def *ArgDef, part string) bool {
// Check for mention
if strings.HasPrefix(part, "<@") && strings.HasSuffix(part, ">") {
return true
}
// Check for ID
_, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return true
}
return false
}
func (u *UserIDArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
if strings.HasPrefix(part, "<@") && len(part) > 3 {
// Direct mention
id := part[2 : len(part)-1]
if id[0] == '!' {
// Nickname mention
id = id[1:]
}
parsed, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return nil, &ImproperMention{part}
}
return parsed, nil
}
id, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return id, nil
}
return nil, &ImproperMention{part}
}
func (u *UserIDArg) HelpName() string {
return "Mention/ID"
}
// UserIDArg matches a mention or a plain id, the user does not have to be a part of the server
// The type of the ID is parsed into a int64
type ChannelArg struct{}
func (ca *ChannelArg) Matches(def *ArgDef, part string) bool {
// Check for mention
if strings.HasPrefix(part, "<#") && strings.HasSuffix(part, ">") {
return true
}
// Check for ID
_, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return true
}
return false
}
func (ca *ChannelArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
if data.GS == nil {
return nil, nil
}
var cID int64
if strings.HasPrefix(part, "<#") && len(part) > 3 {
// Direct mention
id := part[2 : len(part)-1]
parsed, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return nil, &ImproperMention{part}
}
cID = parsed
} else {
id, err := strconv.ParseInt(part, 10, 64)
if err != nil {
return nil, &ImproperMention{part}
}
cID = id
}
data.GS.RLock()
if c, ok := data.GS.Channels[cID]; ok {
data.GS.RUnlock()
return c, nil
}
data.GS.RUnlock()
return nil, &ImproperMention{part}
}
func (ca *ChannelArg) HelpName() string {
return "Channel"
}
type AdvUserMatch struct {
// Member may not be present if "RequireMembership" is false
Member *dstate.MemberState
// User is always present
User *discordgo.User
}
func (a *AdvUserMatch) UsernameOrNickname() string {
if a.Member != nil {
if a.Member.Nick != "" {
return a.Member.Nick
}
}
return a.User.Username
}
// AdvUserArg is a more advanced version of UserArg and UserIDArg, it will return a AdvUserMatch
type AdvUserArg struct {
EnableUserID bool // Whether to check for user IDS
EnableUsernameSearch bool // Whether to search for usernames
RequireMembership bool // Whether this requires a membership of the server, if set then Member will always be populated
}
func (u *AdvUserArg) Matches(def *ArgDef, part string) bool {
if strings.HasPrefix(part, "<@") && strings.HasSuffix(part, ">") {
return true
}
if u.EnableUserID {
_, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return true
}
}
if u.EnableUsernameSearch {
// username search
return true
}
return false
}
func (u *AdvUserArg) Parse(def *ArgDef, part string, data *Data) (interface{}, error) {
var user *discordgo.User
var ms *dstate.MemberState
// check mention
if strings.HasPrefix(part, "<@") && len(part) > 3 {
user = u.ParseMention(def, part, data)
}
msFailed := false
if user == nil && u.EnableUserID {
// didn't find a match in the previous step
// try userID search
if parsed, err := strconv.ParseInt(part, 10, 64); err == nil {
ms, user = u.SearchID(parsed, data)
if ms == nil {
msFailed = true
}
}
}
if u.EnableUsernameSearch && data.GS != nil && ms == nil && user == nil {
// Search for username
var err error
ms, err = FindDiscordMemberByName(data.GS, part)
if err != nil {
return nil, err
}
}
if ms == nil && user == nil {
return nil, NewSimpleUserError("User/Member not found")
}
if ms != nil && user == nil {
user = ms.DGoUser()
} else if ms == nil && user != nil && !msFailed {
ms, user = u.SearchID(user.ID, data)
}
return &AdvUserMatch{
Member: ms,
User: user,
}, nil
}
func (u *AdvUserArg) SearchID(parsed int64, data *Data) (member *dstate.MemberState, user *discordgo.User) {
if data.GS != nil {
// attempt to fetch member
member = data.GS.MemberCopy(true, parsed)
if member != nil {
return member, member.DGoUser()
}
m, err := data.Session.GuildMember(data.GS.ID, parsed)
if err == nil {
member = dstate.MSFromDGoMember(data.GS, m)
return member, m.User
}
}
if u.RequireMembership {
return nil, nil
}
// fallback to standard user
user, _ = data.Session.User(parsed)
return
}
func (u *AdvUserArg) ParseMention(def *ArgDef, part string, data *Data) (user *discordgo.User) {
// Direct mention
id := part[2 : len(part)-1]
if id[0] == '!' {
// Nickname mention
id = id[1:]
}
parsed, _ := strconv.ParseInt(id, 10, 64)
for _, v := range data.Msg.Mentions {
if parsed == v.ID {
return v
}
}
return nil
}
func (u *AdvUserArg) HelpName() string {
out := "User mention"
if u.EnableUsernameSearch {
out += "/Name"
}
if u.EnableUserID {
out += "/ID"
}
return out
}