-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.lua
executable file
·1926 lines (1856 loc) · 67.6 KB
/
bot.lua
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env lua5.3
setmetatable(_G, { __index = function(_, key)
error("__index on _G: " .. tostring(key))
end, __newindex = function(_, key)
error("__newindex on _G: " .. tostring(key))
end })
math.randomseed(os.time())
local cqueues = require("cqueues")
local discord = require("discord")
local logger = require("logger")
local openssl_rand = require("openssl.rand")
local config = require("config")
local secret_config = require("secret_config")
local basexx = require("basexx")
local http_headers = require("http.headers")
local http_server = require("http.server")
local http_util = require("http.util")
local http_cookie = require("http.cookie")
local http_request = require("http.request")
local lpeg_patterns_uri = require("lpeg_patterns.uri")
local lunajson = require("lunajson")
local powder = require("powder")
local util = require("util")
local db = require("db")
local html_entities = require("htmlEntities")
local history = require("history")
local pcre2 = require("rex_pcre2")
local json_nullv = {}
local WHOISCTX_NAME = "Powder Toy Profile"
local GETRQUSER_NAME = "Get Requesting User"
local command_custom_ids = {
verify = "verify",
setnick = "setnick",
msglog_search_prefix = "msglog_search",
}
assert(openssl_rand.ready())
local guild_members = {}
local subst = util.subst
local log = logger.new(print)
local moderators_str
do
local moderators = {}
for i = 1, #secret_config.mod_role_ids do
table.insert(moderators, subst("<@&$>", secret_config.mod_role_ids[i]))
end
moderators_str = table.concat(moderators, ", ")
end
local dbh = db.handle("tptutilitybot.sqlite3")
local function db_connect(log, duser, tuser, tname)
return dbh:exec(log:sub("connecting duser $ with tuser $ aka $", duser, tuser, tname), [[INSERT INTO connections ("duser", "tuser", "tname", "stale") values (?, ?, ?, 0)]], duser, tuser, tname)
end
local function db_tnameupdate(log, duser, tname)
return dbh:exec(log:sub("updating tname of duser $ to $ and unmarking it stale", duser, tname), [[UPDATE connections SET "stale" = 0, "tname" = ? WHERE "duser" = ?]], tname, duser)
end
local function db_markstale(log, duser)
return dbh:exec(log:sub("marking duser $ stale", duser), [[UPDATE connections SET "stale" = 1 WHERE "duser" = ?]], duser)
end
local function db_whois(log, duser)
return dbh:exec(log:sub("looking up duser $", duser), [[SELECT * FROM connections WHERE "duser" = ?]], duser)
end
local function db_rwhois(log, tuser)
return dbh:exec(log:sub("looking up tuser $", tuser), [[SELECT * FROM connections WHERE "tuser" = ? COLLATE NOCASE]], tuser)
end
local function db_disconnect(log, duser)
return dbh:exec(log:sub("disconnecting duser $", duser), [[DELETE FROM connections WHERE "duser" = ?]], duser)
end
local function db_rdisconnect(log, tuser)
return dbh:exec(log:sub("disconnecting tuser $", tuser), [[DELETE FROM connections WHERE "tuser" = ? COLLATE NOCASE]], tuser)
end
local function db_random_nonstale(log)
return dbh:exec(log:sub("selecting random user"), [[SELECT * FROM connections WHERE "stale" = 0 ORDER BY random() LIMIT 1]])
end
local function array_intersect(arr1, arr2)
for i = 1, #arr1 do
for j = 1, #arr2 do
if arr1[i] == arr2[j] then
return true
end
end
end
end
local ident_token_counter = 0
local ident_tokens = {}
local duser_to_ident_token = {}
local function invalidate_ident_token(log, ident_token)
log("invalidating ident token $", ident_tokens[ident_token].unique)
duser_to_ident_token[ident_tokens[ident_token].user.id] = nil
ident_tokens[ident_token] = nil
end
local function prune_iat_table(tbl, max_age, kill_func)
local to_kill = {}
local now = cqueues.monotime()
for key, value in pairs(tbl) do
if value.iat + max_age < now then
to_kill[key] = true
end
end
for key in pairs(to_kill) do
kill_func(key)
end
end
dbh:exec(log:sub("setting up db"), [[CREATE TABLE IF NOT EXISTS connections(
"duser" STRING NOT NULL,
"tuser" INTEGER NOT NULL,
"tname" STRING NOT NULL,
"stale" BOOLEAN NOT NULL,
unique ("duser"),
unique ("tuser")
)]])
local cli
local function give_role(log, duser)
local log = log:sub("giving managed role to duser $", duser)
local data, errcode, errbody = cli:assign_user_role(secret_config.guild_id, duser, secret_config.managed_role_id)
if not data then
log("failed: status $: $", errcode, errbody)
end
return data, errcode, errbody
end
local function take_role(log, duser)
local log = log:sub("taking managed role from duser $", duser)
local data, errcode, errbody = cli:unassign_user_role(secret_config.guild_id, duser, secret_config.managed_role_id)
if not data then
log("failed: status $: $", errcode, errbody)
end
return data, errcode, errbody
end
local function set_nick(log, duser, nick)
local log = log:sub("setting nick of duser $ to $", duser, nick)
local data, errcode, errbody = cli:set_user_nick(secret_config.guild_id, duser, nick)
if not data then
log("failed: status $: $", errcode, errbody)
end
return data, errcode, errbody
end
local function get_roles(log, duser)
local log = log:sub("getting roles of duser $", duser)
local data, errcode, errbody = cli:get_user_roles(secret_config.guild_id, duser)
if not data then
log("failed: status $: $", errcode, errbody)
end
return data
end
local function get_effective_dname(duser, dname)
local log = log:sub("getting effective dname of duser $", duser)
local nick, errcode, errbody = cli:get_user_nick(secret_config.guild_id, duser)
if nick == nil then
log("failed: status $: $", errcode, errbody)
return nil, errcode, errbody
end
return nick or dname, errcode, errbody
end
local function assert_api_fetch(data, errcode, errbody)
if not data then
error(subst("error: code $: $", errcode, errbody))
end
return data
end
local function discord_response_data(info)
local data = {}
if not info.enable_mentions then
data.allowed_mentions = {
replied_user = false,
parse = util.make_array({}),
}
end
data.content = info.content
data.components = info.components
data.flags = discord.interaction_response_flag.EPHEMERAL
if info.url then
assert(not data.components)
data.components = {
{
type = discord.component.ACTION_ROW,
components = {
{
type = discord.component.BUTTON,
style = discord.component_button.LINK,
url = info.url,
label = info.label,
},
},
},
}
end
return data
end
local function discord_interaction_respond(data, info)
return cli:create_interaction_response(data.id, data.token, {
type = discord.interaction_response.CHANNEL_MESSAGE_WITH_SOURCE,
data = discord_response_data(info),
})
end
local function discord_interaction_followup(token, info)
return cli:create_followup_message(token, discord_response_data(info))
end
local recheck_cache = {}
local function recheck_connection(log, record)
if record then
prune_iat_table(recheck_cache, config.bot.recheck_cache_max_age, function(duser)
log("removing recheck cache entry for duser $: pruned", duser)
recheck_cache[duser] = nil
end)
local log = log:sub("rechecking connection for duser $", record.duser)
if recheck_cache[record.duser] then
log("found recheck cache entry")
else
local tuser, err = powder.fetch_user(record.tname)
if tuser == nil then
log("backend fetch failed: $", err)
elseif tuser == false or tuser.ID ~= record.tuser then
if record.stale == 0 then
local log = log:sub("$ has changed usernames, dropping connection", record.tname)
if guild_members[record.duser] then
local ok, errcode, errbody = cli:create_channel_message(secret_config.verification_id, discord_response_data({
content = subst("<@$> You seem to have changed your username on Powder Toy. Use **/verify** or the button below to verify yourself again.", record.duser),
components = {
{
type = discord.component.ACTION_ROW,
components = {
{
type = discord.component.BUTTON,
style = discord.component_button.PRIMARY,
custom_id = command_custom_ids.verify,
label = "Verify yourself again",
},
},
},
},
enable_mentions = true,
}))
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
db_markstale(log, record.duser)
take_role(log, record.duser)
record.stale = 1
end
else
local log = log:sub("$ has not changed usernames yet", record.tname)
log("creating recheck cache entry for duser $", record.duser)
recheck_cache[record.duser] = {
iat = cqueues.monotime(),
}
end
end
end
return record
end
local command_id_to_info = {}
local add_command, register_commands
do
local data_in = {}
local name_to_info = {}
function add_command(command_data)
local function scrub(tbl, key)
local value = tbl[key]
assert(value ~= nil, "missing to-be-scrubbed key " .. tostring(key))
tbl[key] = nil
return value
end
local can_use = scrub(command_data, "can_use_")
local handler
if command_data.options and command_data.options[1] and command_data.options[1].type == discord.command_option.SUB_COMMAND then
handler = {}
for _, subcommand_data in ipairs(command_data.options) do
handler[subcommand_data.name] = scrub(subcommand_data, "handler_")
end
else
handler = scrub(command_data, "handler_")
end
name_to_info[command_data.name] = {
name = command_data.name,
handler = handler,
can_use = can_use,
}
table.insert(data_in, command_data)
end
function register_commands()
local data_out = assert_api_fetch(cli:set_application_commands(secret_config.guild_id, data_in))
for _, command_data in pairs(data_out) do
command_id_to_info[command_data.id] = name_to_info[command_data.name]
end
end
end
local function appcommand_ping(log, data)
local log = log:sub("appcommand_ping for duser $", data.member.user.id)
local ok, errcode, errbody = discord_interaction_respond(data, {
content = "Pong!" .. (math.random() < 0.001 and " 🍌" or ""),
})
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
add_command({
name = "ping",
description = "Ping the Utility Bot",
options = util.make_array({}),
handler_ = appcommand_ping,
can_use_ = true,
})
local function appcommand_ident(log, data)
local log = log:sub("appcommand_ident for duser $", data.member.user.id)
local record = recheck_connection(log, db_whois(log, data.member.user.id)[1])
local tnameupdate = false
if record then
if record.stale == 1 then
tnameupdate = record.tuser
else
local log = log:sub("duser $ already has a tuser connected", data.member.user.id)
local role_ok = give_role(log, data.member.user.id)
local ok, errcode, errbody
if role_ok then
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Your Powder Toy account is already connected: $", record.tname),
url = subst("$/User.html?Name=$", secret_config.backend_base, record.tname),
label = subst("View $'s Powder Toy profile", record.tname),
})
else
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Your Powder Toy account is already connected, but an error occurred while assigning the <@&$> role. Contact $ for help.", secret_config.managed_role_id, moderators_str),
})
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
return
end
end
if duser_to_ident_token[data.member.user.id] then
local log = log:sub("duser $ already had an ident token, obsoleting", data.member.user.id)
local ok, errcode, errbody = discord_interaction_followup(ident_tokens[duser_to_ident_token[data.member.user.id]].followup, {
content = "This link has been invalidated by your requesting another one.",
})
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
invalidate_ident_token(log:sub("invalidating ident token: obsoleted"), duser_to_ident_token[data.member.user.id])
end
prune_iat_table(ident_tokens, config.bot.ident_token_max_age, function(token)
invalidate_ident_token(log:sub("invalidating ident token for $: pruned", ident_tokens[token].user.id), token)
end)
local ident_token
while true do
ident_token = basexx.to_url64(openssl_rand.bytes(48))
if not ident_tokens[ident_token] then
break
end
end
ident_token_counter = ident_token_counter + 1
ident_tokens[ident_token] = {
user = {
id = data.member.user.id,
username = data.member.user.username,
discriminator = data.member.user.discriminator,
global_name = data.member.user.global_name,
},
iat = cqueues.monotime(),
followup = data.token,
unique = ident_token_counter,
tnameupdate = tnameupdate,
}
if tnameupdate then
log("allocated ident tnameupdate token $ for duser $", ident_tokens[ident_token].unique, data.member.user.id)
else
log("allocated ident connect token $ for duser $", ident_tokens[ident_token].unique, data.member.user.id)
end
duser_to_ident_token[data.member.user.id] = ident_token
local ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Are you ready to connect your Powder Toy account? The link below will expire in $ minutes.", math.ceil(config.bot.ident_token_max_age / 60)),
url = subst("$/ExternalAuth.api?Action=Get&Audience=$&AppToken=$", secret_config.backend_base, secret_config.backend_audience, ident_token),
label = "Connect your Powder Toy account",
})
if not ok then
invalidate_ident_token(log:sub("invalidating ident token: undelivered: code $: $", errcode, errbody), ident_token)
return
end
end
add_command({
name = "verify",
description = "Verify yourself by connecting your Powder Toy account",
options = util.make_array({}),
handler_ = appcommand_ident,
can_use_ = true,
})
local function appcommand_setnick(log, data)
local log = log:sub("appcommand_setnick for duser $", data.member.user.id)
local record = recheck_connection(log, db_whois(log, data.member.user.id)[1])
local ok, errcode, errbody
if record then
local edname = get_effective_dname(data.member.user.id, data.member.user.global_name)
if not edname then
ok, errcode, errbody = discord_interaction_respond(data, {
content = "Your nickname could not be set. Contact " .. moderators_str .. " for help.",
})
elseif edname == record.tname then
log("found duser $ with edname $ == tname $", data.member.user.id, edname, record.tname)
ok, errcode, errbody = discord_interaction_respond(data, {
content = "Your nickname already matches your Powder Toy name.",
})
else
log("found duser $ with edname $ != tname $", data.member.user.id, edname, record.tname)
local set_ok = set_nick(log, data.member.user.id, record.tname)
if set_ok then
ok, errcode, errbody = discord_interaction_respond(data, {
content = "Done.",
})
else
ok, errcode, errbody = discord_interaction_respond(data, {
content = "Your nickname could not be set. Contact " .. moderators_str .. " for help.",
})
end
end
else
log("duser $ not found", data.member.user.id)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Your account has been disconnected, see the message in <#$>.", secret_config.verification_id),
})
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
add_command({
name = "setnick",
description = "Set your Powder Toy name as your nickname",
options = util.make_array({}),
handler_ = appcommand_setnick,
can_use_ = secret_config.user_role_ids,
})
local rquser_events = history.history(config.bot.rquser_max_log)
local function appcommand_getrquser(log, data)
local dmsg = data.data.target_id
local log = log:sub("appcommand_getrquser by duser $ for dmsg $", data.member.user.id, dmsg)
local duser = rquser_events:get(dmsg)
local ok, errcode, errbody
if duser then
log("found dmsg $: requested by duser $", dmsg, duser)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Requested by <@$>.", duser),
})
else
log("dmsg $ not found", dmsg)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Not present in log."),
})
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
add_command({
name = GETRQUSER_NAME,
type = discord.command.MESSAGE,
handler_ = appcommand_getrquser,
can_use_ = secret_config.mod_role_ids,
})
local function appcommand_whois(log, data)
local duser
if data.data.target_id then
duser = data.data.target_id
else
for _, option in pairs(data.data.options) do
if option.name == "duser" then
duser = option.value
end
end
end
local log = log:sub("appcommand_whois by duser $ for duser $", data.member.user.id, duser)
local record = recheck_connection(log, db_whois(log, duser)[1])
local ok, errcode, errbody
if record then
if record.stale == 1 then
log("found duser $: tname was $", duser, record.tname)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("<@$> was $.", duser, record.tname),
})
else
log("found duser $: tname is $", duser, record.tname)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("<@$> is $.", duser, record.tname),
url = subst("$/User.html?Name=$", secret_config.backend_base, record.tname),
label = subst("View $'s Powder Toy profile", record.tname),
})
end
else
log("duser $ not found", duser)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("<@$> has not connected a Powder Toy account.", duser),
})
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
add_command({
name = "whois",
description = "Look up a Powder Toy user based on a Discord user",
options = {
{ name = "duser", description = "Discord user to look for", type = discord.command_option.USER, required = true },
},
handler_ = appcommand_whois,
can_use_ = secret_config.user_role_ids,
})
add_command({
name = WHOISCTX_NAME,
type = discord.command.USER,
handler_ = appcommand_whois,
can_use_ = secret_config.user_role_ids,
})
local function appcommand_identmod_dwhois(log, data)
local duserid
for _, option in pairs(data.data.options[1].options) do
if option.name == "duserid" then
duserid = option.value
end
end
local log = log:sub("appcommand_identmod_dwhois by duser $ for duserid $", data.member.user.id, duserid)
if not duserid:find("^[0-9]+$") then
log("invalid snowflake $", duserid)
local ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("$ does not look like a valid snowflake.", duserid),
})
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
return
end
appcommand_whois(log:sub("entering from dwhois"), {
data = { target_id = duserid },
member = data.member,
id = data.id,
token = data.token,
})
end
local function appcommand_rwhois(log, data)
local tname
for _, option in pairs(data.data.options) do
if option.name == "tname" then
tname = option.value
end
end
local log = log:sub("appcommand_rwhois by duser $ for tname $", data.member.user.id, tname)
local tuser, err = powder.fetch_user(tname)
local ok, errcode, errbody
if tuser == nil then
log("failed to fetch user: $", err)
ok, errcode, errbody = discord_interaction_respond(data, {
content = "Backend error, try again later.",
})
elseif not tuser then
log("no such user")
ok, errcode, errbody = discord_interaction_respond(data, {
content = "No such user.",
})
else
log("user found")
local record = recheck_connection(log, db_rwhois(log, tuser.ID)[1])
if record then
if record.stale == 1 then
log("found tuser $: duser was $", tuser.ID, record.duser)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("$ was <@$>.", tuser.Username, record.duser),
})
else
log("found tuser $: duser is $", tuser.ID, record.duser)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("$ is <@$>.", tuser.Username, record.duser),
})
end
else
log("tuser $ not found", tuser.ID)
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("$ has not connected a Discord account.", tuser.Username),
})
end
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
add_command({
name = "rwhois",
description = "Look up a Discord user based on a Powder Toy user",
options = {
{ name = "tname", description = "Powder Toy user to look for", type = discord.command_option.STRING, required = true },
},
handler_ = appcommand_rwhois,
can_use_ = secret_config.user_role_ids,
})
local message_log = history.history(config.bot.message_log_max_blob_bytes)
local search_session_log = history.history(config.bot.message_log_max_sessions)
local MSGLOG_SEARCH_REVISION_AVAILABLE_LAST = -1
local MSGLOG_SEARCH_REVISION_AVAILABLE_FIRST = -2
local function search_respond(log, data, search_session_id, results, page_index, revision_index, item_index)
local ok, errcode, errbody
if #results == 0 then
ok, errcode, errbody = discord_interaction_respond(data, {
content = "No results.",
})
elseif item_index < 1 or item_index > #results then
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Invalid item index $ into result set of $ items.", item_index, #results),
})
else
local item = results[#results + 1 - item_index]
local revision_available_last = item.value.revision
local revisions = {
[ revision_available_last ] = item.value,
}
local revision_available_first = revision_available_last
while true do
local index = revision_available_first - 1
local revision = message_log:get(item.key .. "/" .. index)
if not revision then
break
end
revisions[index] = revision
revision_available_first = index
end
if revision_index == MSGLOG_SEARCH_REVISION_AVAILABLE_LAST then
revision_index = revision_available_last
end
if revision_index == MSGLOG_SEARCH_REVISION_AVAILABLE_FIRST then
revision_index = revision_available_first
end
local selected_revision = revisions[revision_index]
local result_pages = selected_revision and math.ceil(#selected_revision.content_blob / config.bot.message_log_page_size)
if not selected_revision then
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Invalid revision index $ into set of available revisions $ through $.", revision_index, revision_available_first, revision_available_last),
})
elseif page_index < 1 or page_index > result_pages then
ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Invalid page index $ into result set of $ pages.", page_index, result_pages),
})
else
local page_base = (page_index - 1) * config.bot.message_log_page_size
local blob_page = selected_revision.content_blob:sub(page_base + 1, page_base + config.bot.message_log_page_size)
local mention_strs = {}
for i = 1, #selected_revision.mentions do
table.insert(mention_strs, subst("<@$>", selected_revision.mentions[i]))
end
for i = 1, #selected_revision.mention_roles do
table.insert(mention_strs, subst("<@&$>", selected_revision.mention_roles[i]))
end
if #mention_strs == 0 then
table.insert(mention_strs, "nobody")
end
local mentions_str = table.concat(mention_strs, " ")
local content = {}
table.insert(content, subst("Item $ of $, ", item_index, #results))
if revision_available_first > 1 then
table.insert(content, subst("revision $ of $ through $ available, ", revision_index, revision_available_first, revision_available_last))
else
table.insert(content, subst("revision $ of $, ", revision_index, revision_available_last))
end
if result_pages > 1 then
table.insert(content, subst("page $ of $, ", page_index, result_pages))
end
table.insert(content, subst("$ <t:$:R>, ", selected_revision.status, selected_revision.timestamp))
table.insert(content, subst("from <@$>, ", selected_revision.user.id))
table.insert(content, subst("in <#$>, ", selected_revision.channel))
table.insert(content, subst("mentioning $", mentions_str))
table.insert(content, subst("\n```json\n$\n```", blob_page))
local action_row_components = {}
local function custom_id(page_index, revision_index, item_index)
return table.concat({
command_custom_ids.msglog_search_prefix,
search_session_id,
page_index,
revision_index,
item_index,
}, "/")
end
if page_index < result_pages then
table.insert(action_row_components, {
type = discord.component.BUTTON,
style = discord.component_button.SECONDARY,
custom_id = custom_id(page_index + 1, revision_index, item_index),
label = "Next page",
})
end
if revision_index > revision_available_first then
table.insert(action_row_components, {
type = discord.component.BUTTON,
style = discord.component_button.SECONDARY,
custom_id = custom_id(1, revision_index - 1, item_index),
label = "Previous revision",
})
end
if item_index < #results then
table.insert(action_row_components, {
type = discord.component.BUTTON,
style = discord.component_button.SECONDARY,
custom_id = custom_id(1, MSGLOG_SEARCH_REVISION_AVAILABLE_LAST, item_index + 1),
label = "Next item",
})
end
local components
if #action_row_components > 0 then
action_row_components[1].style = discord.component_button.PRIMARY
components = {
{
type = discord.component.ACTION_ROW,
components = action_row_components,
}
}
end
ok, errcode, errbody = discord_interaction_respond(data, {
content = table.concat(content),
components = components,
})
end
end
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
end
local function appcommand_msglog_search(log, data)
if data.data.custom_id then
local _, search_session_id, page_index, revision_index, item_index = table.unpack(util.split(data.data.custom_id, "/"))
page_index = tonumber(page_index)
revision_index = tonumber(revision_index)
item_index = tonumber(item_index)
local log = log:sub("appcommand_msglog_search by duser $ picking up search session $", data.member.user.id, search_session_id)
local results = search_session_log:get(search_session_id)
if not results then
log("search session expired")
local ok, errcode, errbody = discord_interaction_respond(data, {
content = "Search session has expired, try the slash command.",
})
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
return
end
search_respond(log, data, search_session_id, results, page_index, revision_index, item_index)
return
end
local terms = {}
local supported_terms = {
item = true,
revision = true,
page = true,
created = true,
edited = true,
deleted = true,
channel = true,
sender = true,
mentionee = true,
regex = true,
caseless = true,
multiline = true,
dotall = true,
extended = true,
ungreedy = true,
msgid = true,
}
local term_strs = {}
for _, option in pairs(data.data.options[1].options) do
if supported_terms[option.name] then
terms[option.name] = {
type = option.type,
value = option.value,
}
table.insert(term_strs, subst("$ = $", option.name, option.value))
end
end
local terms_str = #term_strs > 0 and ("terms " .. table.concat(term_strs, ", ")) or "no terms"
local log = log:sub("appcommand_msglog_search by duser $ with $", data.member.user.id, terms_str)
local regex
if terms.regex then
local flags = ""
if (terms.caseless and terms.caseless .value) ~= false then flags = flags .. "i" end
if (terms.multiline and terms.multiline.value) ~= false then flags = flags .. "m" end
if (terms.dotall and terms.dotall .value) ~= false then flags = flags .. "s" end
if (terms.extended and terms.extended .value) == true then flags = flags .. "x" end
if (terms.ungreedy and terms.ungreedy .value) == true then flags = flags .. "U" end
local ok, err = pcall(function()
regex = pcre2.new(terms.regex.value, flags)
end)
if not ok then
log("bad regex")
local ok, errcode, errbody = discord_interaction_respond(data, {
content = subst("Invalid regex: $", err),
})
if not ok then
log("failed to notify user: code $: $", errcode, errbody)
end
return
end
end
local mentionables
if terms.mentionee then
mentionables = { [ terms.mentionee.value ] = true }
local roles
if terms.mentionee.value == data.member.user.id then
log("roles for mentionee discovered in the member field")
roles = data.member.roles
elseif data.data.resolved and data.data.resolved.members and data.data.resolved.members[terms.mentionee.value] then
log("roles for mentionee discovered in the resolved field")
roles = data.data.resolved.members[terms.mentionee.value].roles
elseif data.data.resolved and data.data.resolved.roles and data.data.resolved.roles[terms.mentionee.value] then
log("mentionee is a role")
else
assert(false)
end
if roles then
for i = 1, #roles do
mentionables[roles[i]] = true
end
end
end
local results = {}
for key, value in message_log:all() do
local include = true
if key:find("/") then
include = false
end
if terms.created then include = include and terms.created.value == (value.status == "created") end
if terms.edited then include = include and terms.edited .value == (value.status == "edited") end
if terms.deleted then include = include and terms.deleted.value == (value.status == "deleted") end
if terms.channel then include = include and terms.channel.value == value.channel end
if terms.sender then include = include and terms.sender .value == value.user.id end
if terms.msgid then include = include and terms.msgid .value == key end
if regex then include = include and regex:find(value.content_blob) end
if mentionables then
local found = false
local function check_array(array)
for i = 1, #array do
if mentionables[array[i]] then
found = true
end
end
end
check_array(value.mentions)
check_array(value.mention_roles)
include = include and found
end
if include then
table.insert(results, {
key = key,
value = value,
})
end
end
local search_session_id = basexx.to_url64(openssl_rand.bytes(12))
search_session_log:push(search_session_id, results)
local page_index = terms.page and terms.page .value or 1
local revision_index = terms.revision and terms.revision.value or MSGLOG_SEARCH_REVISION_AVAILABLE_LAST
local item_index = terms.item and terms.item .value or 1
search_respond(log, data, search_session_id, results, page_index, revision_index, item_index)
end
local function appcommand_msglog_whopinged(log, data)
local terms = {
mentionee = {
value = data.member.user.id,
},
created = {
value = false,
},
revision = {
value = MSGLOG_SEARCH_REVISION_AVAILABLE_FIRST,
},
}
local supported_terms = {
channel = true,
mentionee = true,
}
local term_strs = {}
for _, option in pairs(data.data.options[1].options) do
if supported_terms[option.name] then
terms[option.name] = {
value = option.value,
}
table.insert(term_strs, subst("$ = $", option.name, option.value))
end
end
local terms_str = #term_strs > 0 and ("terms " .. table.concat(term_strs, ", ")) or "no terms"
local log = log:sub("appcommand_msglog_whopinged by duser $ with $", data.member.user.id, terms_str)
local forwarded_options = {}
for name, item in pairs(terms) do
table.insert(forwarded_options, {
name = name,
value = item.value,
})
end
appcommand_msglog_search(log:sub("entering from whopinged"), {
data = {
options = {
{
options = forwarded_options,
}
},
resolved = data.data.resolved,
},
member = data.member,
id = data.id,
token = data.token,
})
end
add_command({
name = "msglog",
description = "Moderator command for inspecting the message log",
options = {
{
name = "search",
description = "Search for messages in the log",
type = discord.command_option.SUB_COMMAND,
options = {
{ name = "item" , description = "Item index, starts at and defaults to 1 (most recent) and counts up" , type = discord.command_option.INTEGER },
{ name = "revision" , description = "Revision index, starts at 1 (least recent) and counts up, defaults to the most recent one" , type = discord.command_option.INTEGER },
{ name = "page" , description = subst("Page ($-byte chunk) index, starts at and defaults to 1 and counts up", config.bot.message_log_page_size), type = discord.command_option.INTEGER },
{ name = "created" , description = "Created status, defaults to none" , type = discord.command_option.BOOLEAN },
{ name = "edited" , description = "Edited status, defaults to none" , type = discord.command_option.BOOLEAN },
{ name = "deleted" , description = "Deleted status, defaults to none" , type = discord.command_option.BOOLEAN },
{ name = "channel" , description = "Sent to this channel, defaults to none" , type = discord.command_option.CHANNEL },
{ name = "sender" , description = "Sent by this user, defaults to none" , type = discord.command_option.USER },
{ name = "mentionee", description = "Mentioned this user (either directly or via a role) or role, defaults to none" , type = discord.command_option.MENTIONABLE },
{ name = "regex" , description = "PCRE2 regex to filter content blob with, defaults to none" , type = discord.command_option.STRING },
{ name = "caseless" , description = "PCRE2_CASELESS flag, defaults to true" , type = discord.command_option.BOOLEAN },
{ name = "multiline", description = "PCRE2_MULTILINE flag, defaults to true" , type = discord.command_option.BOOLEAN },
{ name = "dotall" , description = "PCRE2_DOTALL flag, defaults to true" , type = discord.command_option.BOOLEAN },
{ name = "extended" , description = "PCRE2_EXTENDED flag, defaults to false" , type = discord.command_option.BOOLEAN },
{ name = "ungreedy" , description = "PCRE2_UNGREEDY flag, defaults to false" , type = discord.command_option.BOOLEAN },
{ name = "msgid" , description = "Message ID, defaults to none" , type = discord.command_option.STRING },
},
handler_ = appcommand_msglog_search,
},
{
name = "whopinged",
description = "Helps you figure out who pinged you last and then edited or deleted their message",
type = discord.command_option.SUB_COMMAND,
options = {
{ name = "channel" , description = "Sent to this channel, defaults to none" , type = discord.command_option.CHANNEL },
{ name = "mentionee", description = "Mentioned this user (either directly or via a role) or role, defaults to you", type = discord.command_option.MENTIONABLE },
},
handler_ = appcommand_msglog_whopinged,
},
},
can_use_ = secret_config.mod_role_ids,
})
local function appcommand_identmod_connect(log, data)
local duser, tname
local giverole = true
for _, option in pairs(data.data.options[1].options) do
if option.name == "duser" then
duser = option.value
end
if option.name == "tname" then
tname = option.value