-
Notifications
You must be signed in to change notification settings - Fork 926
/
util.go
445 lines (354 loc) · 12.2 KB
/
util.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
package commands
import (
"fmt"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/botlabs-gg/yagpdb/v2/bot"
"github.com/botlabs-gg/yagpdb/v2/common"
"github.com/botlabs-gg/yagpdb/v2/lib/dcmd"
"github.com/botlabs-gg/yagpdb/v2/lib/discordgo"
"github.com/botlabs-gg/yagpdb/v2/lib/dstate"
)
type DurationArg struct {
Min, Max time.Duration
}
var _ dcmd.ArgType = (*DurationArg)(nil)
func (d *DurationArg) CheckCompatibility(def *dcmd.ArgDef, part string) dcmd.CompatibilityResult {
if len(part) < 1 {
return dcmd.Incompatible
}
// We "need" the first character to be a number
r, _ := utf8.DecodeRuneInString(part)
if !unicode.IsNumber(r) {
return dcmd.Incompatible
}
_, err := common.ParseDuration(part)
if err != nil {
return dcmd.Incompatible
}
return dcmd.CompatibilityGood
}
func (d *DurationArg) ParseFromMessage(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error) {
dur, err := common.ParseDuration(part)
if err != nil {
return nil, err
}
if d.Min != 0 && d.Min > dur {
return nil, &DurationOutOfRangeError{ArgName: def.Name, Got: dur, Max: d.Max, Min: d.Min}
}
if d.Max != 0 && d.Max < dur {
return nil, &DurationOutOfRangeError{ArgName: def.Name, Got: dur, Max: d.Max, Min: d.Min}
}
return dur, nil
}
func (d *DurationArg) ParseFromInteraction(def *dcmd.ArgDef, data *dcmd.Data, options *dcmd.SlashCommandsParseOptions) (val interface{}, err error) {
s, err := options.ExpectString(def.Name)
if err != nil {
return nil, err
}
dur, err := common.ParseDuration(s)
if err != nil {
return nil, err
}
if d.Min != 0 && d.Min > dur {
return nil, &DurationOutOfRangeError{ArgName: def.Name, Got: dur, Max: d.Max, Min: d.Min}
}
if d.Max != 0 && d.Max < dur {
return nil, &DurationOutOfRangeError{ArgName: def.Name, Got: dur, Max: d.Max, Min: d.Min}
}
return dur, nil
}
func (d *DurationArg) HelpName() string {
return "Duration"
}
func (d *DurationArg) SlashCommandOptions(def *dcmd.ArgDef) []*discordgo.ApplicationCommandOption {
return []*discordgo.ApplicationCommandOption{def.StandardSlashCommandOption(discordgo.ApplicationCommandOptionString)}
}
type DurationOutOfRangeError struct {
Min, Max time.Duration
Got time.Duration
ArgName string
}
func (o *DurationOutOfRangeError) Error() string {
preStr := "too big"
if o.Got < o.Min {
preStr = "too small"
}
if o.Min == 0 {
return fmt.Sprintf("%s is %s, has to be smaller than %s", o.ArgName, preStr, common.HumanizeDuration(common.DurationPrecisionMinutes, o.Max))
} else if o.Max == 0 {
return fmt.Sprintf("%s is %s, has to be bigger than %s", o.ArgName, preStr, common.HumanizeDuration(common.DurationPrecisionMinutes, o.Min))
} else {
format := "%s is %s (has to be within `%s` and `%s`)"
return fmt.Sprintf(format, o.ArgName, preStr, common.HumanizeDuration(common.DurationPrecisionMinutes, o.Min), common.HumanizeDuration(common.DurationPrecisionMinutes, o.Max))
}
}
// PublicError is a error that is both logged and returned as a response
type PublicError string
func (p PublicError) Error() string {
return string(p)
}
func NewPublicError(a ...interface{}) PublicError {
return PublicError(fmt.Sprint(a...))
}
func NewPublicErrorF(f string, a ...interface{}) PublicError {
return PublicError(fmt.Sprintf(f, a...))
}
// UserError is a special error type that is only sent as a response, and not logged
type UserError string
var _ dcmd.UserError = (UserError)("") // make sure it implements this interface
func (ue UserError) Error() string {
return string(ue)
}
func (ue UserError) IsUserError() bool {
return true
}
func NewUserError(a ...interface{}) error {
return UserError(fmt.Sprint(a...))
}
func NewUserErrorf(f string, a ...interface{}) error {
return UserError(fmt.Sprintf(f, a...))
}
func FilterBadInvites(msg string, guildID int64, replacement string) string {
return common.ReplaceServerInvites(msg, guildID, replacement)
}
// CommonContainerNotFoundHandler is a common "NotFound" handler that should be used with dcmd containers
// it ensures that no messages is sent if none of the commands in te container is enabeld
// if "fixedMessage" is empty, then it shows default generated container help
func CommonContainerNotFoundHandler(container *dcmd.Container, fixedMessage string) func(data *dcmd.Data) (interface{}, error) {
return func(data *dcmd.Data) (interface{}, error) {
// Only show stuff if atleast 1 of the commands in the container is enabled
if data.GuildData != nil {
cParentID := data.GuildData.CS.ParentID
ms := data.GuildData.MS
channelOverrides, err := GetOverridesForChannel(data.ChannelID, cParentID, data.GuildData.GS.ID)
if err != nil {
logger.WithError(err).WithField("guild", data.GuildData.GS.ID).Error("failed retrieving command overrides")
return nil, nil
}
chain := []*dcmd.Container{CommandSystem.Root, container}
enabled := false
// make sure that at least 1 command in the container is enabled
for _, v := range container.Commands {
cast := v.Command.(*YAGCommand)
settings, err := cast.GetSettingsWithLoadedOverrides(chain, data.GuildData.GS.ID, channelOverrides)
if err != nil {
logger.WithError(err).WithField("guild", data.GuildData.GS.ID).Error("failed checking if command was enabled")
continue
}
if len(settings.RequiredRoles) > 0 && !common.ContainsInt64SliceOneOf(settings.RequiredRoles, ms.Member.Roles) {
// missing required role
continue
}
if len(settings.IgnoreRoles) > 0 && common.ContainsInt64SliceOneOf(settings.IgnoreRoles, ms.Member.Roles) {
// has ignored role
continue
}
if settings.Enabled {
enabled = true
break
}
}
// no commands enabled, do nothing
if !enabled {
return nil, nil
}
}
if fixedMessage != "" {
return fixedMessage, nil
}
resp := dcmd.GenerateHelp(data, container, &dcmd.StdHelpFormatter{})
if len(resp) > 0 {
return resp[0], nil
}
return nil, nil
}
}
// MemberArg matches a id or mention and returns a MemberState object for the user
type MemberArg struct{}
var _ dcmd.ArgType = (*MemberArg)(nil)
func (ma *MemberArg) CheckCompatibility(def *dcmd.ArgDef, part string) dcmd.CompatibilityResult {
// Check for mention
if strings.HasPrefix(part, "<@") && strings.HasSuffix(part, ">") {
return dcmd.DetermineSnowflakeCompatibility(strings.TrimPrefix(part[2:len(part)-1], "!"))
}
// Check for ID
return dcmd.DetermineSnowflakeCompatibility(part)
}
func (ma *MemberArg) ParseFromMessage(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error) {
id := ma.ExtractID(part, data)
if id < 1 {
return nil, dcmd.NewSimpleUserError("Invalid mention or id")
}
member, err := bot.GetMember(data.GuildData.GS.ID, id)
if err != nil {
if common.IsDiscordErr(err, discordgo.ErrCodeUnknownMember, discordgo.ErrCodeUnknownUser) {
return nil, dcmd.NewSimpleUserError("User not a member of the server")
}
return nil, err
}
return member, nil
}
func (ma *MemberArg) ParseFromInteraction(def *dcmd.ArgDef, data *dcmd.Data, options *dcmd.SlashCommandsParseOptions) (val interface{}, err error) {
member, err := options.ExpectMember(def.Name)
if err != nil {
return nil, err
}
return dstate.MemberStateFromMember(member), nil
}
func (ma *MemberArg) ExtractID(part string, data *dcmd.Data) int64 {
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 -1
}
return parsed
}
id, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return id
}
return -1
}
func (ma *MemberArg) HelpName() string {
return "Member"
}
func (ma *MemberArg) SlashCommandOptions(def *dcmd.ArgDef) []*discordgo.ApplicationCommandOption {
return []*discordgo.ApplicationCommandOption{def.StandardSlashCommandOption(discordgo.ApplicationCommandOptionUser)}
}
type EphemeralOrGuild struct {
Content string
Embed *discordgo.MessageEmbed
}
var _ dcmd.Response = (*EphemeralOrGuild)(nil)
func (e *EphemeralOrGuild) Send(data *dcmd.Data) ([]*discordgo.Message, error) {
switch data.TriggerType {
case dcmd.TriggerTypeSlashCommands:
tmp := &EphemeralOrNone{
Content: e.Content,
Embed: e.Embed,
}
return tmp.Send(data)
default:
send := &discordgo.MessageSend{
Content: e.Content,
Embeds: []*discordgo.MessageEmbed{e.Embed},
AllowedMentions: discordgo.AllowedMentions{},
}
return data.SendFollowupMessage(send, discordgo.AllowedMentions{})
}
}
type EphemeralOrNone struct {
Content string
Embed *discordgo.MessageEmbed
}
var _ dcmd.Response = (*EphemeralOrNone)(nil)
func (e *EphemeralOrNone) Send(data *dcmd.Data) ([]*discordgo.Message, error) {
switch data.TriggerType {
case dcmd.TriggerTypeSlashCommands:
params := &discordgo.WebhookParams{
Content: e.Content,
AllowedMentions: &discordgo.AllowedMentions{},
Flags: 64,
}
if e.Embed != nil {
params.Embeds = []*discordgo.MessageEmbed{e.Embed}
}
// _, err := data.Session.EditOriginalInteractionResponse(common.BotApplication.ID, data.SlashCommandTriggerData.Interaction.Token, &discordgo.EditWebhookMessageRequest{
// Content: "Failed running the command.",
// })
if yc, ok := data.Cmd.Command.(*YAGCommand); ok && !yc.IsResponseEphemeral {
// Yeah so because the original reaction response is not marked as ephemeral, and there's no way to change that, just delete it i guess...
// because otherwise the followup message turns into the original response
err := data.Session.DeleteInteractionResponse(common.BotApplication.ID, data.SlashCommandTriggerData.Interaction.Token)
if err != nil {
return nil, err
}
}
m, err := data.Session.CreateFollowupMessage(common.BotApplication.ID, data.SlashCommandTriggerData.Interaction.Token, params)
// m, err := data.Session.EditOriginalInteractionResponse(common.BotApplication.ID, data.SlashCommandTriggerData.Interaction.Token, params)
// err = data.Session.CreateInteractionResponse(data.SlashCommandTriggerData.Interaction.ID, data.SlashCommandTriggerData.Interaction.Token, &discordgo.InteractionResponse{
// Kind: discordgo.InteractionResponseTypeChannelMessageWithSource,
// Data: &discordgo.InteractionApplicationCommandCallbackData{
// Content: &e.Content,
// Flags: 64,
// },
// })
if err != nil {
return nil, err
}
// return []*discordgo.Message{}, nil
return []*discordgo.Message{m}, nil
default:
return nil, nil
}
}
// RoleArg matches an id or name and returns a discordgo.Role
type RoleArg struct{}
var _ dcmd.ArgType = (*RoleArg)(nil)
func (ra *RoleArg) CheckCompatibility(def *dcmd.ArgDef, part string) dcmd.CompatibilityResult {
// Check for mention
if strings.HasPrefix(part, "<@&") && strings.HasSuffix(part, ">") {
return dcmd.DetermineSnowflakeCompatibility(part[3 : len(part)-1])
}
if part != "" {
// role name can be essentially any string
return dcmd.CompatibilityGood
}
return dcmd.Incompatible
}
func (ra *RoleArg) ParseFromMessage(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error) {
id := ra.ExtractID(part, data)
var idName string
switch t := id.(type) {
case int, int32, int64:
idName = strconv.FormatInt(t.(int64), 10)
case string:
idName = t
default:
idName = ""
}
for _, v := range data.GuildData.GS.Roles {
if v.ID == id {
return &v, nil
} else if v.Name == idName {
return &v, nil
}
}
return nil, dcmd.NewSimpleUserError("Invalid role mention or id")
}
func (ra *RoleArg) ParseFromInteraction(def *dcmd.ArgDef, data *dcmd.Data, options *dcmd.SlashCommandsParseOptions) (val interface{}, err error) {
r, err := options.ExpectRole(def.Name)
return r, err
}
func (ra *RoleArg) SlashCommandOptions(def *dcmd.ArgDef) []*discordgo.ApplicationCommandOption {
return []*discordgo.ApplicationCommandOption{def.StandardSlashCommandOption(discordgo.ApplicationCommandOptionRole)}
}
func (ra *RoleArg) ExtractID(part string, data *dcmd.Data) interface{} {
if strings.HasPrefix(part, "<@&") && len(part) > 3 {
// Direct mention
id := part[3 : len(part)-1]
parsed, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return -1
}
return parsed
}
id, err := strconv.ParseInt(part, 10, 64)
if err == nil {
return id
}
return part
}
func (ra *RoleArg) HelpName() string {
return "Role"
}