-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ts
3933 lines (3902 loc) · 134 KB
/
main.ts
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
/* eslint-disable no-empty */
/* eslint-disable @typescript-eslint/no-var-requires */
import Discord, { Snowflake, TextChannel } from 'discord.js';
import moment from 'moment';
import { Types as ParserTypes } from './parser_types.js';
import Sentry from '@sentry/node';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
import SentryTypes from '@sentry/types';
import { Model } from 'objection';
import Knex from 'knex';
import KeyValueStore from './kvs.js';
import * as AutoResponders from './autoresponders.js';
import vm from 'vm';
import { setLogLevel, LogBit } from 'logbit';
setLogLevel(
['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR'].indexOf(
(process.env.LOG_LEVEL || 'INFO').toUpperCase()
)
);
const log = new LogBit('Main');
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const adminServerPermissionOverwrites: Array<{
guild: string;
timestamp: number;
}> = [];
const store = new KeyValueStore();
// Initialize knex.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const knex = Knex(
Object.values((await import('./knexfile.mjs')).default)[0] as any
);
// Give the knex instance to objection.
Model.knex(knex);
(await import('dotenv')).config();
import * as Web from './web.js';
Sentry.init({
dsn: process.env.SENTRY_TOKEN,
beforeSend: (event: SentryTypes.Event) => {
if (!process.env.SENTRY_TOKEN) {
console.error(event);
return null; // this drops the event and nothing will be send to sentry
}
return event;
},
});
moment.relativeTimeThreshold('ss', 15);
import parse_duration from 'parse-duration';
import nodefetch from 'node-fetch';
const mutes = await (async () => {
try {
return await import('./submodules/mutes.js');
} catch (e) {
return undefined;
}
})();
const alertchannels = await (async () => {
try {
return await import('./submodules/alertchannels.js');
} catch (e) {
return undefined;
}
})();
const automod = await (async () => {
try {
return await import('./submodules/automod.js');
} catch (e) {
return undefined;
}
})();
import { nanoid } from 'nanoid';
//const numbers = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟'];
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
import * as anonchannels from './anonchannels.js';
import * as util_functions from './util_functions.js';
const doCommandHistory: Map<string, util_functions.ChatGPTMessage[]> =
new Map();
const client = new Discord.Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
intents: 65407,
});
interface MatcherCommand {
command: string;
}
import { Prefix } from './types.js';
import * as Types from './types.js';
import parse from 'parse-duration';
const main_commands = {
title: 'Main Commands',
description: 'All main bot commands',
commands: [
{
name: 'pin',
syntax: 'pin <text: string>',
explanation: 'Allows you to pin something anonymously',
permissions: (msg: Discord.Message) =>
msg.member && msg.member.permissions.has('MANAGE_MESSAGES'),
responder: async (msg: Discord.Message, cmd: { text: string }) => {
// Try to delete the message.
// This can throw an error if the message was already deleted by another bot, so catch that if it does
try {
msg.delete();
} catch (e) {}
try {
// Resend the original message through the bot's account, then pin it
await (await msg.channel.send(cmd.text)).pin();
// Log what was done
await Types.LogChannel.tryToLog(
msg,
`Pinned \n> ${cmd.text}\n to ${msg.channel}`
);
} catch (e) {
throw new util_functions.BotError(
'user',
'Failed to pin: ' + e.toString().replace('DiscordAPIError: ', '')
);
}
},
},
{
name: 'eval',
syntax: 'eval <code: string>',
explanation: 'Run code',
version: 2,
permissions: (msg: Discord.Message) =>
msg.author.id === '234020040830091265' && msg.member,
responder: async (ctx: Types.Context, cmd: { code: string }) => {
// This is done to allow accessing discord even in compiled TS where it will be renamed
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const discord = Discord;
try {
// Define a function for cloning users that can be called from inside eval-ed code
const cloneUser = async (user: string, text: string) => {
if (ctx.msg.guild !== null) {
const uuser = ctx.msg.guild.members.cache.get(user as Snowflake);
if (!uuser) throw new Error('User not found');
const loghook = await (
ctx.msg.channel as TextChannel
).createWebhook(uuser.displayName, {
avatar: uuser.user.displayAvatarURL().replace('webp', 'png'),
});
await loghook.send(text);
await loghook.delete();
await ctx.msg.delete();
}
};
if (!cloneUser) return;
// Remove markdown code formatting from the input
let code = cmd.code;
if (code.startsWith('```js')) code = code.substring(5);
if (code.startsWith('```javascript')) code = code.substring(13);
if (code.startsWith('```')) code = code.substring(3);
if (code.startsWith('`')) code = code.substring(1);
if (code.endsWith('```')) code = code.slice(0, -3);
if (code.endsWith('`')) code = code.slice(0, -1);
let wrappedCode = '';
// Detect what type of arrow function needs to be used
try {
// Try to compile function without braces
vm.compileFunction(`(async () => ${code})`);
// If it succeeds, set the final code to be run without braces to remove the need for return statements
wrappedCode = `(async () => ${code})`;
} catch (e) {
// If it fails, set the final code to be run with braces
wrappedCode = `(async () => {${code}})`;
}
log.debug(`Wrapped code: ${wrappedCode}`);
// Define arrow function with eval
const func = eval(wrappedCode);
// Run created arrow function
let funcResult;
try {
funcResult = await func();
} catch (e) {
ctx.msg.channel.send(
util_functions.embed(
util_functions.truncate(e.toString(), 4096),
'warning'
)
);
return;
}
log.debug(`Function result: ${JSON.stringify(funcResult, null, 2)}`);
if (funcResult)
await ctx.msg.channel.send(
util_functions.embed(
'```json\n' +
util_functions.truncate(
JSON.stringify(funcResult, null, 2),
4096 - 11
) +
'```',
'success'
)
);
else await ctx.msg.channel.send(util_functions.embed('', 'success'));
} catch (e) {
throw new util_functions.BotError('user', e.toString());
}
},
},
{
name: 'do',
syntax: 'do <text: string>',
explanation: 'Do anything in the server',
version: 2,
permissions: (msg: Discord.Message) =>
msg.author.id === '234020040830091265' && msg.member,
responder: async (ctx: Types.Context, cmd: { text: string }) => {
// This is done to allow accessing discord even in compiled TS where it will be renamed
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const discord = Discord;
const guild = ctx.msg.guild;
const channel = ctx.msg.channel;
const msg = ctx.msg;
try {
await ctx.msg.channel.sendTyping();
const replyTo = ctx.msg.reference?.messageId;
log.debug(`Reply to: ${replyTo}`);
const history = doCommandHistory.get(replyTo || '') || [];
log.debug(`History: ${JSON.stringify(history, null, 2)}`);
const initialQuery: util_functions.ChatGPTMessage[] = [
{
role: 'system',
content: `You are a code assistant. You will exclusively respond with a single code block and no other commentary. You will write only JavaScript code. The user will give you a task, and you will write the code to complete that task. Your code runs inside of a async block and can use \`await\`. You are writing code that uses the Discord.JS library. You have access to the following variables:
\`discord\`: The core Discord.JS library import
\`msg\`: A Discord.JS \`Message\` object of the user's message
\`channel\`: A Discord.JS \`Channel\` object of the channel of the user's message
\`guild\`: A Discord.JS \`Guild\` object of the guild the user is in.
Your code must eventually return a string, which will be shown to the user.`,
},
...(history.length
? [
{
role: 'user',
content:
'CHAT HISTORY:\n' +
history
.map((m) => `${m.role.toUpperCase()}: ${m.content}`)
.join('\n'),
} as util_functions.ChatGPTMessage,
]
: []),
{
role: 'user',
content: cmd.text,
},
];
log.debug(`Initial query: ${JSON.stringify(initialQuery, null, 2)}`);
let code = (
await util_functions.queryChatGPT(initialQuery, {
model: 'gpt-4',
temp: 0.4,
})
).content;
log.debug(`ChatGPT generated code: ${JSON.stringify(code, null, 2)}`);
// Remove markdown code formatting from the input
if (code.startsWith('```js')) code = code.substring(5);
if (code.startsWith('```javascript')) code = code.substring(13);
if (code.startsWith('```')) code = code.substring(3);
if (code.startsWith('`')) code = code.substring(1);
if (code.endsWith('```')) code = code.slice(0, -3);
if (code.endsWith('`')) code = code.slice(0, -1);
const wrappedCode = `(async () => {${code}})`;
log.debug(`Wrapped code: ${wrappedCode}`);
// Define arrow function with eval
const func = eval(wrappedCode);
// Run created arrow function
let funcResult;
try {
funcResult = await func();
} catch (e) {
ctx.msg.channel.send(
util_functions.embed(
util_functions.truncate(e.toString(), 4096),
'warning'
)
);
return;
}
log.debug(`Function result: ${JSON.stringify(funcResult, null, 2)}`);
let responseMessage;
if (funcResult)
responseMessage = await ctx.msg.channel.send(
util_functions.embed(funcResult, 'success')
);
else
responseMessage = await ctx.msg.channel.send(
util_functions.embed('', 'success')
);
const newHistory: util_functions.ChatGPTMessage[] = [
...history,
{ role: 'user', content: cmd.text },
{ role: 'assistant', content: funcResult },
];
doCommandHistory.set(responseMessage.id, newHistory);
} catch (e) {
throw new util_functions.BotError('user', e.toString());
}
},
},
{
name: 'say',
syntax: 'say [channel: channel] <keep: "keep" | "remove"> <text: string>',
explanation: 'Make the bot say something in a channel',
permissions: (msg: Discord.Message) =>
(msg.member && msg.member.permissions.has('MANAGE_MESSAGES')) ||
msg.author.id === '234020040830091265',
version: 3,
responder: async (
ctx: Types.Context,
cmd: {
channel?: Discord.TextChannel;
keep: 'keep' | 'remove';
text: string;
}
) => {
// If channel isn't a text channel, we can't send messages there, so throw an error
if (
(cmd.channel || ctx.msg.channel).type !== 'GUILD_TEXT' &&
(cmd.channel || ctx.msg.channel).type !== 'GUILD_PRIVATE_THREAD' &&
(cmd.channel || ctx.msg.channel).type !== 'GUILD_PUBLIC_THREAD'
)
throw new util_functions.BotError(
'user',
"Channel isn't a text channel!"
);
// If cmd.channel is not populated then the selected channel should be the current one
const chan = (cmd.channel || ctx.msg.channel) as Discord.TextChannel;
// This shouldn't be able to happen
if (!ctx.msg.guild)
throw new util_functions.BotError('user', 'No guild found');
// If the user wants their command message to be deleted, make sure the bot has permission to do that
if (!cmd.keep)
util_functions.assertHasPerms(ctx.msg.guild, ['MANAGE_MESSAGES']);
// If the channel they're trying to send messages in is an anonchannel, and they're banned from going anon, throw an error
if (
(await prisma.anonchannels.findFirst({
where: {
id: cmd.channel ? cmd.channel.id : ctx.msg.channel.id,
server: ctx.msg.guild.id,
},
})) &&
(await prisma.anonbans.findFirst({
where: {
user: ctx.msg.author.id,
server: ctx.msg.guild.id,
},
}))
) {
throw new util_functions.BotError(
'user',
`${ctx.msg.author}, you're banned from sending messages there!`
);
}
// If the user doesn't have send message perms in the channel they're trying to send a message in, throw an error
if (!chan.permissionsFor(ctx.msg.author)?.has('SEND_MESSAGES')) {
throw new util_functions.BotError(
'user',
`${ctx.msg.author}, you can't send messages there!`
);
} else {
// Delete the command message if the user has chosen to remove it
if (cmd.keep == 'remove')
try {
await ctx.msg.delete();
} catch (e) {}
// If not, add a reaction to show the command has succeeded
else await ctx.msg.react('✅');
// Send the message
await ((cmd.channel || ctx.msg.channel) as Discord.TextChannel).send(
cmd.text
);
// Log what was done
await Types.LogChannel.tryToLog(
ctx.msg,
`Made ModBot say\n> ${cmd.text}\nin <#${
cmd.channel ? cmd.channel.id : ctx.msg.channel.id
}>`
);
}
},
},
{
name: 'setanonchannel',
syntax:
'setanonchannel <enabled: "enabled" | "disabled"> [channel: channel_id]',
explanation:
'Add/Remove an anonymous channel. If no channel is provided it will use the current channel',
permissions: (msg: Discord.Message) =>
msg.member && msg.member.permissions.has('MANAGE_CHANNELS'),
responder: async (
msg: util_functions.EMessage,
cmd: { enabled: 'enabled' | 'disabled'; channel?: string }
) => {
if (!msg.guild || !msg.guild.id) return;
util_functions.assertHasPerms(msg.guild, ['MANAGE_MESSAGES']);
const channel = cmd.channel ? cmd.channel : msg.channel.id;
if (cmd.enabled == 'enabled') {
if (
await prisma.anonchannels.findFirst({
where: {
id: channel,
},
})
)
throw new util_functions.BotError(
'user',
'That anonchannel is already enabled'
);
await prisma.anonchannels.create({
data: {
id: channel,
server: (msg.guild as Discord.Guild).id,
},
});
} else {
await prisma.anonchannels.deleteMany({
where: {
id: channel,
server: (msg.guild as Discord.Guild).id,
},
});
}
msg.dbReply(
util_functions.embed(
`${
cmd.enabled == 'enabled' ? 'Enabled' : 'Disabled'
} <#${channel}>${
cmd.enabled == 'enabled'
? '. Start a message with \\ to prevent it from being sent anonymously'
: ''
}`,
'success'
)
);
await Types.LogChannel.tryToLog(
msg,
`${
cmd.enabled == 'enabled' ? 'Enabled' : 'Disabled'
} anonchannel <#${channel}>`
);
},
},
{
name: 'listanonchannels',
syntax: 'listanonchannels',
explanation: 'Lists all anonymous channels',
permissions: (msg: Discord.Message) =>
msg.member && msg.member.permissions.has('MANAGE_CHANNELS'),
responder: async (msg: util_functions.EMessage) => {
if (!msg.guild || !msg.guild.id) return;
const channels = await prisma.anonchannels.findMany({
where: { server: msg.guild.id },
});
if (channels.length == 0) {
await msg.dbReply('No anon channels');
} else {
await msg.dbReply(
channels
.map(
(channel: { id: string }) => `${channel.id} -> <#${channel.id}>`
)
.join('\n')
);
}
},
},
{
name: 'whosaid',
syntax: 'whosaid <id: string>',
explanation: 'See who sent an anon message',
permissions: (msg: Discord.Message) =>
msg.member && msg.member.permissions.has('MANAGE_MESSAGES'),
responder: async (msg: util_functions.EMessage, cmd: { id: string }) => {
if (!msg.guild || !msg.guild.id) return;
const author = await prisma.anonmessages.findFirst({
where: { id: cmd.id, server: msg.guild.id },
});
if (author) {
await msg.dbReply(util_functions.desc_embed(`<@${author.user}>`));
} else {
await msg.dbReply('No message found');
}
await Types.LogChannel.tryToLog(
msg,
'Checked who said an anonymous message (id: `' + cmd.id + '`)'
);
},
},
{
name: 'reminder',
syntax:
'reminder/rm/remind/remindme [action: "add"] <duration: duration> <text: string>',
explanation: 'Set a reminder',
version: 2,
permissions: () => true,
responder: async (
ctx: Types.Context,
cmd: { duration: number; text: string }
): Promise<Array<() => void> | undefined> => {
const grammar = parseCommandGrammar(
'reminder/rm/remind/remindme [action: "add"] <duration: word> <text: string>'
);
const parsed = await matchCommand(
grammar,
ctx.msg.content.replace(ctx.prefix, ''),
ParserTypes,
ctx
);
const durationText = parsed.duration;
console.log(durationText);
if (!ctx.msg.guild) return;
const undoStack: Array<() => void> = [];
let id = nanoid(5);
if (
ctx.msg.author.id === '671486892457590846' ||
ctx.msg.author.id === '991227059089190932'
) {
for (const morb of util_functions.shuffle([
'M0RB1N-T1M3',
'MORBIUS',
'MORB1US',
'M0RB',
'M0RBIUS',
'M0RB1US',
'farting',
'shitting',
'pooping',
'everyone_stand_back_i_am_beginning_to_morb',
'morb_mode',
'morbinization',
'homestuck',
'love-morbius',
'rachel',
'lettuce',
'69',
'420',
'fuck',
'urinate',
'krkfkdjdjdjirjrnfncjriejsodoejsndnrjenaosjfnrineuehdheisisomcnfirhisjfnrepskcmemsnqosijcnfnfurifhf',
'fern',
'F4RT',
'amongus',
'amogus',
'4M0NG',
'4MONGUS',
'4M0NGUS',
'4M0NGU5',
'AMONGU5',
'AM0NGUS',
'AM0NGU5',
'4MONGU5',
'4M0GU5',
'4MOGUS',
'4M0GUS',
'AM0GUS',
'AM0GU5',
'AMOGU5',
'4MOGU5',
'4MONG-US',
'4M0NG-US',
'4M0NG-U5',
'AMONG-U5',
'AM0NG-US',
'AM0NG-U5',
'4MONG-U5',
"Accordingtoallknownlawsofaviation,thereisnowaythatabeeshouldbeabletofly.Itswingsaretoosmalltogetitsfatlittlebodyofftheground.Thebee,ofcourse,fliesanywaybecausebeesdon'tcarewhathumansthinkisimpossible.CuttoBarry'sroom,wherehe'spickingoutwhattowear.BarryYellow,black.Yellow,black.Yellow,black.Yellow,black.Ooh,blackandyellow!Yeah,let'sshakeitupalittle.",
'shutjdjsisjsk',
'jadsfhjklafhdshiulfadnfangiulfuginlfugilcngiluasguilncaglnucagnucangkacgnCgnacfsuginacsguinaacsyugacgncdfgyncfgniuafcnggancagniucfsaniguafgncdsaiucadsafnuaiscdnifucbdstnoinucfbgnosiadugniufnycgoiuasndcoifugnadsiucfhnosiaudghfnoidusaghnocfugdsanocfiugdoanuicwegoiucfndiougfludsghafinulesdyufhlughincyehwpufinvlughlehnacsfhnashnacshnacshnhnashnfclhunlhewlhuasflhjghlgjfahvnmvcxnjfsglhadsfhwehliouyweuisghjdfjhgnjvcnjdsflhidsafluiywluewfhjadsjsadfhuafdsgknysfgkuynuhewngysdufyiasbkyugihfsnduacgkhweygrdfilnsiuxygahlefudangykhxiefusdnygkjhdfiugkahisugykfhjxanxhudfniuagykwesdf',
'ilovemorbius',
'vriska',
'norris',
'fartmachine',
'yuri',
'minecraft',
'yourmom',
'fernie',
'fart',
'toilet',
'fucjyou',
'AUAUUAUAHAGAHAHHGHGHGHHGHGHHFHGHGHGOWOWOWOWOWOWOWIWIWIWI',
])) {
if (
(await prisma.reminders.findUnique({ where: { id: morb } })) ==
null
) {
id = morb;
break;
}
}
}
if (cmd.duration > 1000 * 60 * 60 * 24 * 365 * 50)
throw new util_functions.BotError(
'user',
'Cannot set reminders more than 50 years in the future'
);
const createdReminder = await prisma.reminders.create({
data: {
author: ctx.msg.author.id,
id,
text: await util_functions.cleanPings(cmd.text, ctx.msg.guild),
time: moment().add(cmd.duration, 'ms').unix(),
},
});
await util_functions.schedule_event(
{
type: 'reminder',
text: await util_functions.cleanPings(cmd.text, ctx.msg.guild),
channel: ctx.msg.channel.id,
user: ctx.msg.author.id,
message: ctx.msg.url,
id,
uniqueId: createdReminder.uniqueId,
},
cmd.duration + 'ms'
);
undoStack.push(
async () => await Types.Reminder.query().delete().where('id', id)
);
let funMessage = '';
if (
((ctx.store.get(
`rateLimits.gptFun.${ctx.msg.member?.id}`
) as number) || 0) <= 4
) {
if (
new Date() >= new Date('2023-04-01') &&
new Date() < new Date('2023-04-02')
)
funMessage = (
await util_functions.queryChatGPT(
[
{
role: 'system',
content: 'You are a rude and mean assistant.',
},
{
role: 'user',
content: `Please respond with a short, funny, and mean response for somebody trying to set a reminder in ${durationText} with the text "${cmd.text}".`,
},
],
{
defaultOnFailure: 'Reminder created!',
}
)
).content;
if (
new Date() >= new Date('2023-05-18') &&
new Date() < new Date('2023-06-09') &&
Math.random() < 0.2
)
funMessage = (
await util_functions.queryChatGPT(
[
{
role: 'system',
content:
'You are a helpful assistant. For your information, the album "Stick Season (Deluxe)" by Noah Kahan releases on June 9th, and can be presaved at https://presave.umusic.com/noah-kahan',
},
{
role: 'user',
content: `Please respond with a short, funny, absurd segue into a promotion to pre-save Stick Season (Deluxe) for somebody trying to set a reminder in ${durationText} with the text "${cmd.text}". i.e. "speaking of etc, what about" or a bad pun or something else that clearly shows you are trying too hard.`,
},
],
{
defaultOnFailure: 'Reminder created!',
}
)
).content;
if (
new Date() >= new Date('2023-06-09') &&
new Date() < new Date('2023-06-10')
)
funMessage = (
await util_functions.queryChatGPT(
[
{
role: 'system',
content:
'You are a helpful assistant. For your information, the album "Stick Season (Deluxe)" by Noah Kahan released TODAY June 9th',
},
{
role: 'user',
content: `Please respond with a short, funny, absurd segue into a promotion to listen Stick Season (Deluxe) for somebody trying to set a reminder in ${durationText} with the text "${cmd.text}". i.e. "speaking of etc, what about" or a bad pun or something else that clearly shows you are trying too hard. mention the fact that it released today`,
},
],
{
defaultOnFailure: 'Reminder created!',
}
)
).content;
}
if (funMessage.startsWith('"')) funMessage = funMessage.slice(1);
if (funMessage.endsWith('"')) funMessage = funMessage.slice(0, -1);
if (funMessage)
ctx.store.addOrCreate(
`rateLimits.gptFun.${ctx.msg.member?.id}`,
1,
60 * 60 * 1000
);
await ctx.msg.dbReply(
util_functions.embed(
`${funMessage ? `${funMessage}\n\n` : ''}You can cancel it with \`${
ctx.prefix
}reminder cancel ${id}\`, or somebody else can run \`${
ctx.prefix
}reminder copy ${id}\` to also get reminded`,
'success',
'Set Reminder!'
)
);
return undoStack;
},
},
{
name: 'reminder',
syntax: 'reminder/rm cancel <id: string>',
explanation: 'Cancel a reminder',
version: 2,
permissions: () => true,
responder: async (
ctx: Types.Context,
cmd: { id: string }
): Promise<Array<() => void> | undefined> => {
if (!ctx.msg.guild) return;
const undoStack: Array<() => void> = [];
const deleted = await Types.Reminder.query()
.delete()
.where('author', ctx.msg.author.id)
.where('id', cmd.id);
if (deleted === 0)
throw new util_functions.BotError('user', 'No reminder found');
await ctx.msg.dbReply(util_functions.embed('Cancelled!', 'success'));
return undoStack;
},
},
{
name: 'reminder',
syntax: 'reminder/rm copy <id: string>',
explanation: 'Copy a reminder',
version: 2,
permissions: () => true,
responder: async (
ctx: Types.Context,
cmd: { id: string }
): Promise<Array<() => void> | undefined> => {
if (!ctx.msg.guild) return;
const undoStack: Array<() => void> = [];
const orig = await Types.Reminder.query().where('id', cmd.id);
if (!orig.length)
throw new util_functions.BotError('user', 'Reminder not found');
if (
(
await Types.ReminderSubscriber.query()
.where('user', ctx.msg.author.id)
.where('id', cmd.id)
).length > 0
)
throw new util_functions.BotError(
'user',
"You can't subscribe to a reminder more than once."
);
await Types.ReminderSubscriber.query().insert({
user: ctx.msg.author.id,
id: cmd.id,
});
await ctx.msg.dbReply(
util_functions.embed(
'You will be notifed when the reminder is ready!',
'success'
)
);
return undoStack;
},
},
{
name: 'reminder',
syntax: 'reminder/rm list',
explanation: 'List all reminders',
version: 2,
permissions: () => true,
responder: async (
ctx: Types.Context
): Promise<Array<() => void> | undefined> => {
if (!ctx.msg.guild) return;
const undoStack: Array<() => void> = [];
const reminders = await Types.Reminder.query().where(
'author',
ctx.msg.author.id
);
let otherOp: number | null = 1;
if (process.env.UI_URL) {
otherOp = await util_functions.embed_options(
'Would you like to view your reminders on discord or be given a link to a website that will allow you to manage them more easily?',
['Website', 'Discord'],
['🕸️', '✍️'],
ctx.msg
);
}
if (otherOp == 1) {
const fields: { name: string; value: string; inline: boolean }[][] =
util_functions.chunk(
reminders
.filter((n) => n.text)
.filter((r) => (r.time || 0) > Date.now() / 1000)
.flatMap((reminder) => {
return [
{ name: 'Text', value: reminder.text || '', inline: true },
{
name: 'Time',
value: reminder.time
? moment.unix(reminder.time).fromNow()
: '[CREATED BEFORE REMINDERS UPDATE]',
inline: true,
},
{ name: 'ID', value: reminder.id, inline: true },
];
}),
21
);
const replies = [
new Discord.MessageEmbed().setTitle(
`${ctx.msg.member?.displayName}'s Reminders`
),
];
if (fields.length === 0)
// Show Explanation for why reminders might be missing, but only for 1 month after update release
replies[0].setDescription(
'No reminders set.' +
(moment().isBefore(moment('11/8/2020', 'MM-DD-YY'))
? ' (Only showing reminders created after October 8th, 2020)'
: '')
);
if (fields.length === 1) replies[0].addFields(fields[0]);
else if (fields.length > 1) {
replies[0].addFields(fields[0]);
for (let i = 1; i < fields.length; i++) {
replies.push(new Discord.MessageEmbed().addFields(fields[i]));
}
}
await ctx.msg.dbReply(util_functions.desc_embed('DMing you!'));
try {
for (const reply of replies)
await (await ctx.msg.author.createDM()).send({ embeds: [reply] });
} catch (e) {
ctx.msg.dbReply(
'Failed to send DM, do you have DMs enabled for this server?'
);
}
} else if (otherOp === 0) {
await ctx.msg.dbReply(util_functions.desc_embed('DMing you!'));
try {
await (
await ctx.msg.author.createDM()
).send({
embeds: [
new Discord.MessageEmbed()
.setURL(
`${
process.env.UI_URL
}reminders/${await Web.mintCapabilityToken(
ctx.msg.author.id,
'reminders'
)}`
)
.setTitle('Click here to manage your reminders'),
],
});
} catch (e) {
ctx.msg.dbReply(
'Failed to send DM, do you have DMs enabled for this server?'
);
}
}
return undoStack;
},
},
{
name: 'clonepurge',
syntax: 'clonepurge',
explanation: 'Purge a channels entire history',
permissions: (msg: Discord.Message) =>
msg.member && msg.member.permissions.has('MANAGE_CHANNELS'),
responder: async (msg: util_functions.EMessage) => {
if (!msg.guild) return;
util_functions.assertHasPerms(msg.guild, [
'MANAGE_MESSAGES',
'MANAGE_CHANNELS',
]);
const type = await util_functions.embed_options(
'What should I do to the original channel?',
['Delete', 'Archive', 'Nothing'],
['🗑️', '📂', '💾'],
msg
);
const clone = async (type: 0 | 1 | 2 | null) => {
if (!msg.guild || !msg.guild.id) return;
if (msg.channel.type !== 'GUILD_TEXT')
throw new util_functions.BotError('user', 'Not a text channel!');
await msg.dbReply(util_functions.desc_embed('Running clonepurge'));
const new_channel = await msg.channel.clone();
await new_channel.setPosition(msg.channel.position);
await new_channel.setTopic(msg.channel.topic || '');
await new_channel.send(util_functions.desc_embed('CLONING PINS'));
const pins = [...(await msg.channel.messages.fetchPinned()).values()];
pins.reverse();
const anonhook = await new_channel.createWebhook('ClonePurgeHook');
try {
for (const pin of pins) {
//console.log(pin);
const msg_username = pin.member
? pin.member.displayName
: pin.author.username;
await (
(await anonhook.send({
content: pin.content,
embeds: pin.embeds,
files: [...pin.attachments.values()].map((n) => n.url),
username: msg_username,
avatarURL: pin.author.displayAvatarURL(),
})) as Discord.Message
).pin();
}
await anonhook.delete();
if (type === 2) {
await msg.dbReply(util_functions.desc_embed('Finished.'));
} else if (type === 1) {
await msg.dbReply(util_functions.desc_embed('Archiving'));
let deleted_catergory = msg.guild.channels.cache.find(
(n) => n.type == 'GUILD_CATEGORY' && n.name == 'archived'
);
if (!deleted_catergory) {
deleted_catergory = await msg.guild.channels.create(
'archived',
{
type: 'GUILD_CATEGORY',
}
);
}
await msg.channel.setParent(
deleted_catergory as Discord.CategoryChannel
);
await msg.channel.permissionOverwrites.set([
{
id: msg.guild.id,
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
},
{
id: msg.author.id,
allow: ['VIEW_CHANNEL'],
},
]);
await msg.dbReply(util_functions.desc_embed('Finished.'));
} else {
await msg.dbReply(
util_functions.embed(
'Finished. Deleting channel in 10 seconds',
'warning'
)
);
await sleep(10000);
await msg.channel.delete();
}
} catch (e) {
await msg.dbReply(
util_functions.desc_embed(`Clonepurge failed: ${e}`)
);
await new_channel.delete();
}
};
if (type === 0) {
if (await util_functions.confirm(msg)) {
await clone(type);
await Types.LogChannel.tryToLog(
msg,