-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbot_commands.lua
More file actions
745 lines (651 loc) · 21.3 KB
/
Copy pathbot_commands.lua
File metadata and controls
745 lines (651 loc) · 21.3 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local client = Bot.Client
local config = Config
local enums = discordia.enums
local MAX_NUMBER_OF_EMBED_FIELDS = 25
local applicationId
client:onceSync("ready", function ()
local info = client:getApplicationInformation()
applicationId = info and info.id or client.user.id
end)
function Bot:BuildUsage(commandTable)
local usage = {}
for k,v in ipairs(commandTable.Args) do
if (v.Optional) then
table.insert(usage, string.format("[%s]", v.Name))
else
table.insert(usage, string.format("<%s>", v.Name))
end
end
return table.concat(usage, " ")
end
function Bot:ParseCommandArgs(member, expectedArgs, args)
local parsers = self.ConfigTypeParameter
local values = {}
local argumentIndex = 1
for argIndex, argData in ipairs(expectedArgs) do
if (not args[argumentIndex]) then
if (not argData.Optional) then
return false, string.format("Missing argument #%d (%s)", argIndex, argData.Name)
end
break
end
local argValue
if (argIndex == #expectedArgs and argumentIndex < #args) then
argValue = table.concat(args, " ", argumentIndex)
else
argValue = args[argumentIndex]
end
local value, err = parsers[argData.Type](argValue, member.guild, argData.Options)
if (value ~= nil) then
values[argIndex] = value
argumentIndex = argumentIndex + 1
elseif (argData.Optional) then
values[argIndex] = nil
-- Do not increment argumentIndex, try to parse it again as the next parameter
else
return false,
string.format("Invalid value for argument %d (%s)%s", argIndex, argData.Name, err and ": " .. err or "")
end
end
return values
end
function Bot:RegisterCommand(values)
local name = string.lower(values.Name)
if (self.Commands[name]) then
error("Command \"" .. name .. " already exists")
end
local subcommands
if (values.Subcommands) then
subcommands = {}
for _, sub in ipairs(values.Subcommands) do
subcommands[sub.Name:lower()] = {
Name = sub.Name:lower(),
Description = sub.Description,
Args = sub.Args or {},
PrivilegeCheck = sub.PrivilegeCheck,
Func = sub.Func
}
end
end
local command = {
Args = values.Args,
Function = values.Func,
Help = values.Help,
Name = name,
PrivilegeCheck = values.PrivilegeCheck,
Silent = values.Silent ~= nil and values.Silent,
BotAware = values.BotAware ~= nil and values.BotAware,
Slash = values.Slash,
ContextMenu = values.ContextMenu,
Subcommands = subcommands,
SlashFunc = values.Slash and values.Slash.Func or values.Func,
ContextMenuFunc = values.ContextMenu and values.ContextMenu.Func or values.Func
}
self.Commands[name] = command
end
function Bot:UnregisterCommand(commandName)
self.Commands[commandName:lower()] = nil
end
Bot.ApplicationCommandIds = {}
local function EncodeDefaultMemberPermissions(permissions)
if (not permissions) then
return nil
end
return string.format("%d", permissions)
end
local function buildOptionsFromArgs(argsList)
local options = {}
for _, argData in ipairs(argsList or {}) do
table.insert(options, {
name = argData.Name:lower(),
description = argData.Description or argData.Name,
type = Bot.ConfigTypeToCommandOptionType[argData.Type],
required = not argData.Optional,
autocomplete = argData.Autocomplete ~= nil or nil
})
end
return options
end
local function CacheKeyForApplicationCommand(guildId, name, commandType)
local kind = commandType == 1 and "slash" or "context"
return guildId .. ":" .. kind .. ":" .. name
end
-- Refreshes Bot.ApplicationCommandIds from Discord instead of trusting the in-memory cache,
-- which is empty right after a bot restart and would otherwise leave stale/renamed commands
-- (e.g. a removed ContextMenu block) registered on Discord forever.
function Bot:RefreshApplicationCommandIdsForGuild(guild, commandNames)
self.Client:info("Refreshing application command ids for guild %s (%d command(s))", guild.id, #commandNames)
local nameSet = {}
for _, name in ipairs(commandNames) do
nameSet[name] = true
end
local existingCommands, err = client._api:getGuildApplicationCommands(applicationId, guild.id)
if (not existingCommands) then
self.Client:error("Failed to fetch existing application commands for guild %s: %s", guild.id, err)
return nil
end
local byName = {}
for _, existing in ipairs(existingCommands) do
if (nameSet[existing.name]) then
self.ApplicationCommandIds[CacheKeyForApplicationCommand(guild.id, existing.name, existing.type)] = existing.id
byName[existing.name] = byName[existing.name] or {}
byName[existing.name][existing.type] = existing.id
end
end
self.Client:info("Found %d existing application command(s) for guild %s", #existingCommands, guild.id)
return byName
end
function Bot:SyncApplicationCommandsForGuild(guild, commandNames)
self.Client:info("Syncing application commands for guild %s: %s", guild.id, table.concat(commandNames, ", "))
local existingByName = self:RefreshApplicationCommandIdsForGuild(guild, commandNames) or {}
for _, name in ipairs(commandNames) do
local commandTable = self.Commands[name]
if (commandTable) then
if (commandTable.Subcommands) then
local options = {}
for _, sub in pairs(commandTable.Subcommands) do
local subOptions = buildOptionsFromArgs(sub.Args)
table.insert(options, {
name = sub.Name,
description = sub.Description or sub.Name,
type = 1,
options = #subOptions > 0 and subOptions or nil
})
end
local payload = {
name = name,
description = type(commandTable.Help) == "function" and commandTable.Help(guild) or commandTable.Help
or name,
type = 1,
options = options
}
local cmd, err = client._api:createGuildApplicationCommand(applicationId, guild.id, payload)
if (cmd) then
self.ApplicationCommandIds[guild.id .. ":slash:" .. name] = cmd.id
self.Client:info("Registered slash command %s (id %s) for guild %s", name, cmd.id, guild.id)
else
self.Client:error("Failed to register slash command %s: %s", name, err)
end
elseif (commandTable.Slash) then
local options = buildOptionsFromArgs(commandTable.Args)
local description = commandTable.Slash.Description
if (type(commandTable.Help) == "function") then
description = description or commandTable.Help(guild)
else
description = description or commandTable.Help
end
local payload = {
name = name,
description = description,
type = 1,
options = #options > 0 and options or nil,
default_member_permissions = EncodeDefaultMemberPermissions(commandTable.Slash.DefaultMemberPermissions)
}
local cmd, err = client._api:createGuildApplicationCommand(applicationId, guild.id, payload)
if (cmd) then
self.ApplicationCommandIds[guild.id .. ":slash:" .. name] = cmd.id
self.Client:info("Registered slash command %s (id %s) for guild %s", name, cmd.id, guild.id)
else
self.Client:error("Failed to register slash command %s: %s", name, err)
end
end
if (commandTable.ContextMenu) then
local menuType = commandTable.ContextMenu.Type == "message" and 3 or 2
local payload = {
name = name,
type = menuType,
default_member_permissions = EncodeDefaultMemberPermissions(commandTable.ContextMenu.DefaultMemberPermissions)
}
local cmd, err = client._api:createGuildApplicationCommand(applicationId, guild.id, payload)
if (cmd) then
self.ApplicationCommandIds[guild.id .. ":context:" .. name] = cmd.id
self.Client:info("Registered context menu command %s (id %s) for guild %s", name, cmd.id, guild.id)
else
self.Client:error("Failed to register context menu command %s: %s", name, err)
end
end
-- Delete any command type Discord still has registered under this name that the
-- current code no longer declares (e.g. a ContextMenu/Slash block that got removed).
local expectedTypes = {}
if (commandTable.Subcommands or commandTable.Slash) then
expectedTypes[1] = true
end
if (commandTable.ContextMenu) then
expectedTypes[commandTable.ContextMenu.Type == "message" and 3 or 2] = true
end
for existingType, existingId in pairs(existingByName[name] or {}) do
if (not expectedTypes[existingType]) then
local success, err = client._api:deleteGuildApplicationCommand(applicationId, guild.id, existingId)
if (success) then
self.ApplicationCommandIds[CacheKeyForApplicationCommand(guild.id, name, existingType)] = nil
self.Client:info(
"Removed orphaned application command %s (type %d) for guild %s", name, existingType, guild.id
)
else
self.Client:error(
"Failed to remove orphaned application command %s (type %d): %s", name, existingType, err
)
end
end
end
end
end
end
function Bot:UnsyncApplicationCommandsForGuild(guild, commandNames)
for _, name in ipairs(commandNames) do
for _, kind in ipairs({ "slash", "context" }) do
local key = guild.id .. ":" .. kind .. ":" .. name
local id = self.ApplicationCommandIds[key]
if (id) then
client._api:deleteGuildApplicationCommand(applicationId, guild.id, id)
self.ApplicationCommandIds[key] = nil
end
end
end
end
local prefixes = {
function (content, guild)
local prefix = Bot:GetGuildPrefix(guild)
return content:startswith(prefix, true) and content:sub(#prefix + 1) or nil
end,
function (content)
local userPing, rest = content:match("<@!?(%d+)>%s*(.+)")
return userPing and userPing == client.user.id and rest or nil
end
}
client:on('messageCreate', function(message)
if (not Bot:IsPublicChannel(message.channel)) then
return
end
local content
for _, func in pairs(prefixes) do
content = func(message.content, message.guild)
if (content) then
break
end
end
if (not content) then
return
end
local commandName, args = content:match("^(%w+)%s*(.*)")
if (not commandName) then
return
end
commandName = commandName:lower()
local commandTable = Bot.Commands[commandName]
if (not commandTable) then
return
end
if (not commandTable.BotAware and message.author.bot) then
return
end
if (commandTable.PrivilegeCheck) then
local success, ret = Bot:ProtectedCall(
"Command " .. commandName .. " privilege check", commandTable.PrivilegeCheck, message.member
)
if (not success) then
message:reply("An error occurred")
return
end
if (not ret) then
print(
string.format(
"%s tried to use command %s on guild %s", message.author.tag, commandName, message.guild.name
)
)
return
end
end
local args, err = Bot:ParseCommandArgs(
message.member, commandTable.Args, string.GetArguments(args, #commandTable.Args)
)
if (not args) then
message:reply(err)
return
end
Bot:ProtectedCall(
"Command " .. commandName, commandTable.Function, message, table.unpack(args, 1, #commandTable.Args)
)
if (commandTable.Silent) then
message:delete()
end
end)
local function getCommands(member)
local commands = {}
for commandName, commandTable in pairs(Bot.Commands) do
local visible = true
if (commandTable.PrivilegeCheck) then
local success, ret = Bot:ProtectedCall(
"Command " .. commandName .. " privilege check", commandTable.PrivilegeCheck, member
)
if (not success or not ret) then
visible = false
end
end
if (visible) then
table.insert(commands, commandTable)
end
end
table.sort(commands, function (a, b) return a.Name < b.Name end)
local commandsFields = {}
for _, commandTable in pairs(commands) do
local helpStr = commandTable.Help or "<none>"
if(type(helpStr) == "function") then -- localization
helpStr = commandTable.Help(member.guild)
end
if commandTable.Args ~= nil then
table.insert(commandsFields, {
name = string.format("**Command: %s**", commandTable.Name),
value = string.format(
"**Description:** %s\n**Usage:** %s %s", helpStr, commandTable.Name, Bot:BuildUsage(commandTable)
)
})
end
end
return commandsFields
end
local function getHelpButtonsComponent(guild, selectedPage, nbPages)
local components = {}
local actionButtons = {
{
type = enums.componentType.button,
custom_id = "help_button_previous_page_" .. selectedPage - 1,
style = enums.buttonStyle.primary,
label = Bot:Format(guild, "BOT_HELP_PREV_BUTTON_LABEL"),
disabled = (selectedPage - 1) < 1 and true or false
},
{
type = enums.componentType.button,
custom_id = "help_button_next_page_" .. selectedPage + 1,
style = enums.buttonStyle.primary,
label = Bot:Format(guild, "BOT_HELP_NEXT_BUTTON_LABEL"),
disabled = (selectedPage + 1) > nbPages and true or false
}
}
table.insert(components, {
type = enums.componentType.actionRow,
components = actionButtons
})
return components
end
local function resolveArgsFromOptions(guild, argsList, options)
local optionsByName = {}
for _, opt in ipairs(options or {}) do
optionsByName[opt.name:lower()] = opt.value
end
local args = {}
for i, argData in ipairs(argsList) do
local raw = optionsByName[argData.Name:lower()]
if (raw == nil) then
if (not argData.Optional) then
return nil, "Missing required argument: " .. argData.Name
end
elseif (argData.Type == Bot.ConfigType.Member) then
args[i] = guild:getMember(raw)
elseif (argData.Type == Bot.ConfigType.User) then
args[i] = Bot:DecodeUser(raw)
elseif (argData.Type == Bot.ConfigType.Duration) then
args[i] = Bot.ConfigTypeParameter[Bot.ConfigType.Duration](tostring(raw), guild)
elseif (argData.Type == Bot.ConfigType.Channel or argData.Type == Bot.ConfigType.Category) then
args[i] = guild:getChannel(raw)
elseif (argData.Type == Bot.ConfigType.Role) then
args[i] = guild:getRole(raw)
else
args[i] = raw
end
end
return args
end
function Bot:DispatchApplicationCommand(interaction)
local guild = interaction.guild
if (not guild) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "This command can only be used in a server.",
flags = enums.interactionResponseFlag.ephemeral
}
})
end
local data = interaction.data
local commandTable = self.Commands[data.name:lower()]
if (not commandTable) then return end
local member = interaction.member
if (commandTable.PrivilegeCheck) then
local success, ret = self:ProtectedCall(
"Command " .. data.name .. " privilege check", commandTable.PrivilegeCheck, member
)
if (not success or not ret) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "You are not authorized to use this command.",
flags = enums.interactionResponseFlag.ephemeral
}
})
end
end
if (commandTable.Subcommands) then
local subOption = data.options and data.options[1]
local sub = subOption and commandTable.Subcommands[subOption.name:lower()]
if (not sub) then return end
if (sub.PrivilegeCheck) then
local success, ret = self:ProtectedCall(
"Command " .. data.name .. " " .. sub.Name .. " privilege check", sub.PrivilegeCheck, member
)
if (not success or not ret) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "You are not authorized to use this command.",
flags = enums.interactionResponseFlag.ephemeral
}
})
end
end
local args, err = resolveArgsFromOptions(guild, sub.Args, subOption.options)
if (not args) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = err,
flags = enums.interactionResponseFlag.ephemeral
}
})
end
return self:ProtectedCall(
"Command " .. data.name .. " " .. sub.Name, sub.Func, interaction, table.unpack(args, 1, #sub.Args)
)
end
local args, func
if (data.target_id) then
if (commandTable.ContextMenu and commandTable.ContextMenu.Type == "message") then
local targetMessage = interaction.channel and interaction.channel:getMessage(data.target_id)
if (not targetMessage) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "Target message not found.",
flags = enums.interactionResponseFlag.ephemeral
}
})
end
args = { targetMessage }
else
local targetMember = guild:getMember(data.target_id)
if (not targetMember) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = "Target is not a member of this server.",
flags = enums.interactionResponseFlag.ephemeral
}
})
end
args = { targetMember }
end
func = commandTable.ContextMenuFunc
else
local err
args, err = resolveArgsFromOptions(guild, commandTable.Args, data.options)
if (not args) then
return interaction:respond({
type = enums.interactionResponseType.channelMessageWithSource,
data = {
content = err,
flags = enums.interactionResponseFlag.ephemeral
}
})
end
func = commandTable.SlashFunc
end
self:ProtectedCall("Command " .. data.name, func, interaction, table.unpack(args, 1, #commandTable.Args))
end
function Bot:DispatchApplicationCommandAutocomplete(interaction)
local guild = interaction.guild
local data = interaction.data
local commandTable = self.Commands[data.name:lower()]
local focused
for _, opt in ipairs(data.options or {}) do
if (opt.focused) then
focused = opt
end
end
local choices = {}
if (guild and commandTable and focused) then
local argData
for _, a in ipairs(commandTable.Args or {}) do
if (a.Name:lower() == focused.name:lower()) then
argData = a
break
end
end
if (argData and argData.Autocomplete) then
local success, ret = self:ProtectedCall(
"Autocomplete " .. data.name, argData.Autocomplete, guild, interaction.member, focused.value or ""
)
if (success and type(ret) == "table") then
choices = ret
if (#choices > 25) then
local clipped = {}
for i = 1, 25 do
clipped[i] = choices[i]
end
choices = clipped
end
end
end
end
interaction:respond({
type = enums.interactionResponseType.applicationCommandAutocompleteResult,
data = { choices = choices }
})
end
client:on("interactionCreate", function (interaction)
if (interaction.type == enums.interactionRequestType.applicationCommand) then
return Bot:DispatchApplicationCommand(interaction)
end
if (interaction.type == enums.interactionRequestType.applicationCommandAutocomplete) then
return Bot:DispatchApplicationCommandAutocomplete(interaction)
end
local guild = interaction.guild
if (not guild) then
return
end
local member = interaction.member
local interactionId = interaction.data.custom_id
if (not interactionId or not string.match(interactionId, "^help_button")) then
return
end
local commandsFields = getCommands(member)
local nbPages = math.floor((#commandsFields - 1) / MAX_NUMBER_OF_EMBED_FIELDS) + 1
local selectedPage = tonumber(string.match(interactionId, "(%d+)$")) or 1
if (selectedPage < 1 or selectedPage > nbPages) then
return
end
local page = {
table.unpack(
commandsFields, ((selectedPage - 1) * MAX_NUMBER_OF_EMBED_FIELDS) + 1,
selectedPage * MAX_NUMBER_OF_EMBED_FIELDS
)
}
interaction.message:update({
components = getHelpButtonsComponent(guild, selectedPage, nbPages),
embed = {
fields = page,
footer = { text = string.format("Page %s/%s", selectedPage, nbPages) }
}
})
interaction:respond({
type = enums.interactionResponseType.updateMessage
})
end)
Bot:RegisterCommand({
Name = "help",
Args = {
{ Name = "command", Type = Bot.ConfigType.String, Optional = true }
},
Silent = false,
Help = function (guild) return Bot:Format(guild, "BOT_HELP_HELP") end,
Func = function (message, commandName)
local member = message.member
local guild = message.guild
local commandsFields = {}
if (commandName) then
commandName = commandName:lower()
local commandTable = Bot.Commands[commandName]
if (not commandTable) then
return
end
if (commandTable.PrivilegeCheck) then
local success, ret = Bot:ProtectedCall(
"Command " .. commandName .. " privilege check", commandTable.PrivilegeCheck, member
)
if (not success) then
message:reply("An error occurred")
return
end
if (not ret) then
print(
string.format(
"%s tried to access command %s via help on guild %s", message.author.tag, commandName,
guild.name
)
)
return
end
end
local helpStr = commandTable.Help or "<none>"
if(type(helpStr) == "function") then -- localization
helpStr = commandTable.Help(guild)
end
table.insert(commandsFields, {
name = string.format("**Command: %s**", commandName),
value = string.format(
"**Description:** %s\n**Usage:** %s %s", helpStr, commandName, Bot:BuildUsage(commandTable)
)
})
else
commandsFields = getCommands(member)
end
-- pagination
local components = {}
if (#commandsFields > MAX_NUMBER_OF_EMBED_FIELDS) then
local nbPages = math.floor((#commandsFields - 1) / MAX_NUMBER_OF_EMBED_FIELDS) + 1
local selectedPage = 1
commandsFields = { table.unpack(commandsFields, 1, MAX_NUMBER_OF_EMBED_FIELDS) }
components = getHelpButtonsComponent(guild, selectedPage, nbPages)
local footer = { text = string.format("Page %s/%s", selectedPage, nbPages) }
end
message:reply({
embed = {
fields = commandsFields,
footer = footer or null
},
components = components
})
end
})