-
Notifications
You must be signed in to change notification settings - Fork 927
/
plugin_bot.go
414 lines (334 loc) · 10.5 KB
/
plugin_bot.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
package commands
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"emperror.dev/errors"
"github.com/botlabs-gg/yagpdb/bot"
"github.com/botlabs-gg/yagpdb/bot/eventsystem"
"github.com/botlabs-gg/yagpdb/common"
"github.com/jonas747/dcmd/v4"
"github.com/jonas747/discordgo/v2"
"github.com/jonas747/dstate/v4"
)
var (
CommandSystem *dcmd.System
)
var _ bot.BotInitHandler = (*Plugin)(nil)
var _ bot.BotStopperHandler = (*Plugin)(nil)
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLastLegacy(p, handleMsgCreate, eventsystem.EventMessageCreate)
eventsystem.AddHandlerAsyncLastLegacy(p, handleInteractionCreate, eventsystem.EventInteractionCreate)
// Slash command permissions are currently pretty fucked so can't use them
//
// eventsystem.AddHandlerAsyncLastLegacy(p, p.handleGuildCreate, eventsystem.EventGuildCreate)
// eventsystem.AddHandlerAsyncLastLegacy(p, p.handleDiscordEventUpdateSlashCommandPermissions, eventsystem.EventGuildRoleCreate, eventsystem.EventGuildRoleUpdate, eventsystem.EventChannelCreate)
// pubsub.AddHandler("update_slash_command_permissions", p.handleUpdateSlashCommandsPermissions, nil)
CommandSystem.State = bot.State
dcmd.CustomUsernameSearchFunc = p.customUsernameSearchFunc
// err := clearGlobalCommands()
// if err != nil {
// logger.WithError(err).Errorf("failed clearing all commands")
// }
p.startSlashCommandsUpdater()
}
func (p *Plugin) customUsernameSearchFunc(tracker dstate.StateTracker, gs *dstate.GuildSet, query string) (ms *dstate.MemberState, err error) {
logger.Info("Searching by username: ", query)
members, err := bot.BatchMemberJobManager.SearchByUsername(gs.ID, query)
if err != nil {
if err == bot.ErrTimeoutWaitingForMember {
return nil, &dcmd.UserNotFound{Part: query}
}
return nil, err
}
lowerIn := strings.ToLower(query)
partialMatches := make([]*discordgo.Member, 0, 5)
fullMatches := make([]*discordgo.Member, 0, 5)
// filter out the results
for _, v := range members {
if v == nil {
continue
}
if v.User.Username == "" {
continue
}
if strings.EqualFold(query, v.User.Username) || strings.EqualFold(query, v.Nick) {
fullMatches = append(fullMatches, v)
if len(fullMatches) >= 5 {
break
}
} else if len(partialMatches) < 5 {
if strings.Contains(strings.ToLower(v.User.Username), lowerIn) {
partialMatches = append(partialMatches, v)
}
}
}
if len(fullMatches) == 1 {
return dstate.MemberStateFromMember(fullMatches[0]), nil
}
if len(fullMatches) == 0 && len(partialMatches) == 0 {
return nil, &dcmd.UserNotFound{Part: query}
}
// Show some help output
out := ""
if len(fullMatches)+len(partialMatches) < 10 {
for _, v := range fullMatches {
if out != "" {
out += ", "
}
out += "`" + v.User.Username + "`"
}
for _, v := range partialMatches {
if out != "" {
out += ", "
}
out += "`" + v.User.Username + "`"
}
} else {
return nil, &dcmd.UserNotFound{Part: query}
}
if len(fullMatches) > 1 {
return nil, dcmd.NewSimpleUserError("Too many users with the name: (" + out + ") Please re-run the command with a narrower search, mention or ID.")
}
return nil, dcmd.NewSimpleUserError("Did you mean one of these? (" + out + ") Please re-run the command with a narrower search, mention or ID")
}
func (p *Plugin) StopBot(wg *sync.WaitGroup) {
atomic.StoreInt32(shuttingDown, 1)
startedWaiting := time.Now()
for {
runningcommandsLock.Lock()
n := len(runningCommands)
runningcommandsLock.Unlock()
if n < 1 {
wg.Done()
return
}
if time.Since(startedWaiting) > time.Second*60 {
// timeout
logger.Infof("[commands] timeout waiting for %d commands to finish running (d=%s)", n, time.Since(startedWaiting))
wg.Done()
return
}
logger.Infof("[commands] waiting for %d commands to finish running (d=%s)", n, time.Since(startedWaiting))
time.Sleep(time.Millisecond * 500)
}
}
var helpFormatter = &dcmd.StdHelpFormatter{}
func YAGCommandMiddleware(inner dcmd.RunFunc) dcmd.RunFunc {
return func(data *dcmd.Data) (interface{}, error) {
yc, ok := data.Cmd.Command.(*YAGCommand)
if !ok {
resp, err := inner(data)
// Filter the response
if data.GuildData != nil {
if resp == nil && err != nil {
err = errors.New(FilterResp(err.Error(), data.GuildData.GS.ID).(string))
} else if resp != nil {
resp = FilterResp(resp, data.GuildData.GS.ID)
}
}
return resp, err
}
guildID := int64(0)
if data.GuildData != nil {
guildID = data.GuildData.GS.ID
}
// Lock the command for execution
if !BlockingAddRunningCommand(guildID, data.ChannelID, data.Author.ID, yc, time.Second*60) {
if atomic.LoadInt32(shuttingDown) == 1 {
return &EphemeralOrGuild{Content: yc.Name + ": Bot is restarting, please try again in a couple seconds..."}, nil
}
return &EphemeralOrGuild{Content: yc.Name + ": Gave up trying to run command after 60 seconds waiting for your previous instance of this command to finish"}, nil
}
defer removeRunningCommand(guildID, data.ChannelID, data.Author.ID, yc)
// Check if the user can execute the command
canExecute, resp, settings, err := yc.checkCanExecuteCommand(data)
if err != nil {
yc.Logger(data).WithError(err).Error("An error occured while checking if we could run command")
}
if resp != nil {
if resp.Type == ReasonCooldown && data.TriggerType != dcmd.TriggerTypeSlashCommands && data.GuildData != nil {
if hasPerms, _ := bot.BotHasPermissionGS(data.GuildData.GS, data.GuildData.CS.ID, discordgo.PermissionAddReactions); hasPerms {
common.BotSession.MessageReactionAdd(data.ChannelID, data.TraditionalTriggerData.Message.ID, "⏳")
return nil, nil
}
}
switch resp.Type {
case ReasonBotMissingPerms:
return &EphemeralOrGuild{
Content: "You're unable to run this command:\n> " + resp.Message,
}, nil
default:
return &EphemeralOrNone{
Content: "You're unable to run this command:\n> " + resp.Message,
}, nil
}
}
if !canExecute {
return &EphemeralOrNone{
Content: "You're unable to run this command.",
}, nil
}
if err != nil {
return nil, err
}
data = data.WithContext(context.WithValue(data.Context(), CtxKeyCmdSettings, settings))
err = dcmd.ParseCmdArgs(data)
if err != nil {
if dcmd.IsUserError(err) {
args := helpFormatter.ArgDefs(data.Cmd, data)
switches := helpFormatter.Switches(data.Cmd.Command)
resp := ""
if args != "" {
resp += "```\n" + args + "\n```"
}
if switches != "" {
resp += "```\n" + switches + "\n```"
}
resp = resp + "\nInvalid arguments provided: " + err.Error()
yc.PostCommandExecuted(settings, data, &EphemeralOrGuild{
Content: resp,
}, nil)
return nil, nil
}
return nil, err
}
innerResp, err := inner(data)
// Send the response
yc.PostCommandExecuted(settings, data, innerResp, err)
return nil, nil
}
}
func FilterResp(in interface{}, guildID int64) interface{} {
switch t := in.(type) {
case string:
return FilterBadInvites(t, guildID, "[removed-invite]")
case error:
return FilterBadInvites(t.Error(), guildID, "[removed-invite]")
}
return in
}
func AddRootCommands(p common.Plugin, cmds ...*YAGCommand) {
for _, v := range cmds {
v.Plugin = p
CommandSystem.Root.AddCommand(v, v.GetTrigger())
}
}
func AddRootCommandsWithMiddlewares(p common.Plugin, middlewares []dcmd.MiddleWareFunc, cmds ...*YAGCommand) {
for _, v := range cmds {
v.Plugin = p
CommandSystem.Root.AddCommand(v, v.GetTrigger().SetMiddlewares(middlewares...))
}
}
func handleMsgCreate(evt *eventsystem.EventData) {
m := evt.MessageCreate()
if !bot.IsNormalUserMessage(m.Message) {
// Pls no panicerinos or banerinos self, also ignore webhooks
return
}
abort := false
for _, filterFunc := range MessageFilterFuncs {
if !filterFunc(evt, m.Message) {
abort = true
}
}
if abort {
return
}
prefix := defaultCommandPrefix()
if evt.GS != nil && evt.HasFeatureFlag(featureFlagHasCustomPrefix) {
var err error
prefix, err = GetCommandPrefixRedis(evt.GS.ID)
if err != nil {
logger.WithError(err).WithField("guild", evt.GS.ID).Error("failed fetching command prefix")
}
}
CommandSystem.CheckMessageWtihPrefetchedPrefix(common.BotSession, evt.MessageCreate(), prefix)
// CommandSystem.HandleMessageCreate(common.BotSession, evt.MessageCreate())
}
func GetCommandPrefixBotEvt(evt *eventsystem.EventData) (string, error) {
prefix := defaultCommandPrefix()
if evt.GS != nil && evt.HasFeatureFlag(featureFlagHasCustomPrefix) {
var err error
prefix, err = GetCommandPrefixRedis(evt.GS.ID)
return prefix, err
}
return prefix, nil
}
func (p *Plugin) Prefix(data *dcmd.Data) string {
if data.Source == dcmd.TriggerSourceDM {
return "-"
}
prefix, err := GetCommandPrefixRedis(data.GuildData.GS.ID)
if err != nil {
logger.WithError(err).Error("Failed retrieving commands prefix")
}
return prefix
}
func ensureEmbedLimits(embed *discordgo.MessageEmbed) {
if utf8.RuneCountInString(embed.Description) < 2000 {
return
}
lines := strings.Split(embed.Description, "\n")
firstField := &discordgo.MessageEmbedField{
Name: "Commands",
}
currentField := firstField
for _, v := range lines {
if utf8.RuneCountInString(currentField.Value)+utf8.RuneCountInString(v) >= 2000 {
currentField = &discordgo.MessageEmbedField{
Name: "...",
Value: v + "\n",
}
embed.Fields = append(embed.Fields, currentField)
} else {
currentField.Value += v + "\n"
}
}
embed.Description = firstField.Value
}
func defaultCommandPrefix() string {
defaultPrefix := "-"
if common.Testing {
defaultPrefix = "("
}
return defaultPrefix
}
var cmdPrefix = &YAGCommand{
Name: "Prefix",
Description: "Shows command prefix of the current server, or the specified server",
CmdCategory: CategoryTool,
Arguments: []*dcmd.ArgDef{
{Name: "Server-ID", Type: dcmd.BigInt, Default: 0},
},
RunFunc: func(data *dcmd.Data) (interface{}, error) {
targetGuildID := data.Args[0].Int64()
if targetGuildID == 0 {
targetGuildID = data.GuildData.GS.ID
}
prefix, err := GetCommandPrefixRedis(targetGuildID)
if err != nil {
return nil, err
}
return fmt.Sprintf("Prefix of `%d`: `%s`", targetGuildID, prefix), nil
},
}
func clearGlobalCommands() error {
commands, err := common.BotSession.GetGlobalApplicationCommands(common.BotApplication.ID)
if err != nil {
return err
}
logger.Info("COMMANDS LENGHT: ", len(commands))
for _, v := range commands {
err = common.BotSession.DeleteGlobalApplicationCommand(common.BotApplication.ID, v.ID)
if err != nil {
return err
}
}
logger.Info("DONE")
return nil
}