-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
828 lines (708 loc) · 30.8 KB
/
index.js
File metadata and controls
828 lines (708 loc) · 30.8 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
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 fs = require('fs');
const path = require('path');
const { updateStats } = require('./Functions/botStats');
const eventLoader = require('./Events/_loader');
const JobScheduler = require('./Functions/JobScheduler');
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`;
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"),
});
// Collections for commands, slash commands, and events — handy globals
client.commands = new Collection();
client.slashCommands = new Collection();
client.events = new Collection();
let jobScheduler = null;
// 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);
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;
}
}
}
// Load and register slash commands with Discord (guild-scoped when possible).
async function registerCommands() {
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 = [];
const commandsPath = path.join(__dirname, 'Commands');
try {
// Load each command module, apply reasonable default permissions for
// moderation/management categories, and collect the JSON payloads.
for (const filePath of getCommandFiles(commandsPath)) {
try {
const command = require(filePath);
if (command.data) {
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);
}
} catch (err) {
console.error(` ❌ Error loading command ${filePath}: ${err.message}`);
}
}
} catch (err) {
console.error('❌ Error scanning command directory:', err.message);
return false;
}
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`);
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);
await require("./Commands/_slashLoader")(client.slashCommands).catch((err) => {
console.error("❌ Couldn't load commands:", err.message);
process.exit(1);
});
const registered = await registerCommands();
if (!registered) {
console.warn('⚠️ Command registration failed but continuing anyway...');
}
require("./Logging/index")(client);
restoreGiveaways(client);
startReminderChecker(client);
jobScheduler = new JobScheduler(client);
await jobScheduler.start();
} 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 } = require('./Config/constants/misc.json').timeouts;
// Check immediately on startup
checkPendingReminders(client);
// Check every so often
setInterval(() => {
checkPendingReminders(client);
}, reminderCheckInterval);
console.log(`⏰ Reminder system started (checking every ${reminderCheckInterval / 1000}s)`);
}
// 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 } = require('./Config/constants/misc.json');
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 = reminderConfig.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 = [];
// Check if message and reactions exist
if (message && message.reactions && message.reactions.cache) {
const reaction = message.reactions.cache.get('🎉');
if (reaction) {
try {
const users = await reaction.users.fetch();
participants = users.filter(user => !user.bot).map(user => user.username);
} 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 winner = participants[Math.floor(Math.random() * participants.length)];
endEmbed = {
color: 65280,
title: '🏆 Giveaway Winner Announced!',
description: `━━━━━━━━━━━━━━━━━━━━━\n\n🎉 **Congratulations ${winner}!** 🎉\n\nYou have won the **${giveaway.prize}** giveaway!\n\n━━━━━━━━━━━━━━━━━━━━━`,
fields: [
{ name: '🎁 Prize Won', value: `**${giveaway.prize}**`, inline: true },
{ name: '🥇 Winner', value: `**${winner}**`, inline: true },
{ name: '👥 Total Participants', value: `**${participants.length}**`, inline: true },
{ name: '📊 Winning Chance', value: `**${((1 / participants.length) * 100).toFixed(2)}%**`, inline: true }
],
footer: { text: '🎊 Giveaway Ended - Congratulations to the winner!' },
timestamp: new Date()
};
}
await message.edit({ embeds: [endEmbed] }).catch((err) => {
console.error(`[Giveaway] Failed to update end embed: ${err.message}`);
});
// Mark as completed in database
try {
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const giveawayDB = DatabaseManager.getGiveawaysDB();
giveaway.completed = true;
giveaway.ended = true;
const giveawayId = giveaway.id || giveaway.messageId;
if (giveawayId) {
await giveawayDB.set(giveawayId, giveaway);
} else {
console.warn('[Giveaway] Cannot save - no valid ID found');
}
} catch (err) {
console.error('[Giveaway] Error saving completed status:', err.message);
}
} catch (error) {
console.error('[Giveaway] Error finalizing restored giveaway:', error.message);
}
}
// Update the giveaway message periodically while the countdown runs.
async function runGiveawayCountdown(message, giveawayId, client, duration, prize, host) {
let timeRemaining = duration;
const updateInterval = Math.min(30, Math.max(5, Math.floor(duration / 10)));
while (timeRemaining > 0) {
await sleep(updateInterval * 1000);
timeRemaining -= updateInterval;
try {
const reaction = message.reactions.cache.get('🎉');
const participantCount = reaction ? reaction.count - 1 : 0;
const countdownEmbed = {
color: 16766680,
title: '🎉 Giveaway in Progress!',
description: '━━━━━━━━━━━━━━━━━━━━━\n\n⏳ **Giveaway is still running!**\n\n━━━━━━━━━━━━━━━━━━━━━',
fields: [
{ name: '🎁 Prize', value: `**${prize}**`, inline: true },
{ name: '⏱️ Time Remaining', value: `**${toTime(timeRemaining)}**`, inline: true },
{ name: '👤 Hosted by', value: host, inline: true },
{ name: '🎪 Participants', value: `**${participantCount}** 🎯`, inline: true }
],
footer: { text: '⚡ Keep reacting to participate! The winner will be selected when time runs out.' },
timestamp: new Date()
};
await message.edit({ embeds: [countdownEmbed] }).catch((err) => {
console.error(`[Giveaway] Failed to update countdown: ${err.message}`);
});
} catch (error) {
console.error('Error updating giveaway:', error);
}
}
// Giveaway ended
await finalizeGiveaway(message, giveawayId, client, prize, host);
}
// Format a duration given in seconds into a human-friendly string.
function toTime(seconds) {
seconds = Number(seconds);
const d = Math.floor(seconds / (3600 * 24));
const h = Math.floor((seconds % (3600 * 24)) / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
const dDisplay = d > 0 ? `${d}${d === 1 ? ' day' : ' days'}, ` : '';
const hDisplay = h > 0 ? `${h}${h === 1 ? ' hour' : ' hours'}, ` : '';
const mDisplay = m > 0 ? `${m}${m === 1 ? ' minute' : ' minutes'}, ` : '';
const sDisplay = s > 0 ? `${s}${s === 1 ? ' second' : ' seconds'}` : '';
const result = `${dDisplay}${hDisplay}${mDisplay}${sDisplay}`.replace(/, $/, '');
return result || '0 seconds';
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Select a giveaway winner (random) and update the end embed accordingly.
async function finalizeGiveaway(message, giveawayId, client, prize, host) {
try {
const reaction = await message.reactions.cache.get('🎉');
const users = reaction ? await reaction.users.fetch() : new Map();
const participants = users.filter(user => !user.bot).map(user => user.username);
let endEmbed;
if (participants.length === 0) {
endEmbed = {
color: 16744171,
title: '❌ No Winners',
description: `━━━━━━━━━━━━━━━━━━━━━\n\nUnfortunately, nobody reacted to the **${prize}** giveaway.\n\n**Better luck next time!** 🍀\n\n━━━━━━━━━━━━━━━━━━━━━`,
fields: [
{ name: '🎁 Prize', value: `**${prize}**`, inline: true },
{ name: '👥 Total Reactions', value: '0', inline: true }
],
footer: { text: 'Giveaway Ended - No participants' },
timestamp: new Date()
};
} else {
const winner = participants[Math.floor(Math.random() * participants.length)];
endEmbed = {
color: 65280,
title: '🏆 Giveaway Winner Announced!',
description: `━━━━━━━━━━━━━━━━━━━━━\n\n🎉 **Congratulations ${winner}!** 🎉\n\nYou have won the **${prize}** giveaway!\n\n━━━━━━━━━━━━━━━━━━━━━`,
fields: [
{ name: '🎁 Prize Won', value: `**${prize}**`, inline: true },
{ name: '🥇 Winner', value: `**${winner}**`, inline: true },
{ name: '👥 Total Participants', value: `**${participants.length}**`, inline: true },
{ name: '📊 Winning Chance', value: `**${((1 / participants.length) * 100).toFixed(2)}%**`, inline: true }
],
footer: { text: '🎊 Giveaway Ended - Congratulations to the winner!' },
timestamp: new Date()
};
}
await message.edit({ embeds: [endEmbed] }).catch((err) => {
console.error(`[Giveaway] Failed to update end embed: ${err.message}`);
});
// Mark as completed in database
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
const giveawayDB = DatabaseManager.getGiveawaysDB();
const giveaway = await giveawayDB.get(giveawayId);
if (giveaway) {
giveaway.completed = true;
await giveawayDB.set(giveawayId, giveaway);
}
} catch (error) {
console.error('Error finalizing giveaway:', error);
}
}
// Handle slash command interactions: permission checks, rate limiting, execution.
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = client.slashCommands.get(interaction.commandName);
if (!command) {
console.warn(`⚠️ No command matching /${interaction.commandName} was found.`);
return;
}
// Rate limiting
const RateLimiter = require('./Functions/RateLimiter');
const { administratorRoleId, moderatorRoleId } = require('./Config/constants/roles.json');
const DatabaseManager = require('./Functions/MySQLDatabaseManager');
// Role and permission checks for moderation/management commands
const category = command.category || 'uncategorized';
const member = interaction.member;
const logInteraction = async (status, errorMessage = null) => {
try {
await DatabaseManager.logUserInteraction({
userId: interaction.user?.id,
username: interaction.user?.username,
commandName: interaction.commandName,
commandCategory: category,
guildId: interaction.guild?.id,
channelId: interaction.channelId,
status,
errorMessage
});
} catch (err) {
// Avoid blocking command flow on logging issues
}
};
if (category === 'moderation' || category === 'management') {
const hasModeratorRole = member?.roles?.cache?.has(moderatorRoleId);
const hasAdminRole = member?.roles?.cache?.has(administratorRoleId);
const hasModeratePermission = member?.permissions?.has('ModerateMembers');
const hasAdminPermission = member?.permissions?.has('Administrator');
const roleAllowed = category === 'management' ? hasAdminRole : (hasAdminRole || hasModeratorRole);
const permissionAllowed = category === 'management' ? hasAdminPermission : (hasAdminPermission || hasModeratePermission);
if (!roleAllowed || !permissionAllowed) {
await logInteraction('PERMISSION', 'Missing required role or permissions');
return interaction.reply({
content: '❌ You do not have the required role and permissions for this command.',
flags: MessageFlags.Ephemeral
}).catch(() => { });
}
}
// Determine if the user is exempt from rate limits (admins/mods).
const isExempt = RateLimiter.isExempt(interaction.member, [administratorRoleId, moderatorRoleId]);
if (!isExempt) {
const rateLimit = RateLimiter.checkLimit(interaction.user.id, interaction.commandName);
if (rateLimit.limited) {
const errorMessage = rateLimit.type === 'global'
? `⏱️ You're using commands too quickly! Please wait **${rateLimit.retryAfter}s** before trying again.`
: `⏱️ You're using this command too quickly! Please wait **${rateLimit.retryAfter}s** before using \`/${interaction.commandName}\` again.`;
await logInteraction('RATE_LIMIT', errorMessage);
return interaction.reply({
content: errorMessage,
flags: MessageFlags.Ephemeral
}).catch(() => { });
}
// Record usage
RateLimiter.recordUsage(interaction.user.id, interaction.commandName);
}
try {
await command.execute(interaction);
await logInteraction('SUCCESS');
} catch (error) {
console.error(`❌ Error executing command /${interaction.commandName}:`, error.message);
await logInteraction('ERROR', error.message);
await sendCommandErrorResponse(interaction);
}
});
// Make sure required environment variables exist and have values; exit with
// clear instructions if anything is missing.
function validateEnvironment() {
const required = {
'TOKEN': 'Discord Bot Token',
'CLIENT_ID': 'Discord Application ID',
'GUILD_ID': 'Discord Server ID'
};
const missing = [];
const empty = [];
for (const [key, description] of Object.entries(required)) {
if (!(key in process.env)) {
missing.push(`${key} (${description})`);
} else if (!process.env[key] || process.env[key].trim() === '') {
empty.push(`${key} (${description})`);
}
}
if (missing.length > 0) {
console.error('❌ Missing required environment variables:');
missing.forEach(item => console.error(` - ${item}`));
console.error('\n📖 Please configure these in Config/credentials.env\n');
process.exit(1);
}
if (empty.length > 0) {
console.error('❌ Empty environment variables (must have values):');
empty.forEach(item => console.error(` - ${item}`));
console.error('\n📖 Please add values in Config/credentials.env\n');
process.exit(1);
}
console.log('✅ All required environment variables configured\n');
}
client.once("clientReady", () => {
client.emit("commandsAndEventsLoaded", 1);
// Send bot stats immediately on ready, then update every 30 seconds.
const updateBotStats = () => {
try {
const guildCount = client.guilds.cache.size;
let totalMembers = 0;
let botMembers = 0;
// Count total members and bots
client.guilds.cache.forEach(guild => {
totalMembers += guild.memberCount;
// Count bots in this guild
guild.members.cache.forEach(member => {
if (member.user.bot) botMembers++;
});
});
const totalRoles = client.guilds.cache.reduce((acc, guild) => acc + guild.roles.cache.size, 0);
const totalChannels = client.guilds.cache.reduce((acc, guild) => acc + guild.channels.cache.size, 0);
const totalEmojis = client.guilds.cache.reduce((acc, guild) => acc + guild.emojis.cache.size, 0);
updateStats({
uptime: Math.floor(client.uptime / 1000), // Convert to seconds
guildCount: guildCount,
totalMembers: totalMembers,
botMembers: botMembers,
totalRoles: totalRoles,
totalChannels: totalChannels,
totalEmojis: totalEmojis,
commandsLoaded: client.slashCommands.size,
eventsLoaded: eventLoader.getEventCount()
});
} catch (err) {
console.error('Error updating bot stats:', err.message);
}
};
// Update immediately on ready
updateBotStats();
// Then update every 30 seconds
setInterval(updateBotStats, 30000);
});
client.on('error', (err) => {
console.error('❌ Client error:', err.message);
});
client.on('warn', (msg) => {
console.warn('⚠️ Client warn:', msg);
});
// Log unhandled promise rejections and exit to avoid inconsistent state.
process.on('unhandledRejection', (err) => {
console.error('❌ Unhandled Promise Rejection:', err);
process.exit(1);
});
// Log uncaught exceptions and exit to prevent the bot from running in a bad state.
process.on('uncaughtException', (err) => {
console.error('❌ Uncaught Exception:', err);
process.exit(1);
});
// Graceful shutdown on SIGINT: destroy the client and exit cleanly.
process.on('SIGINT', async () => {
console.log('\n🛑 Shutting down...');
await client.destroy();
process.exit(0);
});
// Start everything
(async () => {
try {
validateEnvironment();
await initializeBot();
client.login(process.env.TOKEN);
// Start admin panel if enabled
if (process.env.ENABLE_ADMIN_PANEL !== 'false') {
try {
const adminPanel = require('./adminPanel');
if (typeof adminPanel.setDiscordClient === 'function') {
adminPanel.setDiscordClient(client);
}
console.log('Admin Panel: Enabled');
} catch (err) {
console.warn('⚠️ Admin panel could not start:', err.message);
}
}
} catch (err) {
console.error('❌ Fatal error during startup:', err.message);
process.exit(1);
}
})();