-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
1206 lines (1118 loc) · 54.3 KB
/
index.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
/*
* Copyright (c) 2024 Inimi | InimicalPart | Incoverse
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {
Collection,
GuildMember,
Role,
Snowflake,
Client,
Events,
Partials,
GatewayIntentBits,
REST,
Routes,
version,
Team,
PermissionsBitField,
CommandInteractionOptionResolver,
EmbedBuilder,
ActivityType,
Colors,
basename,
} from "discord.js";
import { AppInterface } from "@src/interfaces/appInterface.js";
import { IRISGlobal, LoggedEventEmitter } from "@src/interfaces/global.js";
import prettyMilliseconds from "pretty-ms";
import chalk from "chalk";
import { EventEmitter } from "events";
import JsonCParser from "jsonc-parser";
import { readFileSync, readdirSync, existsSync, createWriteStream, mkdirSync, unlinkSync } from "fs";
import dotenv from "dotenv";
import moment from "moment-timezone";
import { fileURLToPath } from "url";
import { dirname, join, relative, resolve } from "path";
import { inspect } from "util";
import performance from "./lib/performance.js";
import { checkPermissions, getFullCMD } from "./lib/utilities/permissionsCheck.js";
import storage, { checkMongoAvailability, dataLocations } from "./lib/utilities/storage.js";
import { IRISEvent } from "./lib/base/IRISEvent.js";
import { IRISCommand } from "./lib/base/IRISCommand.js";
import { setupHandler, unloadHandler } from "./lib/utilities/misc.js";
import os from "os";
import md5 from "md5";
import { IRISSubcommand } from "./lib/base/IRISSubcommand.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
dotenv.config();
declare const global: IRISGlobal;
//! ------------------------------------------- !\\
//! -- This is the start of the IRIS journey -- !\\
//! ------------------------------------------- !\\
let client: Client = null;
global.identifier = md5(os.userInfo().username + "@" + os.hostname()).substring(0,5);
(async () => {
const fullRunStart = process.hrtime.bigint();
console.clear();
global.logger = {
log: async (message: any, sender: string) => {
return new Promise(async (resolve) => {
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.log(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [" +
sender +
"]"), message
);
// clear chalk coloring for log file
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [LOG] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
)
})
},
error: async (message: any, sender: string) => {
return new Promise((resolve) => {
message = (message && message.stack) ? message.stack : message
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.error(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] ")+chalk.redBright("[" +
sender +
"]"), message
);
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [ERR] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
);
resolve();
})
},
warn: async (message: any, sender: string) => {
return new Promise((resolve) => {
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.log(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] ")+chalk.yellow("[" +
sender +
"]"), message
);
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [WRN] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
);
resolve()
})
},
debug: async (message: any, sender: string) => {
return new Promise((resolve) => {
if (config.debugging.debugMessages) {
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.log(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [" +
sender +
"]"), message
);
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [DBG] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
);
resolve()
} else resolve()
})
},
debugError: async (message: any, sender: string) => {
return new Promise((resolve) => {
if (config.debugging.debugMessages) {
message = (message && message.stack) ? message.stack : message
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.error(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] ")+chalk.redBright("[" +
sender +
"]"), message
);
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [DER] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
);
resolve()
} else resolve()
})
},
debugWarn: async (message: any, sender: string) => {
return new Promise((resolve) => {
if (config.debugging.debugMessages) {
if (typeof message !== "string") message = inspect(message, { depth: 1 });
console.log(
chalk.white.bold(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] ")+chalk.yellow("[" +
sender +
"]"), message
);
message = message.replace(/\u001b\[.*?m/g, "");
logStream.write(
"[" +
moment().format("M/D/y HH:mm:ss") +
"] [DWR] [" +
sender +
"] " +
message +
"\n", (err) => {
if (err) console.error(err)
resolve()
}
);
resolve()
} else resolve()
})
}
}
let fullyReady = false;
if (!existsSync("./config.jsonc")) {
global.logger.error(
"Config file not found. Please see config.template.jsonc for an example configuration file with an explanation of each setting.",
"IRIS-ERR"
);
process.exit(1);
}
const config = JsonCParser.parse(
readFileSync("./config.jsonc", { encoding: "utf-8" })
);
global.logName = `IRIS-${new Date().getTime()}.log`;
// if the logs folder doesn't exist, create it. if the log folder has more than 10 files, delete the oldest one. you can check which one is the oldest one by the numbers after IRIS- and before .log. the lower the number, the older it is
if (!existsSync("./logs")) {
mkdirSync("./logs");
} else {
const logFiles = readdirSync("./logs");
if (logFiles.length > 9) {
const oldestLog = logFiles.sort((a, b) => {
return parseInt(a.split("-")[1].split(".")[0]) - parseInt(b.split("-")[1].split(".")[0]);
})[0];
unlinkSync(`./logs/${oldestLog}`);
}
}
const logStream = createWriteStream(`./logs/${global.logName}`);
const app: AppInterface = {
version: JSON.parse(readFileSync("./package.json", { encoding: "utf-8" }))
.version,
config: config,
owners: [], //? this will be filled in later
};
global.app = app;
performance.start("fullRun", fullRunStart);
global.eventInfo = new Map();
global.birthdays = [];
global.communicationChannel = new EventEmitter() as LoggedEventEmitter;
let oldEmit = global.communicationChannel.emit
let oldOn = global.communicationChannel.on
let oldOnce = global.communicationChannel.once
let oldOff = global.communicationChannel.off
//! Log every emit
global.communicationChannel.emit = function(...args: any) {
var emitArgs = arguments;
if (global.app.config.debugging.internalCommunication) global.logger.log(("Emitted '"+chalk.cyanBright.bold(emitArgs[0])+"' with data: " + chalk.yellowBright(JSON.stringify(emitArgs[1]))),"IRIS-COMM")
return oldEmit.apply(global.communicationChannel, arguments)
}
//! Log every on
global.communicationChannel.on = function(...args: any) {
const caller = args[2] || "unknown"
var onArgs = arguments;
if (!(new Error("")).stack.includes("once")) if (global.app.config.debugging.internalCommunication) global.logger.log("Listening for '"+chalk.cyanBright.bold(onArgs[0])+"'",caller)
return oldOn.apply(global.communicationChannel, arguments)
}
global.communicationChannel.addListener = global.communicationChannel.on
//! Log every once
global.communicationChannel.once = function(...args: any) {
const caller = args[2] || "unknown"
var onceArgs = arguments;
if (global.app.config.debugging.internalCommunication) global.logger.log("Listening once for '"+chalk.cyanBright.bold(onceArgs[0])+"'",caller)
return oldOnce.apply(global.communicationChannel, arguments)
}
//! Log every off
global.communicationChannel.off = function(...args: any) {
let caller = args[2] || "FromONCE"
const fromOnce = caller == "FromONCE"
if (fromOnce) {
const errorStack = (new Error()).stack.split("\n")
const handleOnceIndex = errorStack.findIndex((line) => line.includes("#handleOnce"))
if (handleOnceIndex != -1) {
const dirSeparator = process.platform == "linux" ? /.*\// : /.*\\/g
caller = errorStack[handleOnceIndex-1].trim().split(" ")[1].replace("file:","").replace(/:.*/g,"").replace(dirSeparator,"")
}
}
var offArgs = arguments;
if (global.app.config.debugging.internalCommunication) global.logger.log("No longer listening"+(fromOnce?" (once)":"")+" for '"+chalk.cyanBright.bold(offArgs[0])+"'",caller)
return oldOff.apply(global.communicationChannel, arguments)
}
global.communicationChannel.removeListener = global.communicationChannel.off
global.newMembers = [];
const requiredPermissions = [
PermissionsBitField.Flags.AddReactions,
PermissionsBitField.Flags.AttachFiles,
PermissionsBitField.Flags.ManageMessages,
PermissionsBitField.Flags.ManageRoles,
PermissionsBitField.Flags.ReadMessageHistory,
PermissionsBitField.Flags.SendMessages,
PermissionsBitField.Flags.UseExternalEmojis,
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.ManageChannels,
PermissionsBitField.Flags.ManageWebhooks
]
process.on('uncaughtException', function(err) {
console.error(err)
if (!fullyReady) {
client.user.setPresence({
activities: [
{
name: "❌ Encountered an error!",
type: ActivityType.Custom,
},
],
status: "dnd",
});
}
global.logger.error((err && err.stack) ? err.stack : err, "IRIS-ERR");
});
let exiting = false
const onExit = async (signal: string | number) => {
if (signal == 2) return //! prevents loop
if (exiting) return global.logger.log("Exit already in progress...", "IRIS-"+signal)
exiting = true
global.logger.log(chalk.redBright.bold("IRIS is shutting down..."), "IRIS-"+signal);
global.logger.debug("Unloading all modules...", "IRIS-"+signal);
for (let i in global.requiredModules) {
if (!global.requiredModules[i]._loaded) {
global.logger.debug(`Module ${chalk.yellowBright(i)} is not loaded, skipping...`, "IRIS-"+signal);
continue
}
try {
let timeout;
let properName = global.requiredModules[i] instanceof IRISCommand ? "Command" : "Event"
if (global.requiredModules[i] instanceof IRISCommand) {
timeout = global.requiredModules[i].commandSettings.unloadTimeoutMS ?? IRISCommand.defaultUnloadTimeoutMS;
} else if (global.requiredModules[i] instanceof IRISEvent) {
timeout = global.requiredModules[i].eventSettings.unloadTimeoutMS ?? IRISEvent.defaultUnloadTimeoutMS;
} else {
global.logger.error(`An unknown module was found while unloading all modules: ${chalk.yellowBright(i)}`, "IRIS-"+signal);
continue
}
const unloadResult = await unloadHandler(timeout, global.requiredModules[i], client, "shuttingDown")
if (unloadResult == "timeout") {
global.logger.error(`${properName} ${chalk.redBright(global.requiredModules[i].constructor.name)} failed to unload within the ${chalk.yellowBright(timeout)} ms timeout.`, "IRIS-"+signal);
continue
}
} catch (e) {
global.logger.error(e, "IRIS-"+signal);
}
}
global.logger.debug("Logging out...", "IRIS-"+signal);
await client.destroy()
global.logger.debug("Closing storage connections...", "IRIS-"+signal);
await storage.cleanup();
await global.logger.debug("Ready to exit. Goodbye!", "IRIS-"+signal).then(() => {
logStream.end(()=>process.exit(2))
})
}
//catches ctrl+c event
process.on('exit', onExit.bind("exit"));
process.on('SIGINT', onExit.bind("SIGINT"));
// catches signal termination
process.on('SIGTERM', onExit.bind("SIGTERM"));
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', onExit.bind("SIGUSR1"));
process.on('SIGUSR2', onExit.bind("SIGUSR2"));
global.mongoStatuses = {
RUNNING: 0,
RESTARTING: 1,
STOPPED: 2,
FAILED: 3,
NOT_AVAILABLE: 4,
};
global.punishmentTimers = {}
global.reload = {
commands: []
};
global.status = {}
global.server = {
main: {
rules: [],
},
};
global.moduleInfo = {
commands: [],
events: []
};
global.mongoStatus = global.mongoStatuses.NOT_AVAILABLE
if (!process.env.DEVELOPMENT) {
global.logger.warn("DEVELOPMENT environment variable is not set. Defaulting to production mode.", "IRIS-ENV");
}
global.app.config.development = process.env.DEVELOPMENT == "YES";
global.dirName = __dirname;
global.mongoConnectionString =
`mongodb://${process.env.DBUSERNAME}:${process.env.DBPASSWD}@${global.app.config.mongoDBServer}/?authMechanism=DEFAULT&tls=true&family=4`;
//! Becomes something like: mongodb://username:[email protected]/?authMechanism=DEFAULT&tls=true&family=4
//!--------------------------
global.logger.log(`${chalk.green("IRIS")} ${chalk.bold.white(`v${app.version}`)} ${chalk.green("is starting up!")}`, returnFileName());
global.logger.log("------------------------", returnFileName());
//!--------------------------
global.resources = {};
if (global.app.config.development) {
global.app.config.mainServer = global.app.config.developmentServer;
}
try {
if (process.env.TOKEN == null) {
global.logger.log(
"Token is missing, please make sure you have the .env file in the directory with the correct information. Please see https://github.com/Incoverse/IRIS for more information.", returnFileName()
);
process.exit(1);
}
client = new Client({
intents: [
GatewayIntentBits.AutoModerationConfiguration,
GatewayIntentBits.AutoModerationExecution,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildScheduledEvents,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
Partials.Message
]
});
global.requiredModules = {};
global.logger.log(`${chalk.white("[I]")} ${chalk.yellow("Logging in...")} ${chalk.white("[I]")}`, returnFileName());
client.on(Events.InteractionCreate, async (interaction: any) => {
if (global.status.noInteract) return
if (!fullyReady) return
if (interaction.isAutocomplete()) {
if (global.status.updating) return await interaction.respond([
"IRIS is currently updating, please wait a moment and try again."
])
const responsibleHandler = global.requiredModules[Object.keys(global.requiredModules).filter((a) => a.startsWith("cmd"))
.find((a) => global.requiredModules[a].slashCommand.name == interaction.commandName)]
if (!responsibleHandler) return
if (responsibleHandler.autocomplete) {
try {
await responsibleHandler.autocomplete(interaction, global.requiredModules);
} catch (e) {
global.logger.debugError(
`An error occurred while running the autocomplete for command '${interaction.commandName}'!`,
returnFileName()
);
global.logger.debugError(e, returnFileName());
return
}
}
return
}
})
client.on(Events.InteractionCreate, async (interaction: any) => {
if (global.status.noInteract) return
if (interaction.isChatInputCommand()) {
if (!fullyReady) {
return await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("IRIS is starting up...").setDescription(
"IRIS is currently starting up, please wait a moment and try again."
).setColor(Colors.Red)
],
ephemeral: true,
});
}
if (global.status.updating) {
return await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("IRIS is updating...").setDescription(
"IRIS is currently updating, please wait a moment and try again."
).setColor(Colors.Red)
],
ephemeral: true,
});
}
if (global.mongoStatus == global.mongoStatuses.RESTARTING) {
return await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("IRIS' database is restarting...").setDescription(
"IRIS' database is currently restarting, please wait a moment and try again."
).setColor(Colors.Red)
],
ephemeral: true,
});
}
if (interaction.guild == null)
return await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("Command failed").setDescription(
"We're sorry, but IRIS is not currently available in DMs."
).setColor(Colors.Red)
],
ephemeral: true,
})
if (interaction.guildId !== global.app.config.mainServer) return;
}
try {
storage.findOne("user", { id: interaction.user.id }).then((result) => {
const user = interaction.member;
if (result == null) {
const entry = {
...global.app.config.defaultEntry,
...{
id: interaction.user.id,
last_active: new Date().toISOString(),
username: interaction.user.username,
isNew:
new Date().getTime() - ((user as GuildMember).joinedAt?.getTime() ?? 0) <
7 * 24 * 60 * 60 * 1000,
},
};
if (
interaction.user.discriminator !== "0" &&
interaction.user.discriminator
) {
entry.discriminator = interaction.user.discriminator;
storage.insertOne("user", entry);
}
} else {
const updateDoc = {
$set: {
last_active: new Date().toISOString(),
},
};
storage.updateOne("user", { id: interaction.user.id }, updateDoc)
}
});
} catch {}
if (!interaction.isChatInputCommand()) return;
let fullCmd = getFullCMD(interaction, true);
if (interaction.isAutocomplete()) return;
const responsibleHandler = global.requiredModules[Object.keys(global.requiredModules).filter((a) => a.startsWith("cmd"))
.find((a) => global.requiredModules[a].slashCommand.name == interaction.commandName)]
if (!responsibleHandler) return await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("Command failed").setDescription(
"We're sorry, a handler for this command could not be located, please try again later."
).setColor("Red")
],
ephemeral: true,
})
if (await checkPermissions(interaction, fullCmd)) {
try {
responsibleHandler.runCommand(interaction).then(async (res)=>{
if (res == false) return
if (!interaction.replied && !interaction.deferred) {
global.logger.debugWarn(
`${interaction.user.username} ran command '${chalk.yellowBright("/"+getFullCMD(interaction))}' which triggered handler '${chalk.yellowBright(responsibleHandler.fileName)}' but it appears that the command did not reply or defer the interaction. This is not recommended.`,
returnFileName()
);
await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("Command failed").setDescription(
"We're sorry, this command could currently not be processed by IRIS, please try again later."
).setColor("Red")
],
ephemeral: true,
})
}
})
} catch (e) {
global.logger.error(e, (responsibleHandler as IRISCommand).fileName);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({
content:
"⚠️ There was an error while executing this command!" +
(global.app.config.showErrors == true
? "\n\n``" +
(global.app.owners.includes(interaction.user.id)
? e.stack.toString()
: e.toString()) +
"``"
: ""),
ephemeral: true,
});
} else {
await interaction.reply({
content:
"⚠️ There was an error while executing this command!" +
(global.app.config.showErrors == true
? "\n\n``" +
(global.app.owners.includes(interaction.user.id)
? e.stack.toString()
: e.toString()) +
"``"
: ""),
ephemeral: true,
});
}
}
} else {
// global.logger.debugError(`${interaction.user.username} tried to run command '/${fullCmd}' but was denied access.`, returnFileName())
await interaction.reply({
embeds: [
new EmbedBuilder().setTitle("Access Denied").setDescription(
"You do not have permission to run this command."
).setColor("Red").setFooter({
text: interaction.user.username,
iconURL: interaction.user.avatarURL()
})
],
ephemeral: true,
});
}
});
client.on(Events.ClientReady, async () => {
const finalLogInTime = performance.end("logInTime", {
silent: !global.app.config.debugging.performances,
})
client.user.setPresence({
activities: [
{
name: "Starting up...",
type: ActivityType.Custom,
},
],
status: "idle",
});
global.logger.log(`${chalk.white("[I]")} ${chalk.green("Logged in!")} ${chalk.white("[I]")}`, returnFileName());
global.logger.log("------------------------", returnFileName());
// Check if bot has every permission it needs in global.app.config.mainServer
const guild = await client.guilds.fetch(global.app.config.mainServer);
const me = await guild.members.fetch(client.user.id);
const perms = me.permissions;
let hasAllPerms = true
global.logger.log(
`Checking permissions in ${chalk.cyanBright(guild.name)}`,
returnFileName()
)
global.logger.log("------------------------", returnFileName());
performance.start("permissionCheck");
for (let i of requiredPermissions) {
if (!perms.has(i)) {
global.logger.error(
`${chalk.redBright.bold(client.user.username)} is missing permission ${chalk.redBright.bold(new PermissionsBitField(i).toArray()[0])}!`,
returnFileName()
);
hasAllPerms = false
} else {
performance.pause(["fullRun", "permissionCheck"]);
global.logger.log(
`${chalk.yellowBright(client.user.username)} has permission ${chalk.yellowBright(new PermissionsBitField(i).toArray()[0])}.`,
returnFileName()
)
performance.resume(["fullRun", "permissionCheck"]);
}
}
const finalPermissionCheckTime = performance.end("permissionCheck", { //1.234ms
silent: !global.app.config.debugging.performances,
})
global.logger.log("------------------------", returnFileName());
if (!hasAllPerms) {
global.logger.error(
`${chalk.redBright.bold(client.user.username)} is missing one or more permissions! Please grant them and restart the bot.`,
returnFileName()
);
process.exit(1);
}
global.communicationChannel.on("ipc-query", async (data: any) => {
if (data.type == "server:info") {
global.communicationChannel.emit("ipc-query-"+data.nonce, {
name: client.guilds.cache.get(global.app.config.mainServer).name,
id: global.app.config.mainServer,
icon: client.guilds.cache.get(global.app.config.mainServer).iconURL(),
})
}
})
if (global.mongoConnectionString.match(/^(mongodb(?:\+srv)?(\:)?(?:\/{2}){1})(?:\w+\:\w+\@)?(\w+?(?:\.\w+?)*)(?::(\d+))?((?:\/\w+?)?)(?:\/)(?:\?\w+?\=\w+(?:\&\w+?\=\w+)*)?$/gm)) { //! Partial credits: https://regex101.com/library/jxxyRm
const isMongoAvailable = await checkMongoAvailability();
if (isMongoAvailable) {
global.logger.log("The MongoDB connection string is valid. Switching to "+chalk.yellowBright("MongoDB")+" storage...", returnFileName());
global.mongoStatus = global.mongoStatuses.RUNNING;
} else global.logger.warn("The MongoDB server is inaccessible. Switching to "+chalk.yellowBright("file")+" storage...", returnFileName());
} else global.logger.warn("Invalid MongoDB credentials provided. Switching to "+chalk.yellowBright("file")+" storage...", returnFileName());
global.logger.log("------------------------", returnFileName());
if (storage.method == "file" && !global.app.config.skipMongoFailWait) await sleep(3000);
function extendsIRISSubcommand(subcommand: any): subcommand is typeof IRISSubcommand {
return subcommand && subcommand.prototype instanceof IRISSubcommand;
};
performance.start("subcommandSaving")
if (!global.subcommands) {
global.subcommands = new Map()
let folder = resolve("dist/commands/command-lib")
if (existsSync(folder)) {
let files = readdirSync(folder, {recursive: true})
for (let file of files) {
if (!(file as string).endsWith(".cmdlib.js") || file instanceof Buffer) continue
const subcommand = await import(join(folder, file))
if (!subcommand.default || !extendsIRISSubcommand(subcommand.default)) continue
if (!subcommand.default.parentCommand) {
global.logger.warn(`Subcommand with class name ${chalk.yellowBright(subcommand.default.name)} (${chalk.yellowBright(basename(file))}) does not have a parent command defined. Skipping...`,returnFileName());
global.logger.debugWarn(`You can define a parent command by adding a static property named 'parentCommand' to the class.`,returnFileName())
continue
}
if (global.subcommands.has(subcommand.default.name + "@" + subcommand.default.parentCommand)) {
global.logger.error(`Subcommand with class name '${chalk.redBright(subcommand.default.name)}' for command with class name '${chalk.redBright(subcommand.default.parentCommand)}' already exists. Conflict detected.`,returnFileName());
throw new Error(`SUBCOMMAND_ALREADY_EXISTS`) //? trigger an uncaughtException, also triggering the shutdown process (onExit)
continue
}
global.subcommands.set(subcommand.default.name + "@" + subcommand.default.parentCommand, subcommand.default)
}
}
}
performance.end("subcommandSaving", {silent: true})
performance.start("commandRegistration");
const commands: Array<string> = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = join(__dirname, "commands");
const commandFiles = readdirSync(commandsPath).filter((file: string) =>
file.endsWith(".cmd.js")
);
performance.pause("commandRegistration");
performance.start("eventLoader");
const eventFiles = readdirSync(join(__dirname, "events")).filter((file: string) =>
file.endsWith(".evt.js")
);
global.moduleInfo.events = []
eventFiles.forEach((file: string) => {
return (import(`./events/${file}`)).then(a=>global.moduleInfo.events.push(a.default.name))
})
performance.pause("eventLoader");
performance.resume("commandRegistration");
global.moduleInfo.commands = []
commandFiles.forEach((file: string) => {
return (import(`./commands/${file}`)).then(a=>global.moduleInfo.commands.push(a.default.name))
})
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debug(`Registering command: ${chalk.blueBright(file)}`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
const commandClass = (await import(`./commands/${file}`)).default
const command: IRISCommand = new commandClass(client, file);
if (
command.commandSettings.devOnly &&
command.commandSettings.mainOnly
) {
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debugError(`Error while registering command: ${chalk.redBright(file)} (${chalk.redBright("Command cannot be both devOnly and mainOnly!")})`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
continue;
}
if (!global.app.config.development && command.commandSettings.devOnly) {
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debug(`Command ${chalk.yellowBright(file)} is setup for development only and will not be loaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
continue;
}
if (global.app.config.development && command.commandSettings.mainOnly) {
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debug(`Command ${chalk.yellowBright(file)} is setup for production only and will not be loaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
continue;
}
if (Object.keys(global.requiredModules).includes("cmd" + command.constructor.name)) {
const duplicatedCmd = global.requiredModules["cmd" + command.constructor.name]
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debugError(`Error while registering command: ${chalk.redBright(file)} (${chalk.redBright("Command class with the same name already exists!")})`,returnFileName());
global.logger.debugError(`Command ${chalk.bold(file)} collides with ${chalk.bold(duplicatedCmd.fileName)}. Command will not be loaded and duplicate command will be unloaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
delete commands[commands.indexOf(command?.slashCommand?.toJSON() as any)]
await duplicatedCmd.unload(client)
delete global.requiredModules["cmd" + command.constructor.name]
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
continue;
}
await command.setupSubCommands(client)
let timeout = command.commandSettings.setupTimeoutMS ?? IRISCommand.defaultSetupTimeoutMS;
let setupResult = await setupHandler(timeout, command, client, "startup")
if (setupResult == false) {
performance.pause(["fullRun", "commandRegistration"]);
global.logger.error(`Command ${chalk.redBright(file)} failed to complete setup script. Command will not be loaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
continue
} else if (!setupResult) {
//! Silent fail
performance.pause(["fullRun", "commandRegistration"]);
global.logger.debugWarn(`Command ${chalk.yellowBright(file)} failed to complete setup script silently. Command will not be loaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
continue
} else if (setupResult == "timeout") {
performance.pause(["fullRun", "commandRegistration"]);
global.logger.error(`Command ${chalk.redBright(file)} failed to complete setup script within the ${chalk.yellowBright(timeout)} ms timeout. Command will not be loaded.`,returnFileName());
performance.resume(["fullRun", "commandRegistration"]);
global.moduleInfo.commands = global.moduleInfo.commands.filter((e) => e != command.constructor.name)
continue
}
global.requiredModules[
"cmd" + command.constructor.name
] = command;
commands.push(command?.slashCommand?.toJSON() as any);
}
const finalCommandRegistrationTime = performance.end("commandRegistration", {silent: !global.app.config.debugging.performances})
global.reload.commands = commands;
await client.application.fetch();
if (client.application.owner instanceof Team) {
global.app.owners = Array.from(
client.application.owner.members.keys()
);
} else {
global.app.owners = [client.application.owner.id];
}
global.app.owners = [...global.app.owners, ...global.app.config.externalOwners];
global.logger.debug("------------------------", returnFileName());
performance.resume("eventLoader");
for (const file of eventFiles) {
global.logger.debug(
`Registering event: ${chalk.blueBright(file)}`,
returnFileName()
);
const eventClass = (await import(`./events/${file}`)).default;
const event: IRISEvent = new eventClass(file)
if (!(event.eventSettings.devOnly && event.eventSettings.mainOnly)) {
if (!global.app.config.development && event.eventSettings.devOnly) {
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
global.logger.debug(`Event ${chalk.yellowBright(file)} is setup for development only and will not be loaded.`,returnFileName());
continue;
}
if (global.app.config.development && event.eventSettings.mainOnly) {
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
global.logger.debug(`Event ${chalk.yellowBright(file)} is setup for production only and will not be loaded.`,returnFileName());
continue;
}
} else {
performance.pause(["fullRun", "eventLoader"])
global.logger.debugError(`Error while loading event: ${chalk.redBright(file)} (${chalk.redBright("Event cannot be both devOnly and mainOnly!")})`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue;
}
//! Make sure the event is correctly set up
switch (event.type) {
// discordEvent needs a listenerKey, runEvery needs a ms
case "discordEvent":
if (!event.listenerKey) {
performance.pause(["fullRun", "eventLoader"])
global.logger.debugError(`Event ${chalk.redBright(file)} is missing a listenerKey. Event will not be loaded.`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue
}
break;
case "runEvery":
if (!event.ms) {
performance.pause(["fullRun", "eventLoader"])
global.logger.debugError(`Event ${chalk.redBright(file)} is missing a ms value. Event will not be loaded.`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue
}
break;
}
if (Object.keys(global.requiredModules).includes("event" + event.constructor.name)) {
performance.pause(["fullRun", "eventLoader"])
global.logger.debugError(`Error while registering event: ${chalk.redBright(file)} (${chalk.redBright("Event class with the same name already exists!")})`,returnFileName());
global.logger.debugError(`Event ${chalk.bold(file)} collides with ${chalk.bold(global.requiredModules["event" + event.constructor.name].fileName)}. Event will not be loaded and duplicate event will be unloaded.`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
delete global.requiredModules["event" + event.constructor.name]
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue;
}
const setupRes = await setupHandler(event.eventSettings.setupTimeoutMS ?? IRISEvent.defaultSetupTimeoutMS, event, client, "startup")
if (setupRes == false) {
performance.pause(["fullRun", "eventLoader"])
global.logger.error(`Event ${chalk.redBright(file)} failed to complete setup script. Event will not be loaded.`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue
} else if (!setupRes) {
//! Silent fail
performance.pause(["fullRun", "eventLoader"])
global.logger.debugWarn(`Event ${chalk.yellowBright(file)} failed to complete setup script silently. Event will not be loaded.`,returnFileName());
performance.resume(["fullRun", "eventLoader"])
global.moduleInfo.events = global.moduleInfo.events.filter((e) => e != event.constructor.name)
continue
} else if (setupRes == "timeout") {