-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.js
3781 lines (3431 loc) · 109 KB
/
bot.js
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
/******************************************************
* Discord Bot Maker Bot
* Version 2.1.7
* Robert Borghese
* Modified for discord.js@14.14.1 by DBM Mods Community
* https://github.com/dbm-network
******************************************************/
const DBM = {};
DBM.version = "2.1.7";
const DiscordJS = (DBM.DiscordJS = require("discord.js"));
const requiredDjsVersion = "14.14.1";
if (requiredDjsVersion.localeCompare(DiscordJS.version, { numeric: true, sensitivity: "base" }) > 0) {
console.log(
`This version of Discord Bot Maker requires discord.js ${requiredDjsVersion}+.
It is currently ${DiscordJS.version}.
Please use "Project > Module Manager" and "Project > Reinstall Node Modules" to update to discord.js ${requiredDjsVersion}.\n\n`,
);
throw new Error(`Need discord.js ${requiredDjsVersion} to run!!!`);
}
const noop = () => void 0;
//---------------------------------------------------------------------
//#region Output Messages
// Gathered all the output messages in single place for easier translation.
//---------------------------------------------------------------------
const MsgType = {
MISSING_ACTION: 0,
DATA_PARSING_ERROR: 1,
MISSING_ACTIONS: 2,
DUPLICATE_SLASH_COMMAND: 3,
INVALID_SLASH_NAME: 4,
DUPLICATE_USER_COMMAND: 5,
DUPLICATE_MESSAGE_COMMAND: 6,
DUPLICATE_SLASH_PARAMETER: 7,
INVALID_SLASH_PARAMETER_NAME: 8,
INVALID_SLASH_COMMAND_SERVER_ID: 9,
DUPLICATE_BUTTON_ID: 10,
DUPLICATE_SELECT_ID: 11,
TOO_MANY_SPACES_SLASH_NAME: 12,
SUB_COMMAND_ALREADY_EXISTS: 13,
SUB_COMMAND_GROUP_ALREADY_EXISTS: 14,
MISSING_APPLICATION_COMMAND_ACCESS: 100,
MISSING_MUSIC_MODULES: 101,
MUTABLE_VOLUME_DISABLED: 200,
MUTABLE_VOLUME_NOT_IN_CHANNEL: 201,
ERROR_GETTING_YT_INFO: 202,
ERROR_CREATING_AUDIO: 203,
MISSING_MEMBER_INTENT_FIND_USER_ID: 300,
CANNOT_FIND_USER_BY_ID: 301,
SERVER_MESSAGE_INTENT_REQUIRED: 400,
CHANNEL_PARTIAL_REQUIRED: 401,
};
function PrintError(type) {
const { format } = require("node:util");
const { error, warn } = console;
switch (type) {
case MsgType.MISSING_ACTION: {
error(format("%s does not exist!", arguments[1]));
break;
}
case MsgType.DATA_PARSING_ERROR: {
error(format("There was issue parsing %s!", arguments[1]));
break;
}
case MsgType.MISSING_ACTIONS: {
error(
format(
"[Missing Actions]\nPlease copy the \"Actions\" folder from the Discord Bot Maker directory to this bot's directory: \n%s",
arguments[1],
),
);
break;
}
case MsgType.DUPLICATE_SLASH_COMMAND: {
warn(format("[Duplicate Slash Command]\nSlash command with name \"%s\" already exists!\nThis duplicate will be ignored.\n", arguments[1]));
break;
}
case MsgType.TOO_MANY_SPACES_SLASH_NAME: {
warn(format("[Too Many Spaces in Slash Name]\nSlash command with name \"%s\" has too many spaces!\nSlash command names may only contain a maximum of three different words.\n", arguments[1]));
break;
}
case MsgType.SUB_COMMAND_ALREADY_EXISTS: {
warn(format("[Sub-Command Already Exists]\nSlash command with name \"%s\" cannot exist.\nIt requires the creation of a \"sub-command group\" called \"%s\",\nbut there's already a command with that name.", arguments[1], arguments[2]));
break;
}
case MsgType.SUB_COMMAND_GROUP_ALREADY_EXISTS: {
warn(format("[Sub-Command Group Already Exists]\nSlash command with name \"%s\" cannot exist.\nThere is already a \"sub-command group\" with that name.\nThe \"sub-command group\" exists because of a command named something like: \"%s _____\"", arguments[1], arguments[1]));
break;
}
case MsgType.INVALID_SLASH_NAME: {
error(
format(
"[Invalid Slash Command Name]\nSlash command has invalid name: \"%s\".\nSlash command names cannot have spaces and must only contain letters, numbers, underscores, and dashes!\nThis command will be ignored.",
arguments[1],
),
);
break;
}
case MsgType.DUPLICATE_USER_COMMAND: {
warn(format("[Duplicate User Command]\nUser command with name \"%s\" already exists!\nThis duplicate will be ignored.\n", arguments[1]));
break;
}
case MsgType.DUPLICATE_MESSAGE_COMMAND: {
warn(format("[Duplicate Message Command]\nMessage command with name \"%s\" already exists!\nThis duplicate will be ignored.\n", arguments[1]));
break;
}
case MsgType.DUPLICATE_SLASH_PARAMETER: {
warn(
format(
"[Duplicate Slash Command]\nSlash command \"%s\" parameter #%d (\"%s\") has a name that's already being used!\nThis duplicate will be ignored.\n",
arguments[1],
arguments[2],
arguments[3],
),
);
break;
}
case MsgType.INVALID_SLASH_PARAMETER_NAME: {
error(
format(
"[Invalid Slash Parameter Name]\nSlash command \"%s\" parameter #%d has invalid name: \"%s\".\nSlash command parameter names cannot have spaces and must only contain letters, numbers, underscores, and dashes!\nThis parameter will be ignored.\n",
arguments[1],
arguments[2],
arguments[3],
),
);
break;
}
case MsgType.INVALID_SLASH_COMMAND_SERVER_ID: {
error(
format("Invalid Server ID \"%s\" listed in \"Slash Command Options -> Server IDs for Slash Commands\"!\n"),
arguments[1],
);
break;
}
case MsgType.DUPLICATE_BUTTON_ID: {
warn(
format(
"Button interaction with unique id \"%s\" already exists!\nThis duplicate will be ignored.\n",
arguments[1],
),
);
break;
}
case MsgType.DUPLICATE_SELECT_ID: {
warn(
format(
"Select menu interaction with unique id \"%s\" already exists!\nThis duplicate will be ignored.\n",
arguments[1],
),
);
break;
}
case MsgType.MISSING_APPLICATION_COMMAND_ACCESS: {
warn(
format(
"Slash commands cannot be provided to server: %s (ID: %s).\nPlease re-invite the bot to this server using the invite link found in \"Settings -> Bot Settings\".\nAlternatively, you can switch to using Global Slash Commands in \"Settings -> Slash Command Settings -> Slash Command Creation Preference\". However, please note global commands take a long time to update (~1 hour).",
arguments[1],
arguments[2],
),
);
break;
}
case MsgType.MISSING_MUSIC_MODULES: {
warn(format("Could not load audio-related Node modules.\nPlease run \"File -> Music Capabilities -> Update Music Libraries\" to ensure they are installed."));
break;
}
case MsgType.MUTABLE_VOLUME_DISABLED: {
warn(format("[Mutable Volume Disabled]\nTried setting volume but \"Mutable Volume\" is disabled."));
break;
}
case MsgType.MUTABLE_VOLUME_NOT_IN_CHANNEL: {
warn(format("[Mutable Volume Not in Channel]\nTried setting volume but the bot is not in a voice channel."));
break;
}
case MsgType.ERROR_GETTING_YT_INFO: {
warn(format("Error getting YouTube info.\n%s", arguments[1]));
break;
}
case MsgType.ERROR_CREATING_AUDIO: {
warn(format("Error creating audio resource.\n%s", arguments[1]));
break;
}
case MsgType.MISSING_MEMBER_INTENT_FIND_USER_ID: {
warn(" - DBM Warning - \nFind User (by Name/ID) may freeze or error because\nthe bot has not enabled the Server Member Events Intent.");
break;
}
case MsgType.CANNOT_FIND_USER_BY_ID: {
warn(format("[Cannot Find User by ID]\nCannot find user by id: %s", arguments[1]));
break;
}
case MsgType.SERVER_MESSAGE_INTENT_REQUIRED: {
warn(format("[Message Content Intent Required]\n%s commands found that require the \"Message Content\" intent.\nThese commands require the bot to be able to read messages from Discord servers.\nTo enable this behavior, first ensure the \"MESSAGE CONTENT INTENT\" is enabled in the \"Bot\" section on the Discord Developer Portal (the same page you got your bot token from).\nSecondly, in Discord Bot Maker, select Extensions -> Bot Intents from the title menu bar, and in this dialog, make sure \"Message Content\" is checked.", arguments[1]));
break;
}
case MsgType.CHANNEL_PARTIAL_REQUIRED: {
warn(format("[Channel Partial Required]\n%s commands are set to \"DMs Only\", but the Channel partial is not enabled.\nTo allow the bot to read messages from DMs, do the following: In Discord Bot Maker, on the title menu bar, go to Extensions -> Bot Partials.\nIn the dialog that appears, select \"Custom\" and then make sure \"Channel (Enables DMs)\" is checked.", arguments[1]));
}
}
}
function GetActionErrorText(location, index, dataName) {
return "Error with the " + location + (dataName ? ` - Action #${index} (${dataName})` : "");
}
//#endregion
//---------------------------------------------------------------------
//#region Bot
// Contains functions for controlling the bot.
//---------------------------------------------------------------------
const Bot = (DBM.Bot = {});
Bot.$slash = {}; // Slash commands
Bot.$user = {}; // User commands
Bot.$msge = {}; // Message commands
Bot.$button = {}; // Button interactions
Bot.$select = {}; // Select interactions
Bot.$cmds = {}; // Normal commands
Bot.$icds = []; // Includes word commands
Bot.$regx = []; // Regular Expression commands
Bot.$anym = []; // Any message commands
Bot.$other = {}; // Manual commands
Bot.$evts = {}; // Events
Bot.bot = null;
Bot.applicationCommandData = [];
Bot.PRIVILEGED_INTENTS =
DiscordJS.IntentsBitField.Flags.GuildMembers |
DiscordJS.IntentsBitField.Flags.GuildPresences |
DiscordJS.IntentsBitField.Flags.MessageContent;
Bot.NON_PRIVILEGED_INTENTS =
DiscordJS.IntentsBitField.Flags.Guilds |
DiscordJS.IntentsBitField.Flags.GuildModeration | // Previously GUILD_BANS
DiscordJS.IntentsBitField.Flags.GuildEmojisAndStickers |
DiscordJS.IntentsBitField.Flags.GuildIntegrations |
DiscordJS.IntentsBitField.Flags.GuildWebhooks |
DiscordJS.IntentsBitField.Flags.GuildInvites |
DiscordJS.IntentsBitField.Flags.GuildVoiceStates |
DiscordJS.IntentsBitField.Flags.GuildMessages |
DiscordJS.IntentsBitField.Flags.GuildMessageReactions |
DiscordJS.IntentsBitField.Flags.GuildMessageTyping |
DiscordJS.IntentsBitField.Flags.DirectMessages |
DiscordJS.IntentsBitField.Flags.DirectMessageReactions |
DiscordJS.IntentsBitField.Flags.DirectMessageTyping;
Bot.ALL_INTENTS = Bot.PRIVILEGED_INTENTS | Bot.NON_PRIVILEGED_INTENTS;
Bot.init = function () {
this.initBot();
this.setupBot();
this.reformatData();
this.checkForCommandErrors();
this.initEvents();
this.login();
};
Bot.initBot = function () {
const options = this.makeClientOptions();
options.intents = this.intents();
if (this.usePartials()) {
options.partials = this.partials();
}
this.hasMemberIntents = (options.intents & DiscordJS.IntentsBitField.Flags.GuildMembers) !== 0;
this.hasMessageContentIntents = (options.intents & DiscordJS.IntentsBitField.Flags.MessageContent) !== 0;
this.bot = new DiscordJS.Client(options);
};
Bot.makeClientOptions = function () {
return {};
};
Bot.intents = function () {
return this.NON_PRIVILEGED_INTENTS;
};
Bot.usePartials = function () {
return false;
};
Bot.partials = function () {
return [];
};
Bot.setupBot = function () {
this.bot.on("raw", this.onRawData);
};
// TODO: This looks redundant, faulty logic in first if statement (always returns true)
Bot.onRawData = function (packet) {
if (packet.t !== "MESSAGE_REACTION_ADD" || packet.t !== "MESSAGE_REACTION_REMOVE") return;
const client = Bot.bot;
const channel = client.channels.resolve(packet.d.channel_id);
if (channel?.messages.cache.has(packet.d.message_id)) return;
channel.messages
.fetch(packet.d.message_id)
.then((message) => {
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
const reaction = message.reactions.resolve(emoji);
if (packet.t === "MESSAGE_REACTION_ADD") {
client.emit("messageReactionAdd", reaction, client.users.resolve(packet.d.user_id));
}
if (packet.t === "MESSAGE_REACTION_REMOVE") {
client.emit("messageReactionRemove", reaction, client.users.resolve(packet.d.user_id));
}
})
.catch(noop);
};
Bot.reformatData = function () {
this.reformatCommands();
this.reformatEvents();
};
Bot.reformatCommands = function () {
const data = Files.data.commands;
if (!data) return;
this._hasTextCommands = false;
this._textCommandCount = 0;
this._dmTextCommandCount = 0;
this._caseSensitive = Files.data.settings.case === "true";
for (let i = 0; i < data.length; i++) {
const com = data[i];
if (com) {
this.prepareActions(com.actions);
if (com.comType <= "3") {
this._textCommandCount++;
if (com.restriction === "3") {
this._dmTextCommandCount++;
}
}
switch (com.comType) {
case "0": {
this._hasTextCommands = true;
if (this._caseSensitive) {
this.$cmds[com.name] = com;
if (com._aliases) {
const aliases = com._aliases;
for (let j = 0; j < aliases.length; j++) {
this.$cmds[aliases[j]] = com;
}
}
} else {
this.$cmds[com.name.toLowerCase()] = com;
if (com._aliases) {
const aliases = com._aliases;
for (let j = 0; j < aliases.length; j++) {
this.$cmds[aliases[j].toLowerCase()] = com;
}
}
}
break;
}
case "1": {
this.$icds.push(com);
break;
}
case "2": {
this.$regx.push(com);
break;
}
case "3": {
this.$anym.push(com);
break;
}
case "4": {
const names = this.validateSlashCommandName(com.name);
if (names) {
if (names.length > 3) {
PrintError(MsgType.TOO_MANY_SPACES_SLASH_NAME, com.name);
} else {
const keyName = names.join(" ");
if (this.$slash[keyName]) {
PrintError(MsgType.DUPLICATE_SLASH_COMMAND, keyName);
} else {
this.$slash[keyName] = com;
if (names.length === 1) {
this.applicationCommandData.push(this.createApiJsonFromCommand(com, keyName));
} else {
this.mergeSubCommandIntoCommandData(names, this.createApiJsonFromCommand(com, names[names.length - 1]));
}
}
}
} else {
PrintError(MsgType.INVALID_SLASH_NAME, com.name);
}
break;
}
case "5": {
const name = com.name;
if (this.$user[name]) {
PrintError(MsgType.DUPLICATE_USER_COMMAND, name);
} else {
this.$user[name] = com;
this.applicationCommandData.push(this.createApiJsonFromCommand(com, name));
}
break;
}
case "6": {
const name = com.name;
if (this.$msge[name]) {
PrintError(MsgType.DUPLICATE_MESSAGE_COMMAND, name);
} else {
this.$msge[name] = com;
this.applicationCommandData.push(this.createApiJsonFromCommand(com, name));
}
break;
}
default: {
this.$other[com._id] = com;
break;
}
}
}
}
};
Bot.createApiJsonFromCommand = function (com, name) {
const result = {
name: name ?? com.name,
description: this.generateSlashCommandDescription(com),
};
switch (com.comType) {
case "4": {
result.type = DiscordJS.ApplicationCommandType.ChatInput;
break;
}
case "5": {
result.type = DiscordJS.ApplicationCommandType.User;
break;
}
case "6": {
result.type = DiscordJS.ApplicationCommandType.Message;
break;
}
}
if (com.comType === "4" && com.parameters && Array.isArray(com.parameters)) {
result.options = this.validateSlashCommandParameters(com.parameters, result.name);
}
return result;
};
Bot.mergeSubCommandIntoCommandData = function (names, data) {
data.type = "SUB_COMMAND";
const baseName = names[0];
let baseCommand = this.applicationCommandData.find(data => data.name === baseName) ?? null;
if (baseCommand === null) {
baseCommand = {
name: baseName,
description: this.getNoDescriptionText(),
options: [],
};
this.applicationCommandData.push(baseCommand);
}
if (names.length === 2) {
if (!baseCommand.options) {
baseCommand.options = [];
}
if (baseCommand.options.find(d => d.name === data.name && d.type === "SUB_COMMAND_GROUP")) {
PrintError(MsgType.SUB_COMMAND_GROUP_ALREADY_EXISTS, names.join(" "));
} else {
baseCommand.options.push(data);
}
} else if (names.length >= 3) {
if (!baseCommand.options) {
baseCommand.options = [];
}
const groupName = names[1];
let baseGroup = baseCommand.options.find(option => option.name === groupName) ?? null;
if (baseGroup === null) {
baseGroup = {
name: groupName,
description: this.getNoDescriptionText(),
type: "SUB_COMMAND_GROUP",
options: [],
}
baseCommand.options.push(baseGroup);
} else if (baseGroup.type === "SUB_COMMAND") {
PrintError(MsgType.SUB_COMMAND_ALREADY_EXISTS, names.join(" "), `${names[0]} ${names[1]}`);
return;
}
baseGroup.options.push(data);
}
};
Bot.validateSlashCommandName = function (name) {
if (!name) {
return false;
}
const names = name
.split(/\s+/)
.map(name => this.validateSlashCommandParameterName(name))
.filter(name => typeof name === "string");
return names.length > 0 ? names : false;
};
Bot.validateSlashCommandParameterName = function (name) {
if (!name) {
return false;
}
if (name.length > 32) {
name = name.substring(0, 32);
}
if (name.match(/^[\p{L}\w-]{1,32}$/ui)) {
return name.toLowerCase();
}
return false;
};
Bot.generateSlashCommandDescription = function (com) {
const desc = com.description;
if (com.comType !== "4") {
return "";
}
return this.validateSlashCommandDescription(desc);
};
Bot.validateSlashCommandDescription = function (desc) {
if (desc?.length > 100) {
return desc.substring(0, 100);
}
return desc || this.getNoDescriptionText();
};
Bot.getNoDescriptionText = function () {
return Files.data.settings.noDescriptionText ?? "(no description)";
};
Bot.validateSlashCommandParameters = function (parameters, commandName) {
const requireParams = [];
const optionalParams = [];
const existingNames = {};
for (let i = 0; i < parameters.length; i++) {
const paramsData = parameters[i];
const name = this.validateSlashCommandParameterName(paramsData.name);
if (name) {
if (!existingNames[name]) {
existingNames[name] = true;
paramsData.name = name;
paramsData.description = this.validateSlashCommandDescription(paramsData.description);
switch(paramsData.type) {
case 'STRING':
paramsData.type = DiscordJS.ApplicationCommandOptionType.String;
break;
case 'INTEGER':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Integer;
break;
case 'NUMBER':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Number;
break;
case 'BOOLEAN':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Boolean;
break;
case 'USER':
paramsData.type = DiscordJS.ApplicationCommandOptionType.User;
break;
case 'CHANNEL':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Channel;
break;
case 'ROLE':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Role;
break;
case 'ATTACHMENT':
paramsData.type = DiscordJS.ApplicationCommandOptionType.Attachment;
break;
}
if (paramsData.required) {
requireParams.push(paramsData);
} else {
optionalParams.push(paramsData);
}
} else {
PrintError(MsgType.DUPLICATE_SLASH_PARAMETER, commandName, i + 1, name);
}
} else {
PrintError(MsgType.INVALID_SLASH_PARAMETER_NAME, commandName, i + 1, paramsData.name);
}
}
return requireParams.concat(optionalParams);
};
Bot.reformatEvents = function () {
const data = Files.data.events;
if (!data) return;
for (let i = 0; i < data.length; i++) {
const com = data[i];
if (com) {
this.prepareActions(com.actions);
const type = com["event-type"];
if (!this.$evts[type]) this.$evts[type] = [];
this.$evts[type].push(com);
}
}
};
Bot.prepareActions = function (actions) {
if (actions) {
const customData = {};
for (let i = 0; i < actions.length; i++) {
const action = actions[i];
if (action?.name && Actions.modInitReferences[action.name]) {
Actions.modInitReferences[action.name].call(this, action, customData, i);
}
}
if (Object.keys(customData).length > 0) {
actions._customData = customData;
}
}
};
Bot.registerButtonInteraction = function (interactionId, data) {
if (interactionId) {
if (!this.$button[interactionId]) {
this.$button[interactionId] = data;
} else {
PrintError(MsgType.DUPLICATE_BUTTON_ID, interactionId);
}
}
};
Bot.registerSelectMenuInteraction = function (interactionId, data) {
if (interactionId) {
if (!this.$select[interactionId]) {
this.$select[interactionId] = data;
} else {
PrintError(MsgType.DUPLICATE_SELECT_ID, interactionId);
}
}
};
Bot.checkForCommandErrors = function () {
if (this._textCommandCount > 0 && !this.hasMessageContentIntents) {
PrintError(MsgType.SERVER_MESSAGE_INTENT_REQUIRED, this._textCommandCount);
}
if (this._dmTextCommandCount > 0 && (!this.usePartials() || !this.partials().includes("CHANNEL"))) {
PrintError(MsgType.CHANNEL_PARTIAL_REQUIRED, this._dmTextCommandCount);
}
};
Bot.initEvents = function () {
this.bot.on("ready", this.onReady.bind(this));
this.bot.on("guildCreate", this.onServerJoin.bind(this));
this.bot.on("messageCreate", this.onMessage.bind(this));
this.bot.on("interactionCreate", this.onInteraction.bind(this));
Events.registerEvents(this.bot);
};
Bot.login = function () {
this.bot.login(Files.data.settings.token);
};
Bot.onReady = function () {
process.send?.("BotReady");
console.log("Bot is ready!"); // Tells editor to start!
this.restoreVariables();
this.registerApplicationCommands();
this.preformInitialization();
};
Bot.restoreVariables = function () {
Files.restoreServerVariables();
Files.restoreGlobalVariables();
};
Bot.registerApplicationCommands = function () {
let slashType = Files.data.settings.slashType ?? "auto";
if (slashType === "auto") {
const serverCount = this.bot.guilds.cache.size;
if (serverCount <= 15) {
slashType = "all";
} else {
slashType = "global";
}
}
this._slashCommandCreateType = slashType;
this._slashCommandServerList = Files.data.settings?.slashServers?.split?.(/[\n\r]+/) ?? [];
switch (slashType) {
case "all": {
this.setAllServerCommands(this.applicationCommandData);
this.setGlobalCommands([]);
break;
}
case "global": {
this.setAllServerCommands([], false);
this.setGlobalCommands(this.applicationCommandData);
break;
}
case "manual": {
this.setCertainServerCommands(this.applicationCommandData, this._slashCommandServerList);
this.setGlobalCommands([]);
break;
}
case "manualglobal": {
this.setCertainServerCommands(this.applicationCommandData, this._slashCommandServerList);
this.setGlobalCommands(this.applicationCommandData);
break;
}
}
};
Bot.onServerJoin = function (guild) {
this.initializeCommandsForNewServer(guild);
};
Bot.initializeCommandsForNewServer = function (guild) {
switch (this._slashCommandCreateType) {
case "all":
case "manual":
case "manualglobal": {
if (this._slashCommandCreateType === "all" || this._slashCommandServerList.includes(guild.id)) {
this.setCommandsForServer(guild, this.applicationCommandData, true);
}
break;
}
}
};
Bot.shouldPrintAnyMissingAccessError = function () {
return !(Files.data.settings.ignoreCommandScopeErrors ?? false);
};
Bot.clearUnspecifiedServerCommands = function () {
return Files.data.settings.clearUnlistedServers ?? false;
};
Bot.setGlobalCommands = function (commands) {
this.bot.application?.commands?.set?.(commands).then(function () {}).catch(function (err) {
console.error(err);
})
};
Bot.setCommandsForServer = function (guild, commands, printMissingAccessError) {
if (guild?.commands?.set) {
guild.commands.set(commands).then(function () {}).catch((err) => {
if (err.code === 50001) {
if (this.shouldPrintAnyMissingAccessError() && printMissingAccessError) {
PrintError(MsgType.MISSING_APPLICATION_COMMAND_ACCESS, guild.name, guild.id);
}
} else {
console.error(err);
}
});
}
};
Bot.setAllServerCommands = function (commands, printMissingAccessError = true) {
this.bot.guilds.cache.forEach((cachedGuild, value) => {
cachedGuild
.fetch()
.then((guild) => {
this.setCommandsForServer(guild, commands, printMissingAccessError);
})
.catch(function (err) {
console.error(err);
});
});
};
Bot.setCertainServerCommands = function (commands, serverIdList) {
if (this.clearUnspecifiedServerCommands()) {
this.bot.guilds.cache.forEach((cachedGuild, value) => {
cachedGuild
.fetch()
.then((guild) => {
if (serverIdList.includes(guild.id)) {
this.setCommandsForServer(guild, commands, true);
} else {
this.setCommandsForServer(guild, [], true);
}
})
.catch(function (err) {
console.error(err);
});
});
} else {
for (let i = 0; i < serverIdList.length; i++) {
this.bot.guilds
.fetch(serverIdList[i])
.then((guild) => {
this.setCommandsForServer(guild, commands, true);
})
.catch(function (err) {
PrintError(MsgType.INVALID_SLASH_COMMAND_SERVER_ID, serverIdList[i]);
});
}
}
};
Bot.preformInitialization = function () {
const bot = this.bot;
if (this.$evts["1"]) {
Events.onInitialization(bot);
}
if (this.$evts["48"]) {
Events.onInitializationOnce(bot);
}
if (this.$evts["3"]) {
Events.setupIntervals(bot);
}
};
Bot.onMessage = function (msg) {
if (msg.author.bot) return;
try {
if (!this.checkCommand(msg)) {
this.onAnyMessage(msg);
}
} catch (e) {
console.error(e);
}
};
Bot.checkCommand = function (msg) {
if (!this._hasTextCommands) return false;
let command = this.checkTag(msg.content);
if (!command) return false;
if (!this._caseSensitive) {
command = command.toLowerCase();
}
const cmd = this.$cmds[command];
if (cmd) {
Actions.preformActionsFromMessage(msg, cmd);
return true;
}
return false;
};
Bot.escapeRegExp = function (text) {
return text.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
};
Bot.generateTagRegex = function (tag, allowPrefixSpace) {
return new RegExp(`^${this.escapeRegExp(tag)}${allowPrefixSpace ? "\\s*" : ""}`);
};
Bot.populateTagRegex = function () {
if (this.tagRegex) return;
const tag = Files.data.settings.tag;
const allowPrefixSpace = Files.data.settings.allowPrefixSpace === "true";
this.tagRegex = this.generateTagRegex(tag, allowPrefixSpace);
return this.tagRegex;
};
Bot.checkTag = function (content) {
const allowPrefixSpace = Files.data.settings.allowPrefixSpace === "true";
const tag = Files.data.settings.tag;
this.populateTagRegex();
const separator = Files.data.settings.separator || "\\s+";
if (content.startsWith(tag)) {
if (allowPrefixSpace && this.tagRegex.test(content)) {
content = content.replace(this.tagRegex, "");
return content.split(new RegExp(separator))[0];
} else {
content = content.split(new RegExp(separator))[0];
return content.substring(tag.length);
}
}
return null;
};
Bot.onAnyMessage = function (msg) {
this.checkIncludes(msg);
this.checkRegExps(msg);
if (!msg.author.bot) {
if (this.$evts["2"]) {
Events.callEvents("2", 1, 0, 2, false, "", msg);
}
const anym = this.$anym;
for (let i = 0; i < anym.length; i++) {
if (anym[i]) {
Actions.preformActionsFromMessage(msg, anym[i]);
}
}
}
};
Bot.checkIncludes = function (msg) {
const text = msg.content;
if (!text) return;
const icds = this.$icds;
const icds_len = icds.length;
for (let i = 0; i < icds_len; i++) {
if (!icds[i]?.name) continue;
if (icds[i]._aliases) {
const words = [icds[i].name].concat(icds[i]._aliases);
if (text.match(new RegExp("\\b(?:" + words.join("|") + ")\\b", "i"))) {
Actions.preformActionsFromMessage(msg, icds[i]);
}
} else if (text.match(new RegExp("\\b" + icds[i].name + "\\b", "i"))) {
Actions.preformActionsFromMessage(msg, icds[i]);
}
}
};
Bot.checkRegExps = function (msg) {
const text = msg.content;
if (!text) return;
const regx = this.$regx;
const regx_len = regx.length;
for (let i = 0; i < regx_len; i++) {
if (regx[i]?.name) {
if (text.match(new RegExp(regx[i].name, "i"))) {
Actions.preformActionsFromMessage(msg, regx[i]);
} else if (regx[i]._aliases) {
const aliases = regx[i]._aliases;
const aliases_len = aliases.length;
for (let j = 0; j < aliases_len; j++) {
if (text.match(new RegExp("\\b" + aliases[j] + "\\b", "i"))) {
Actions.preformActionsFromMessage(msg, regx[i]);
break;
}
}
}
}
}
};
Bot.onInteraction = function (interaction) {
if (interaction.isChatInputCommand()) {
this.onSlashCommandInteraction(interaction);
} else if (interaction.isContextMenuCommand()) {
this.onContextMenuInteraction(interaction);
} else if (interaction.isModalSubmit()) {
Actions.checkModalSubmitResponses(interaction);
} else {
if (interaction.component?.type === DiscordJS.ComponentType.Button) {
interaction._button = interaction.component;
} else if (interaction.component?.type === DiscordJS.ComponentType.StringSelect) {
interaction._select = interaction.component;
}
if (!Actions.checkTemporaryInteractionResponses(interaction)) {
if (interaction.isButton()) {
this.onButtonInteraction(interaction);
} else if (interaction.isStringSelectMenu()) {
this.onSelectMenuInteraction(interaction);
}
}
}
};
Bot.onSlashCommandInteraction = function (interaction) {
let interactionName = interaction.commandName;
const group = interaction.options.getSubcommandGroup(false);
if (group) interactionName = `${interactionName} ${group}`;
const sub = interaction.options.getSubcommand(false);
if (sub) interactionName = `${interactionName} ${sub}`;
if (this.$slash[interactionName]) Actions.preformActionsFromInteraction(interaction, this.$slash[interactionName], true);
};
Bot.onContextMenuInteraction = function (interaction) {
if (interaction.isUserContextMenuCommand()) {
this.onUserContextMenuInteraction(interaction);
} else if (interaction.isMessageContextMenuCommand()) {