-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
1479 lines (1274 loc) · 54.7 KB
/
Copy pathindex.js
File metadata and controls
1479 lines (1274 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
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
require("dotenv").config({ path: "./Config/credentials.env", override: false, debug: false, quiet: true });
const { Client, Collection, GatewayIntentBits, MessageFlags, Partials, PermissionFlagsBits } = require("discord.js");
const { REST } = require('@discordjs/rest');
const express = require('express');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { updateStats } = require('./Functions/botStats');
const eventLoader = require('./Events/_loader');
const JobScheduler = require('./Functions/JobScheduler');
const { ROLES, MISC, CHANNELS } = require('./Config/constants');
const { EmbedBuilder: DiscordEmbedBuilder } = require('discord.js');
let BuildersEmbedBuilder = null;
try {
BuildersEmbedBuilder = require('@discordjs/builders').EmbedBuilder;
} catch (err) {
BuildersEmbedBuilder = null;
}
const appName = require('./package.json')?.name || 'Bot';
const DEFAULT_EMBED_COLOR = 0x5865F2;
const DEFAULT_EMBED_FOOTER = `${appName} • System`;
const resilienceConfig = MISC?.resilience || {};
const LOGIN_MAX_ATTEMPTS = Math.max(1, Math.min(20, Number(resilienceConfig.loginMaxAttempts) || 5));
const LOGIN_BASE_RETRY_DELAY_MS = Math.max(500, Math.min(60_000, Number(resilienceConfig.loginBaseRetryDelayMs) || 2500));
const LOGIN_MAX_RETRY_DELAY_MS = Math.max(LOGIN_BASE_RETRY_DELAY_MS, Math.min(300_000, Number(resilienceConfig.loginMaxRetryDelayMs) || 30_000));
const HEALTH_CHECK_INTERVAL_MS = Math.max(15_000, Math.min(10 * 60 * 1000, Number(resilienceConfig.healthCheckIntervalMs) || 60_000));
const DB_FAILURE_THRESHOLD = Math.max(1, Math.min(10, Number(resilienceConfig.dbFailureThreshold) || 3));
const SHUTDOWN_TIMEOUT_MS = Math.max(2_000, Math.min(120_000, Number(resilienceConfig.shutdownTimeoutMs) || 15_000));
const EXIT_ON_UNHANDLED_REJECTION = resilienceConfig.exitOnUnhandledRejection !== false;
const EXIT_ON_UNCAUGHT_EXCEPTION = resilienceConfig.exitOnUncaughtException !== false;
function applyEmbedDefaults(embed) {
if (!embed?.data) return;
if (!embed.data.color) embed.setColor(DEFAULT_EMBED_COLOR);
if (!embed.data.timestamp) embed.setTimestamp();
if (!embed.data.footer?.text) embed.setFooter({ text: DEFAULT_EMBED_FOOTER });
}
function patchEmbedBuilder(EmbedBuilder) {
if (!EmbedBuilder || EmbedBuilder.prototype.__embedDefaultsPatched) return;
const originalToJSON = EmbedBuilder.prototype.toJSON;
EmbedBuilder.prototype.toJSON = function (...args) {
applyEmbedDefaults(this);
return originalToJSON.apply(this, args);
};
EmbedBuilder.prototype.__embedDefaultsPatched = true;
}
patchEmbedBuilder(DiscordEmbedBuilder);
patchEmbedBuilder(BuildersEmbedBuilder);
// Create the Discord client with the intents we currently need.
// We can remove unused intents later if we want to tighten permissions.
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates,
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
presence: require("./Config/presence.json"),
});
const BOT_WEBHOOK_PORT = Number(process.env.BOT_WEBHOOK_PORT || 3050);
const BOT_WEBHOOK_SECRET = String(process.env.BOT_WEBHOOK_SECRET || '').trim();
const BOT_WEBHOOK_MAX_DRIFT_MS = Math.max(30_000, Math.min(15 * 60 * 1000, Number(process.env.BOT_WEBHOOK_MAX_DRIFT_MS) || 5 * 60 * 1000));
let webhookServer = null;
function verifyWebhookSignature(req, secret) {
if (!secret) return false;
const timestamp = String(req.headers['x-webhook-timestamp'] || '').trim();
const signature = String(req.headers['x-webhook-signature'] || '').trim();
if (!timestamp || !signature) return false;
const tsNumber = Number(timestamp);
if (!Number.isFinite(tsNumber)) return false;
if (Math.abs(Date.now() - tsNumber) > BOT_WEBHOOK_MAX_DRIFT_MS) return false;
const rawBody = typeof req.rawBody === 'string' ? req.rawBody : JSON.stringify(req.body || {});
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
if (expected.length !== signature.length) return false;
try {
return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'));
} catch {
return false;
}
}
async function dispatchWebsiteWebhook(payload) {
if (!payload || typeof payload !== 'object') return;
client.runtimeState.lastWebsiteWebhookAt = Date.now();
client.runtimeState.lastWebsiteWebhookEvent = String(payload.event || 'website.event');
const channelId = CHANNELS?.webhookChannelId || CHANNELS?.notificationChannelId || CHANNELS?.serverLogChannelId;
if (!channelId) return;
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel || !channel.isTextBased?.()) return;
const eventName = String(payload.event || 'website.event');
const actor = payload.actor || 'system';
const when = payload.timestamp || new Date().toISOString();
let dataBlock = '';
try {
const json = JSON.stringify(payload.data || {}, null, 2);
dataBlock = json.length > 900 ? `${json.slice(0, 900)}\n...` : json;
} catch {
dataBlock = String(payload.data || '');
}
const payloadField = dataBlock ? `\`\`\`json\n${dataBlock}\n\`\`\`` : 'None';
const embed = new DiscordEmbedBuilder()
.setTitle(`Website Webhook: ${eventName}`)
.setDescription(`Actor: **${actor}**`)
.addFields(
{ name: 'Timestamp', value: String(when), inline: false },
{ name: 'Source IP', value: String(payload.ipAddress || 'unknown'), inline: true },
{ name: 'User Agent', value: String(payload.userAgent || 'unknown').slice(0, 200), inline: false },
{ name: 'Payload', value: payloadField, inline: false }
);
channel.send({ embeds: [embed] }).catch(() => null);
}
const webhookApp = express();
webhookApp.use(express.json({
verify: (req, _res, buf) => {
req.rawBody = buf.toString('utf8');
}
}));
function isRuntimeReady() {
if (shutdownInProgress) return false;
if (!client.isReady?.()) return false;
if (client.runtimeHealth.lastDatabaseHealth === false
&& client.runtimeHealth.consecutiveDatabaseHealthFailures >= DB_FAILURE_THRESHOLD) {
return false;
}
return true;
}
function buildRuntimeSnapshot() {
const rawShards = client.ws?.shards;
const shardList = Array.isArray(rawShards)
? rawShards
: Array.from(rawShards?.values?.() || []);
const shardStatus = shardList.map((shard) => ({ id: shard.id, status: shard.status }));
return {
appName,
pid: process.pid,
nodeVersion: process.version,
platform: process.platform,
uptimeMs: process.uptime() * 1000,
shutdownInProgress,
ready: client.isReady?.() || false,
runtimeState: { ...client.runtimeState },
discord: {
userId: client.user?.id || null,
tag: client.user?.tag || null,
pingMs: typeof client.ws?.ping === 'number' ? client.ws.ping : null,
guildCount: client.guilds?.cache?.size || 0,
shardStatus
},
commands: {
loaded: client.slashCommands?.size || 0,
interactionHandlers: {
component: client.interactionHandlers?.component?.length || 0,
modal: client.interactionHandlers?.modal?.length || 0
},
lastRegisteredSignatureLength: String(lastRegisteredCommandSignature || '').length
},
metrics: {
...client.runtimeMetrics,
recentSlowCommands: Array.isArray(client.runtimeMetrics?.recentSlowCommands)
? client.runtimeMetrics.recentSlowCommands.slice(-10)
: []
},
health: { ...client.runtimeHealth },
scheduler: {
active: Boolean(jobScheduler || client.jobScheduler),
reminderTimerActive: Boolean(reminderTimer),
botStatsTimerActive: Boolean(botStatsTimer),
runtimeHealthTimerActive: Boolean(runtimeHealthTimer),
commandWatcherActive: typeof stopCommandWatcher === 'function'
},
memory: process.memoryUsage()
};
}
function hasDiagnosticsAccess(req) {
if (!BOT_WEBHOOK_SECRET) return false;
const provided = String(req.headers['x-bot-secret'] || '').trim();
return Boolean(provided) && provided === BOT_WEBHOOK_SECRET;
}
webhookApp.get('/healthz', (_req, res) => {
res.status(200).json({
ok: true,
shutdownInProgress,
ready: client.isReady?.() || false,
uptimeMs: process.uptime() * 1000,
pingMs: typeof client.ws?.ping === 'number' ? client.ws.ping : null,
databaseHealthy: client.runtimeHealth.lastDatabaseHealth,
consecutiveDatabaseHealthFailures: client.runtimeHealth.consecutiveDatabaseHealthFailures
});
});
webhookApp.get('/readyz', (_req, res) => {
const ready = isRuntimeReady();
res.status(ready ? 200 : 503).json({
ready,
shutdownInProgress,
discordReady: client.isReady?.() || false,
databaseHealthy: client.runtimeHealth.lastDatabaseHealth,
consecutiveDatabaseHealthFailures: client.runtimeHealth.consecutiveDatabaseHealthFailures
});
});
webhookApp.get('/diagnostics', (req, res) => {
if (!hasDiagnosticsAccess(req)) {
return res.status(401).json({ error: 'Unauthorized' });
}
return res.json(buildRuntimeSnapshot());
});
webhookApp.post('/webhooks/website', (req, res) => {
if (!BOT_WEBHOOK_SECRET) {
return res.status(503).json({ error: 'Webhook secret not configured' });
}
if (!verifyWebhookSignature(req, BOT_WEBHOOK_SECRET)) {
return res.status(401).json({ error: 'Invalid webhook signature' });
}
const payload = req.body || {};
dispatchWebsiteWebhook(payload).catch(() => null);
return res.json({ success: true });
});
webhookServer = webhookApp.listen(BOT_WEBHOOK_PORT, () => {
if (!BOT_WEBHOOK_SECRET) {
console.warn('⚠️ Bot webhook server started without BOT_WEBHOOK_SECRET. Requests will be rejected.');
}
client.runtimeState.webhookServerStartedAt = Date.now();
console.log(`🔗 Bot webhook listener running on port ${BOT_WEBHOOK_PORT}`);
});
// Collections for commands, slash commands, and events - handy globals
client.commands = new Collection();
client.slashCommands = new Collection();
client.events = new Collection();
client.interactionHandlers = {
component: [],
modal: []
};
client.runtimeHealth = {
healthCheckIntervalMs: HEALTH_CHECK_INTERVAL_MS,
consecutiveDatabaseHealthFailures: 0,
lastDatabaseHealthCheckAt: null,
lastDatabaseHealth: null,
lastDatabaseHealthError: null
};
client.runtimeMetrics = {
commandsExecuted: 0,
commandErrors: 0,
buttonsHandled: 0,
modalsHandled: 0,
interactionErrors: 0,
lastCommandDurationMs: 0,
slowCommandThresholdMs: Math.max(250, Number(process.env.SLOW_COMMAND_THRESHOLD_MS) || 4000),
recentSlowCommands: []
};
client.jobScheduler = null;
let jobScheduler = null;
let reminderTimer = null;
let botStatsTimer = null;
let runtimeHealthTimer = null;
let runtimeHealthCheckInProgress = false;
let consecutiveDatabaseHealthFailures = 0;
let shutdownInProgress = false;
let stopCommandWatcher = null;
let pendingWatchRegistrationTimer = null;
let lastRegisteredCommandSignature = null;
client.runtimeState = {
startupStartedAt: Date.now(),
initializedAt: null,
loggedInAt: null,
readyAt: null,
shutdownReason: null,
webhookServerStartedAt: null,
lastWebsiteWebhookAt: null,
lastWebsiteWebhookEvent: null,
lastCommandsRegisteredAt: null,
lastCommandsRegisteredReason: null
};
function sleep(ms) {
const safeDelay = Math.max(0, Number(ms) || 0);
return new Promise((resolve) => setTimeout(resolve, safeDelay));
}
// Recursively yield command file paths (.js) from a directory.
// Files or folders that start with '_' are skipped (they're helpers/private).
function* getCommandFiles(dir) {
const files = fs.readdirSync(dir).sort((a, b) => a.localeCompare(b));
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory() && !file.startsWith('_')) {
yield* getCommandFiles(filePath);
} else if (file.endsWith('.js') && !file.startsWith('_')) {
yield filePath;
}
}
}
function buildSlashCommandPayloadsFromCollection(collection) {
const commands = [];
const entries = Array.from(collection?.entries?.() || []).sort(([a], [b]) => String(a).localeCompare(String(b)));
for (const [, command] of entries) {
if (!command?.data || typeof command.data.toJSON !== 'function') continue;
const json = command.data.toJSON();
const category = command.category || 'uncategorized';
if (!json.default_member_permissions) {
if (category === 'moderation') {
json.default_member_permissions = PermissionFlagsBits.ModerateMembers.toString();
}
if (category === 'management') {
json.default_member_permissions = PermissionFlagsBits.Administrator.toString();
}
}
commands.push(json);
}
return commands;
}
function createSlashCommandSignature(commands = []) {
return JSON.stringify(Array.isArray(commands) ? commands : []);
}
function refreshInteractionHandlerRegistry() {
const commands = Array.from(client.slashCommands.values());
client.interactionHandlers.component = commands.filter((command) => typeof command?.handleComponent === 'function');
client.interactionHandlers.modal = commands.filter((command) => typeof command?.handleModal === 'function');
console.log(
`🧩 Interaction handlers ready: buttons=${client.interactionHandlers.component.length}, modals=${client.interactionHandlers.modal.length}`
);
}
function recordSlowCommandMetric(commandName, durationMs) {
const entry = {
commandName: String(commandName || 'unknown'),
durationMs: Math.max(0, Number(durationMs) || 0),
recordedAt: Date.now()
};
client.runtimeMetrics.recentSlowCommands.push(entry);
if (client.runtimeMetrics.recentSlowCommands.length > 25) {
client.runtimeMetrics.recentSlowCommands.shift();
}
}
async function dispatchRegisteredInteraction(interaction, handlerType) {
const handlerList = Array.isArray(client.interactionHandlers?.[handlerType])
? client.interactionHandlers[handlerType]
: [];
for (const command of handlerList) {
const handler = handlerType === 'modal' ? command.handleModal : command.handleComponent;
if (typeof handler !== 'function') continue;
const handled = await handler.call(command, interaction);
if (handled) {
if (handlerType === 'modal') {
client.runtimeMetrics.modalsHandled += 1;
} else {
client.runtimeMetrics.buttonsHandled += 1;
}
return true;
}
}
return false;
}
async function sendInteractionFailure(interaction, content) {
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content,
flags: MessageFlags.Ephemeral
}).catch(() => { });
}
}
// Load and register slash commands with Discord (guild-scoped when possible).
async function registerCommands({ commandsOverride = null, skipIfUnchanged = false, reason = 'manual' } = {}) {
const TOKEN = process.env.TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;
if (!TOKEN || !CLIENT_ID) {
console.error('🗑️Missing TOKEN or CLIENT_ID in environment variables');
return false;
}
const commands = Array.isArray(commandsOverride)
? commandsOverride
: buildSlashCommandPayloadsFromCollection(client.slashCommands);
const signature = createSlashCommandSignature(commands);
if (skipIfUnchanged && signature === lastRegisteredCommandSignature) {
console.log(`↩️ Slash command schema unchanged, skipping registration (${reason}).`);
return true;
}
const rest = new REST({ version: '10' }).setToken(TOKEN);
try {
console.log(`\n⚙️ Registering ${commands.length} commands...`);
// Register to a guild (faster propagation) if `GUILD_ID` is set; otherwise
// register globally which can take longer to appear.
const route = GUILD_ID
? `/applications/${CLIENT_ID}/guilds/${GUILD_ID}/commands`
: `/applications/${CLIENT_ID}/commands`;
const data = await rest.put(route, { body: commands });
console.log(`✅ ${data.length} commands registered\n`);
lastRegisteredCommandSignature = signature;
client.runtimeState.lastCommandsRegisteredAt = Date.now();
client.runtimeState.lastCommandsRegisteredReason = String(reason || 'manual');
return true;
} catch (error) {
console.error('🗑️Error registering commands:', error.message);
return false;
}
}
// Reply with a generic ephemeral error message when a command throws.
async function sendCommandErrorResponse(interaction) {
const errorMessage = {
content: '- There was an error while executing this command!',
flags: MessageFlags.Ephemeral
};
try {
if (interaction.replied || interaction.deferred) {
await interaction.followUp(errorMessage);
} else {
await interaction.reply(errorMessage);
}
} catch (err) {
console.error('Failed to send error response:', err.message);
}
}
async function initializeBot() {
try {
console.log('\n🚀 Starting up...');
// Initialize MySQL connection first
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
await DatabaseManager.initialize();
await eventLoader(client);
const slashLoader = require('./Commands/_slashLoader');
await slashLoader(client.slashCommands).catch((err) => {
console.error("- Couldn't load commands:", err.message);
process.exit(1);
});
client.runtimeState.initializedAt = Date.now();
refreshInteractionHandlerRegistry();
const initialCommandsPayload = buildSlashCommandPayloadsFromCollection(client.slashCommands);
const registered = await registerCommands({ commandsOverride: initialCommandsPayload, reason: 'startup' });
if (!registered) {
console.warn('⚠️ Command registration failed but continuing anyway...');
}
const commandWatchMode = String(process.env.COMMANDS_WATCH_MODE || '').toLowerCase() === 'true';
if (commandWatchMode && typeof slashLoader.createCommandWatcher === 'function') {
const watchRegisterCooldownMs = Math.max(250, Number(process.env.COMMANDS_REGISTER_COOLDOWN_MS) || 2000);
let lastWatchRegisterAt = 0;
const runWatchRegistration = async (event) => {
const commandsPayload = buildSlashCommandPayloadsFromCollection(client.slashCommands);
const syncOk = await registerCommands({ commandsOverride: commandsPayload, skipIfUnchanged: true, reason: event });
if (!syncOk) {
console.warn(`⚠️ Slash command re-registration failed after reload (${event}).`);
return;
}
lastWatchRegisterAt = Date.now();
};
stopCommandWatcher = slashLoader.createCommandWatcher({
collection: client.slashCommands,
watchDir: './Commands',
debounceMs: Number(process.env.COMMANDS_WATCH_DEBOUNCE_MS) || 500,
onReload: async ({ event, result }) => {
console.log(`🔄 Reloaded slash commands (${event}) -> loaded=${result.loaded}, errors=${result.errors}`);
refreshInteractionHandlerRegistry();
if (result?.errors > 0) {
console.warn('⚠️ Skipping slash command registration because loader reported errors.');
return;
}
const elapsed = Date.now() - lastWatchRegisterAt;
if (elapsed < watchRegisterCooldownMs) {
const waitMs = watchRegisterCooldownMs - elapsed;
console.log(`⏳ Slash registration cooldown active (${waitMs}ms remaining) after ${event}; scheduling deferred sync.`);
if (pendingWatchRegistrationTimer) {
clearTimeout(pendingWatchRegistrationTimer);
}
pendingWatchRegistrationTimer = setTimeout(() => {
pendingWatchRegistrationTimer = null;
console.log(`🕒 Running deferred slash registration sync (trigger: ${event}).`);
runWatchRegistration(`cooldown:${event}`).catch((error) => {
console.warn('⚠️ Deferred slash registration failed:', error?.message || error);
});
}, waitMs);
return;
}
await runWatchRegistration(event);
}
});
}
require("./Logging/index")(client);
restoreGiveaways(client);
startReminderChecker(client);
jobScheduler = new JobScheduler(client);
await jobScheduler.start();
client.jobScheduler = jobScheduler;
} catch (error) {
console.error('🗑️Fatal error during bot initialization:', error);
process.exit(1);
}
}
/**
* Start the periodic reminder checker. Runs once immediately and then on an interval.
* Responsible for delivering due reminders (DMs) and retrying or notifying staff on failures.
*/
function startReminderChecker(client) {
const { reminderCheckInterval } = MISC.timeouts;
// Check immediately on startup
checkPendingReminders(client);
// Check every so often
reminderTimer = setInterval(() => {
checkPendingReminders(client);
}, reminderCheckInterval);
if (typeof reminderTimer.unref === 'function') {
reminderTimer.unref();
}
console.log(`⏰ Reminder system started (checking every ${reminderCheckInterval / 1000}s)`);
}
function startRuntimeHealthMonitor() {
if (runtimeHealthTimer) {
clearInterval(runtimeHealthTimer);
runtimeHealthTimer = null;
}
runtimeHealthTimer = setInterval(async () => {
if (runtimeHealthCheckInProgress || shutdownInProgress) return;
runtimeHealthCheckInProgress = true;
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const health = await DatabaseManager.getDatabaseHealth();
if (health?.ok) {
if (consecutiveDatabaseHealthFailures > 0) {
console.log('✅ Database health restored');
}
consecutiveDatabaseHealthFailures = 0;
} else {
consecutiveDatabaseHealthFailures += 1;
console.warn(
`⚠️ Database health check failed (${consecutiveDatabaseHealthFailures}/${DB_FAILURE_THRESHOLD})${health?.error ? `: ${health.error}` : ''}`
);
if (consecutiveDatabaseHealthFailures >= DB_FAILURE_THRESHOLD) {
console.warn('♻️ Attempting database reconnection...');
const reinitialized = await DatabaseManager.initialize();
if (reinitialized) {
consecutiveDatabaseHealthFailures = 0;
console.log('✅ Database reconnection successful');
} else {
console.error('🗑️Database reconnection attempt failed');
}
}
}
client.runtimeHealth.consecutiveDatabaseHealthFailures = consecutiveDatabaseHealthFailures;
client.runtimeHealth.lastDatabaseHealthCheckAt = Date.now();
client.runtimeHealth.lastDatabaseHealth = Boolean(health?.ok);
client.runtimeHealth.lastDatabaseHealthError = health?.error || null;
if (typeof client.ws?.ping === 'number' && client.ws.ping > 15_000) {
console.warn(`⚠️ High Discord gateway ping detected: ${client.ws.ping}ms`);
}
} catch (error) {
consecutiveDatabaseHealthFailures += 1;
client.runtimeHealth.consecutiveDatabaseHealthFailures = consecutiveDatabaseHealthFailures;
client.runtimeHealth.lastDatabaseHealthCheckAt = Date.now();
client.runtimeHealth.lastDatabaseHealth = false;
client.runtimeHealth.lastDatabaseHealthError = error?.message || 'Runtime health check failed';
console.error('[Health] Runtime health check failed:', error.message || error);
} finally {
runtimeHealthCheckInProgress = false;
}
}, HEALTH_CHECK_INTERVAL_MS);
if (typeof runtimeHealthTimer.unref === 'function') {
runtimeHealthTimer.unref();
}
console.log(`🩺 Runtime health monitor started (${HEALTH_CHECK_INTERVAL_MS / 1000}s interval)`);
}
async function loginWithRetry(clientInstance, token) {
let attempt = 0;
let delayMs = LOGIN_BASE_RETRY_DELAY_MS;
while (attempt < LOGIN_MAX_ATTEMPTS) {
attempt += 1;
try {
await clientInstance.login(token);
if (attempt > 1) {
console.log(`✅ Discord login succeeded on attempt ${attempt}/${LOGIN_MAX_ATTEMPTS}`);
}
return true;
} catch (error) {
const isFinal = attempt >= LOGIN_MAX_ATTEMPTS;
console.error(`- Discord login failed (attempt ${attempt}/${LOGIN_MAX_ATTEMPTS}): ${error.message}`);
if (isFinal) {
throw error;
}
await sleep(delayMs);
delayMs = Math.min(LOGIN_MAX_RETRY_DELAY_MS, delayMs * 2);
}
}
return false;
}
async function gracefulShutdown(reason = 'shutdown', exitCode = 0) {
if (shutdownInProgress) return;
shutdownInProgress = true;
client.runtimeState.shutdownReason = String(reason || 'shutdown');
console.log(`\n🛑 Shutting down (${reason})...`);
const shutdownTask = (async () => {
try {
if (runtimeHealthTimer) {
clearInterval(runtimeHealthTimer);
runtimeHealthTimer = null;
}
if (reminderTimer) {
clearInterval(reminderTimer);
reminderTimer = null;
}
if (botStatsTimer) {
clearInterval(botStatsTimer);
botStatsTimer = null;
}
if (jobScheduler && typeof jobScheduler.stop === 'function') {
jobScheduler.stop();
}
if (typeof stopCommandWatcher === 'function') {
stopCommandWatcher();
stopCommandWatcher = null;
}
if (pendingWatchRegistrationTimer) {
clearTimeout(pendingWatchRegistrationTimer);
pendingWatchRegistrationTimer = null;
}
if (webhookServer) {
await new Promise((resolve) => {
webhookServer.close(() => resolve());
}).catch(() => { });
webhookServer = null;
}
if (client && typeof client.destroy === 'function') {
await client.destroy().catch(() => { });
}
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
if (DatabaseManager?.connection?.close) {
await DatabaseManager.connection.close();
}
} catch (closeError) {
console.warn('⚠️ Failed to close database connection cleanly:', closeError.message);
}
} catch (error) {
console.error('🗑️Error during graceful shutdown:', error.message || error);
}
})();
await Promise.race([
shutdownTask,
sleep(SHUTDOWN_TIMEOUT_MS)
]);
process.exit(exitCode);
}
// Process pending reminders from the database and deliver them when due.
async function checkPendingReminders(client) {
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const { EmbedBuilder } = require('discord.js');
const moment = require('moment-timezone');
const { reminders: reminderConfig } = MISC;
const remindDB = DatabaseManager.getRemindersDB();
const now = Date.now();
// Get all reminders
const allReminders = Object.values(await remindDB.all());
for (const reminder of allReminders) {
// Skip if already completed
if (reminder.completed) continue;
// Skip if not yet due
if (reminder.triggerAt > now) continue;
try {
// Initialize delivery attempt tracking
if (!reminder.deliveryAttempts) {
reminder.deliveryAttempts = 0;
}
// Fetch user
const user = await client.users.fetch(reminder.userId).catch(() => null);
if (!user) {
console.log(`[Remind] User not found for reminder ${reminder.id}: ${reminder.userId}`);
reminder.completed = true;
await remindDB.set(reminder.id, reminder);
continue;
}
// Create reminder embed
const reminderEmbed = new EmbedBuilder()
.setColor(0xFFD700)
.setTitle('🔔 Reminder!')
.setDescription(reminder.message)
.setFooter({ text: `Set ${moment(reminder.createdAt).fromNow()}` })
.setTimestamp();
try {
// Attempt to send reminder DM first - mark as completed ONLY after successful send
await user.send({ embeds: [reminderEmbed] });
console.log(`[Remind] Reminder delivered to ${user.tag}`);
// ONLY mark as completed AFTER successful send to prevent race conditions
reminder.completed = true;
await remindDB.set(reminder.id, reminder);
// Clean up after a delay
setTimeout(async () => {
await remindDB.delete(reminder.id);
}, 300000); // Keep for 5 minutes then delete
} catch (dmError) {
// DM failed - implement retry logic
reminder.deliveryAttempts++;
reminder.lastFailureReason = dmError.message;
reminder.lastFailureTime = Date.now();
console.warn(`[Remind] DM delivery failed for ${user.tag} (attempt ${reminder.deliveryAttempts}/${reminderConfig.maxDeliveryAttempts}): ${dmError.message}`);
// Check if we've exceeded max attempts
if (reminder.deliveryAttempts >= reminderConfig.maxDeliveryAttempts) {
console.error(`[Remind] Max delivery attempts reached for reminder ${reminder.id}`);
// Try to notify in notification channel
const notificationChannelId = CHANNELS.notificationChannelId;
if (notificationChannelId && notificationChannelId !== 'YOUR_NOTIFICATIONS_CHANNEL_ID') {
try {
const channel = await client.channels.fetch(notificationChannelId).catch(() => null);
if (channel && channel.isTextBased()) {
const failedEmbed = new EmbedBuilder()
.setColor(0xFF6B6B)
.setTitle('- Reminder Delivery Failed')
.setDescription(`Could not deliver reminder to <@${reminder.userId}>`)
.addFields(
{ name: '💬 Message', value: reminder.message, inline: false },
{ name: '⚠️ Reason', value: dmError.message, inline: false },
{ name: '📝 Note', value: 'User may have DMs disabled or has left the server', inline: false }
)
.setFooter({ text: `Reminder ID: ${reminder.id}` })
.setTimestamp();
await channel.send({ embeds: [failedEmbed] }).catch(sendErr => {
console.error(`[Remind] Failed to notify staff channel: ${sendErr.message}`);
});
console.log(`[Remind] Notified staff channel about failed reminder for ${reminder.userId}`);
}
} catch (notifyError) {
console.error(`[Remind] Could not send notification to staff channel: ${notifyError.message}`);
}
}
// Mark as completed after max attempts
reminder.completed = true;
await remindDB.set(reminder.id, reminder);
} else {
// Schedule retry - reset triggerAt to retry in configured minutes
const retryDelayMs = reminderConfig.retryDelayMinutes * 60 * 1000;
reminder.triggerAt = Date.now() + retryDelayMs;
console.log(`[Remind] Scheduled retry for ${user.tag} in ${reminderConfig.retryDelayMinutes} minutes`);
await remindDB.set(reminder.id, reminder);
}
}
} catch (error) {
console.error(`[Remind] Error processing reminder ${reminder.id}: ${error.message}`);
}
}
} catch (error) {
console.error('[Remind] Error in reminder checker:', error.message);
}
}
// Restore active giveaways from the database and resume their countdowns.
async function restoreGiveaways(client) {
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const giveawayDB = DatabaseManager.getGiveawaysDB();
const allGiveaways = Object.values(await giveawayDB.all());
let restored = 0;
let invalid = 0;
if (!allGiveaways || allGiveaways.length === 0) {
return;
}
for (const giveaway of allGiveaways) {
if (!giveaway || giveaway.completed) continue;
// Ensure giveaway has all required fields; delete invalid entries to avoid buildup.
if (!giveaway.channelId || !giveaway.messageId || !giveaway.endTime || !giveaway.prize) {
console.log(`[Giveaway] Invalid giveaway data, cleaning up: ${JSON.stringify(giveaway)}`);
// DELETE invalid giveaway from database to prevent accumulation
try {
await giveawayDB.delete(giveaway.id || giveaway.messageId);
invalid++;
} catch (deleteErr) {
console.error(`[Giveaway] Failed to delete invalid entry: ${deleteErr.message}`);
}
continue;
}
try {
const channel = await client.channels.fetch(giveaway.channelId).catch(() => null);
if (!channel) continue;
const message = await channel.messages.fetch(giveaway.messageId).catch(() => null);
if (!message) continue;
// Calculate remaining time
const timeRemaining = Math.max(0, giveaway.endTime - Date.now());
// If giveaway has already ended, finalize it
if (timeRemaining === 0) {
await finalizeGiveawayFromDB(message, giveaway, client);
restored++;
continue;
}
// Resume countdown for giveaway
const durationInSeconds = Math.ceil(timeRemaining / 1000);
runGiveawayCountdown(message, giveaway.messageId, client, durationInSeconds, giveaway.prize, giveaway.hostName);
restored++;
console.log(`[Giveaway] ${giveaway.prize} - ${Math.ceil(timeRemaining / 1000)}s left`);
} catch (error) {
console.error(`[Giveaway] Couldn't restore ${giveaway.messageId}: ${error.message}`);
}
}
} catch (error) {
console.error('[Giveaway] Error in giveaway restoration:', error.message);
}
}
// End a giveaway that ended while bot was offline
async function finalizeGiveawayFromDB(message, giveaway, client) {
try {
let participants = Array.isArray(giveaway?.entries) ? [...new Set(giveaway.entries)] : [];
const winnerCount = Math.max(1, Number(giveaway?.winnerCount || 1));
// Check if message and reactions exist
if (message && message.reactions && message.reactions.cache) {
const reaction = message.reactions.cache.get('🎉');
if (reaction && participants.length === 0) {
try {
const users = await reaction.users.fetch();
participants = users.filter(user => !user.bot).map(user => user.id);
} catch (err) {
console.error('[Giveaway] Could not fetch reaction users:', err.message);
}
}
} else {
console.warn('[Giveaway] Message reactions not available for finalization');
}
// Ensure the message can be edited. If not, mark the giveaway completed to
// avoid retry loops; don't attempt to edit a non-editable object.
if (!message || typeof message.edit !== 'function') {
console.warn('[Giveaway] Cannot finalize - message object is invalid or missing edit method');
// Mark as completed anyway to prevent retry loops - but don't try to save if we don't have valid data
if (giveaway && (giveaway.messageId || giveaway.id)) {
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const giveawayDB = DatabaseManager.getGiveawaysDB();
giveaway.completed = true;
giveaway.ended = true;
const giveawayId = giveaway.id || giveaway.messageId;
await giveawayDB.set(giveawayId, giveaway);
} catch (err) {
console.error('[Giveaway] Could not mark as completed:', err.message);
}
}
return;
}
let endEmbed;
if (participants.length === 0) {
endEmbed = {
color: 16744171,
title: '- No Winners',
description: `━━━━━━━━━━━━━━━━━━━━━\n\nUnfortunately, nobody reacted to the **${giveaway.prize}** giveaway.\n\n**Better luck next time!** 🍀\n\n━━━━━━━━━━━━━━━━━━━━━`,
fields: [
{ name: '🎁 Prize', value: `**${giveaway.prize}**`, inline: true },
{ name: '👥 Total Reactions', value: '0', inline: true }
],
footer: { text: 'Giveaway Ended - No participants' },
timestamp: new Date()
};
} else {
const shuffled = [...participants].sort(() => Math.random() - 0.5);
const winnerIds = shuffled.slice(0, Math.min(winnerCount, shuffled.length));
const winnerMentions = winnerIds.map((id) => `<@${id}>`).join('\n');
endEmbed = {
color: 65280,
title: winnerIds.length > 1 ? '🏆 Giveaway Winners Announced!' : '🏆 Giveaway Winner Announced!',
description: `━━━━━━━━━━━━━━━━━━━━━\n\n🎉 **Congratulations!** 🎉\n\nYou won the **${giveaway.prize}** giveaway!\n\n━━━━━━━━━━━━━━━━━━━━━`,
fields: [
{ name: '🎁 Prize Won', value: `**${giveaway.prize}**`, inline: true },
{ name: winnerIds.length > 1 ? '🥇 Winners' : '🥇 Winner', value: winnerMentions.slice(0, 1024), inline: false },
{ name: '👥 Total Participants', value: `**${participants.length}**`, inline: true },
{ name: '🏆 Winner Count', value: `**${winnerIds.length}**`, inline: true }