-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.ts
More file actions
1539 lines (1308 loc) · 50 KB
/
Copy pathbot.ts
File metadata and controls
1539 lines (1308 loc) · 50 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
/**
* The Roommates Helper - Discord Bot
* ---------------------------------
* A utility bot for the Roommates Discord server with features including:
* - Color role management
* - Age verification system
* - Message logging system
* - Welcome DM system
* - Warning system with escalating punishments
* - NSFW access toggle system
* - Discord log forwarding
* - Rotating status system
* - Dynamic description management
* - Guild management (auto-leave unwanted servers)
* - Music Bot
*
* @license MIT
* @copyright 2025 Clove Twilight
*/
//=============================================================================
// IMPORTS
//=============================================================================
import {
Client,
GatewayIntentBits,
ActivityType,
REST,
Routes,
SlashCommandBuilder,
ChatInputCommandInteraction,
EmbedBuilder,
ComponentType,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder,
ActionRowBuilder,
Role,
DiscordAPIError,
ButtonInteraction,
Interaction,
Events,
ModalSubmitInteraction,
GuildMember,
MessageFlags
} from 'discord.js';
import dotenv from 'dotenv';
import fs from 'fs';
//=============================================================================
// IMPORT DISCORD LOGGER
//=============================================================================
import { discordLogger } from './discord-logger';
//=============================================================================
// IMPORT OTHER SYSTEMS
//=============================================================================
import {
registerVerificationCommands,
setupVerificationSystem,
handleVerifyCommand,
handleModVerifyCommand,
handleVerificationButton,
handleVerificationDecision,
getAgeUnverifiedRoleId,
loadVerificationConfig
} from './verification';
import {
handleVerificationContinue,
handleVerificationCancel,
handleVerificationUpload,
handleVerificationModal
} from './verification';
import {
registerMessageLoggerCommands,
setupMessageLogger,
handleLoggerCommand,
loadMessageLoggerConfig,
testLoggerChannel
} from './message-logger';
import {
setupWelcomeDM,
sendWelcomeDM
} from './welcome-dm';
import {
registerModCommands,
setupWarningSystem,
handleModCommand,
handleModButtonInteraction,
handleModModalSubmit,
} from './warning-system';
import { writeHealthStatus } from './healthcheck';
// Import rotating status system
import {
setupRotatingStatus,
stopRotatingStatus,
setTemporaryStatus,
setStaticStatus
} from './rotating-status';
// Import bot description manager
import {
setupBotDescription,
setupDescriptionShutdownHandlers,
setBotDescriptionStarting,
setBotDescriptionOnline,
setBotDescriptionUpdating
} from './bot-description';
// Import music system
import { MusicManager } from './music/music-manager';
import { registerMusicCommands, handleMusicCommand } from './music/commands';
//=============================================================================
// BOT INITIALIZATION
//=============================================================================
// Track bot startup time
const startTime = Date.now();
writeHealthStatus('starting', startTime);
// Load environment variables from .env file
dotenv.config();
// Bot configuration
const BOT_NAME = process.env.BOT_NAME || "The Roommates Helper";
const SERVER_NAME = process.env.SERVER_NAME || "Roommates";
const TOKEN = process.env.DISCORD_TOKEN;
if (!TOKEN) throw new Error('DISCORD_TOKEN is not set in environment variables');
const CLIENT_ID = process.env.CLIENT_ID;
if (!CLIENT_ID) throw new Error('CLIENT_ID is not set in environment variables');
const AGE_UNVERIFIED_ROLE_ID = process.env.AGE_UNVERIFIED_ROLE_ID;
if (!AGE_UNVERIFIED_ROLE_ID) throw new Error('AGE_UNVERIFIED_ROLE_ID is not set in environment variables');
const NSFW_ACCESS_ROLE_ID = process.env.NSFW_ACCESS_ROLE_ID;
if (!NSFW_ACCESS_ROLE_ID) throw new Error('NSFW_ACCESS_ROLE_ID is not set in environment variables');
const NSFW_NO_ACCESS_ROLE_ID = process.env.NSFW_NO_ACCESS_ROLE_ID;
if (!NSFW_NO_ACCESS_ROLE_ID) throw new Error('NSFW_NO_ACCESS_ROLE_ID is not set in environment variables');
const GUILD_TO_KEEP = process.env.GUILD_ID;
if (!GUILD_TO_KEEP) throw new Error('GUILD_ID is not set in environment variables');
// Create a new client instance with ALL required intents
const client = new Client({
intents: [
// Base intents
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
// Message-related intents - REQUIRED for message logging
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
// DM intents
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
// Voice intents - REQUIRED for music
GatewayIntentBits.GuildVoiceStates
]
});
// Initialize music manager AFTER client creation
const musicManager = new MusicManager(client);
//=============================================================================
// GUILD MANAGEMENT SYSTEM
//=============================================================================
/**
* Check and leave all guilds except the specified one
*/
async function manageGuilds() {
try {
console.log('🔄 Checking guild membership...');
// Get all guilds the bot is in
const guilds = client.guilds.cache;
console.log(`Bot is currently in ${guilds.size} guild(s)`);
if (guilds.size === 0) {
console.log('Bot is not in any guilds.');
return;
}
// List all guilds for reference
console.log('\nCurrent guilds:');
guilds.forEach((guild: any) => {
console.log(`- ${guild.name} (ID: ${guild.id})`);
});
// Check if the bot is in the target guild
const targetGuild = guilds.get(GUILD_TO_KEEP!);
if (!targetGuild) {
console.log(`⚠️ Bot is not in the target guild (ID: ${GUILD_TO_KEEP})`);
console.log('Available guild IDs:');
guilds.forEach((guild: any) => console.log(`- ${guild.id} (${guild.name})`));
return;
}
console.log(`✅ Target guild found: ${targetGuild.name} (${targetGuild.id})`);
// Count guilds to leave
const guildsToLeave = guilds.filter((guild: any) => guild.id !== GUILD_TO_KEEP);
if (guildsToLeave.size === 0) {
console.log('✅ Bot is only in the target guild. No action needed.');
return;
}
console.log(`🚪 Leaving ${guildsToLeave.size} unwanted guild(s)...`);
// Set temporary status while leaving guilds
setTemporaryStatus(client, 'guild cleanup', ActivityType.Custom, 30000, '🧹 Spring cleaning');
// Leave unwanted guilds
let leftCount = 0;
for (const [guildId, guild] of guildsToLeave) {
try {
await guild.leave();
console.log(`✅ Left: ${guild.name} (${guild.id})`);
leftCount++;
// Log to Discord
safeDiscordLog('info', `Left unwanted guild: ${guild.name}`, 'GuildManager');
// Add delay to avoid rate limits
await new Promise(resolve => setTimeout(resolve, 1000));
} catch (error) {
console.error(`❌ Failed to leave ${guild.name}:`, error);
safeDiscordLog('error', `Failed to leave guild ${guild.name}: ${error}`, 'GuildManager');
}
}
if (leftCount > 0) {
console.log(`🎉 Successfully left ${leftCount} guild(s)`);
console.log(`✅ Remaining in: ${targetGuild.name}`);
safeDiscordLog('info', `Guild cleanup complete: Left ${leftCount} guild(s), staying in ${targetGuild.name}`, 'GuildManager');
}
} catch (error) {
console.error('❌ Error in guild management:', error);
safeDiscordLog('error', `Guild management error: ${error}`, 'GuildManager');
}
}
//=============================================================================
// SAFE LOGGING SETUP (NO LOOPS!)
//=============================================================================
// Store original console methods
const originalConsoleLog = console.log;
const originalConsoleError = console.error;
const originalConsoleWarn = console.warn;
// Flag to prevent recursive logging
let isLoggingToDiscord = false;
// Safe Discord logging function
function safeDiscordLog(level: 'info' | 'warn' | 'error', message: string, source: string = 'Bot') {
if (isLoggingToDiscord) return; // Prevent recursion
isLoggingToDiscord = true;
try {
switch (level) {
case 'info':
discordLogger.info(message, source);
break;
case 'warn':
discordLogger.warn(message, source);
break;
case 'error':
discordLogger.error(message, source);
break;
}
} catch (error) {
// Use original console to avoid loops
originalConsoleError('Error in Discord logging:', error);
} finally {
isLoggingToDiscord = false;
}
}
// Override console methods (safer version)
console.log = (...args: any[]) => {
const message = args.join(' ');
originalConsoleLog(...args);
// Only send important messages to Discord
if (!isLoggingToDiscord && (
message.toLowerCase().includes('✅') ||
message.toLowerCase().includes('🚀') ||
message.toLowerCase().includes('ready') ||
message.toLowerCase().includes('online') ||
message.toLowerCase().includes('started') ||
message.toLowerCase().includes('loaded') ||
message.toLowerCase().includes('success')
)) {
safeDiscordLog('info', message, 'Bot');
}
};
console.error = (...args: any[]) => {
const message = args.join(' ');
originalConsoleError(...args);
if (!isLoggingToDiscord) {
safeDiscordLog('error', message, 'Bot');
}
};
console.warn = (...args: any[]) => {
const message = args.join(' ');
originalConsoleWarn(...args);
if (!isLoggingToDiscord) {
safeDiscordLog('warn', message, 'Bot');
}
};
// Log what events the client is listening for
console.log("Discord.js Events supported by this client instance:");
console.log("MessageCreate:", client.listenerCount(Events.MessageCreate));
console.log("MessageUpdate:", client.listenerCount(Events.MessageUpdate));
console.log("MessageDelete:", client.listenerCount(Events.MessageDelete));
//=============================================================================
// COLOR ROLE MANAGEMENT
//=============================================================================
// Role management
interface ColorRole {
id: string;
name: string;
hexColor: string;
}
// Store our color roles
let colorRoles: ColorRole[] = [];
let colorCategories: Record<string, ColorRole[]> = {};
/**
* Load color roles from the file
*/
function loadColorRolesFromFile(filePath: string = 'roommates_roles.txt'): void {
try {
console.log(`🔄 Loading color roles from ${filePath}...`);
const fileContent = fs.readFileSync(filePath, 'utf8');
const lines = fileContent.split('\n');
// Reset the roles array
colorRoles = [];
// Parse each line in the format [ROLE_NAME, ROLE_ID]
for (const line of lines) {
// Skip empty lines
if (!line.trim()) continue;
// Extract role name and ID
const match = line.match(/\[(.*?), (\d+)\]/);
if (match && match.length >= 3) {
const name = match[1];
const id = match[2];
// Skip non-color roles
const skipRoles = [
'@everyone', 'moderator', 'verified!', 'PluralKit', 'TTS Bot',
'carl-bot', 'Captcha.bot', 'Zahra', 'Doughmination System',
'You have name privileges', 'You\'ve lost name privileges',
'MF BOTS ARE ASSHOLES', '18+', 'new role', 'soundboard',
'Age Unverified', 'NSFW Access', 'NSFW No Access'
];
if (skipRoles.includes(name)) continue;
// Add to our color roles array
colorRoles.push({
id,
name,
hexColor: '#FFFFFF'
});
}
}
console.log(`✅ Loaded ${colorRoles.length} color roles successfully`);
// Categorize color roles
categorizeColorRoles();
} catch (error) {
console.error(`❌ Error loading color roles from ${filePath}:`, error);
safeDiscordLog('error', `Error loading color roles: ${error}`, 'ColorRoles');
writeHealthStatus('offline', startTime);
}
}
/**
* Categorize color roles for easier selection
*/
function categorizeColorRoles(): void {
// Reset categories
colorCategories = {};
// Create categories based on color names
const categories = {
'Red': ['Red', 'Crimson', 'Scarlet', 'Cherry', 'Bean', 'Love', 'Wine', 'Valentine', 'Maroon'],
'Pink': ['Pink', 'Rose', 'Blush', 'Hot Pink', 'Deep Pink', 'Neon Pink', 'Cadillac Pink', 'Carnation Pink', 'Light Pink', 'Watermelon Pink', 'Pig Pink'],
'Orange': ['Orange', 'Mango', 'Cantaloupe', 'Coral', 'Light Coral', 'Light Salmon', 'Saffron'],
'Yellow': ['Yellow', 'Gold', 'Light Yellow', 'Sun Yellow', 'Electric Yellow', 'Lemon', 'Harvest Gold', 'Bright Gold', 'Mustard', 'Champagne', 'Cream', 'Parchment'],
'Green': ['Green', 'Lime', 'Forest', 'Mint', 'Sage', 'Sea', 'Kelly', 'Avocado', 'Fern', 'Jungle', 'Lawn', 'Chartreuse', 'Dragon', 'Venom', 'Algae', 'Alien', 'Stoplight Go', 'Hummingbird', 'Nebula', 'Hoja', 'Literally Shrek', 'Light Sea Green', 'Medium Sea Green', 'Sea Turtle Green'],
'Cyan': ['Cyan', 'Teal', 'Aquamarine', 'Light Aquamarine', 'Medium Aquamarine', 'Turquoise', 'Medium Turquoise', 'Light Cyan', 'Dark Turquoise', 'Tiffany Blue', 'Cyan Opaque'],
'Blue': ['Blue', 'Navy', 'Sky', 'Light Blue', 'Deep Sky Blue', 'Baby Blue', 'Royal Blue', 'Steel Blue', 'Light Steel Blue', 'Powder Blue', 'Alice Blue', 'Dodger Blue', 'Cornflower Blue', 'Medium Blue', 'Midnight Blue', 'Light Sky Blue', 'Day Sky Blue', 'Columbia Blue', 'Jeans Blue', 'Denim Blue', 'Denim Dark Blue', 'Dark Slate Blue', 'Blue Lagoon', 'Blue Jay', 'Blue Angel', 'Blue Eyes', 'Blue Whale', 'Blue Koi', 'Blue Ivy', 'Blue Dress', 'Blue Diamond', 'Blue Zircon', 'Blue Green', 'Blue Gray', 'Blue Hosta', 'Blueberry Blue', 'Electric Blue', 'Cobalt Blue', 'Sapphire Blue', 'Crystal Blue', 'Earth Blue', 'Ocean Blue', 'Windows Blue', 'Pastel Blue', 'Northern Lights Blue', 'Robbin Egg Blue', 'Light Slate Blue', 'Iceberg', 'Butterfly Blue', 'Glacial Blue Ice', 'Silk Blue', 'Lapis Blue', 'Jelly Fish'],
'Purple': ['Purple', 'Violet', 'Indigo', 'Lavender', 'Plum', 'Mauve', 'Magneta', 'Helitrope Purple', 'Crocus Purple', 'Lovely Purple', 'Purple Flower', 'Purple Iris', 'Purple Mimosa', 'Aztech Purple', 'Purple Ametyhst', 'Tyrian Purple', 'Plum Velvet', 'Lavender Blue'],
'Gray': ['Gray', 'Light Slate Gray', 'Dark Slate Gray', 'Light Slate', 'Gray Goose', 'Platinum', 'Metallic Silver'],
'Black & White': ['Black', 'White', 'Night', 'Oil', 'Discord Shadow']
};
// Function to find which category a role belongs to
const findCategory = (roleName: string): string => {
for (const [category, keywords] of Object.entries(categories)) {
if (keywords.some(keyword =>
roleName.toLowerCase().includes(keyword.toLowerCase()))) {
return category;
}
}
return 'Other';
};
// Categorize each role
for (const role of colorRoles) {
const category = findCategory(role.name);
if (!colorCategories[category]) {
colorCategories[category] = [];
}
colorCategories[category].push(role);
}
// Sort roles alphabetically within each category
for (const category in colorCategories) {
colorCategories[category].sort((a, b) => a.name.localeCompare(b.name));
}
// Log categories
const categoryInfo = Object.entries(colorCategories)
.map(([category, roles]) => `${category}: ${roles.length}`)
.join(', ');
console.log(`✅ Color categories created: ${categoryInfo}`);
}
//=============================================================================
// NSFW ACCESS MANAGEMENT
//=============================================================================
/**
* Handle the NSFW toggle command
*/
async function handleNSFWCommand(interaction: ChatInputCommandInteraction) {
if (!interaction.guild) {
await interaction.reply({ content: 'This command can only be used in a server!', flags: MessageFlags.Ephemeral });
return;
}
// Check if NSFW roles are configured
if (!NSFW_ACCESS_ROLE_ID || !NSFW_NO_ACCESS_ROLE_ID) {
await interaction.reply({
content: 'NSFW roles are not properly configured. Please contact an administrator.',
flags: MessageFlags.Ephemeral
});
return;
}
const member = interaction.guild.members.cache.get(interaction.user.id);
if (!member) {
await interaction.reply({ content: 'Could not find you in this server!', ephemeral: true });
return;
}
const nsfwValue = interaction.options.getBoolean('value', true);
try {
// Get the roles
const nsfwAccessRole = interaction.guild.roles.cache.get(NSFW_ACCESS_ROLE_ID);
const nsfwNoAccessRole = interaction.guild.roles.cache.get(NSFW_NO_ACCESS_ROLE_ID);
if (!nsfwAccessRole || !nsfwNoAccessRole) {
await interaction.reply({
content: 'NSFW roles not found in this server. Please contact an administrator.',
flags: MessageFlags.Ephemeral
});
return;
}
if (nsfwValue) {
// User wants NSFW access
if (member.roles.cache.has(NSFW_NO_ACCESS_ROLE_ID)) {
await member.roles.remove(nsfwNoAccessRole);
}
if (!member.roles.cache.has(NSFW_ACCESS_ROLE_ID)) {
await member.roles.add(nsfwAccessRole);
}
safeDiscordLog('info', `User ${interaction.user.tag} enabled NSFW access`, 'NSFW');
// Set temporary status for NSFW access change
setTemporaryStatus(client, 'NSFW access requests', ActivityType.Custom, 10000, '🔓 Access granted');
const embed = new EmbedBuilder()
.setTitle('NSFW Access Enabled')
.setDescription('You now have access to NSFW content.')
.setColor(0x00FF00)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true
});
} else {
// User wants to disable NSFW access
if (member.roles.cache.has(NSFW_ACCESS_ROLE_ID)) {
await member.roles.remove(nsfwAccessRole);
}
if (!member.roles.cache.has(NSFW_NO_ACCESS_ROLE_ID)) {
await member.roles.add(nsfwNoAccessRole);
}
safeDiscordLog('info', `User ${interaction.user.tag} disabled NSFW access`, 'NSFW');
// Set temporary status for NSFW access change
setTemporaryStatus(client, 'NSFW access requests', ActivityType.Custom, 10000, '🔒 Access revoked');
const embed = new EmbedBuilder()
.setTitle('NSFW Access Disabled')
.setDescription('You no longer have access to NSFW content.')
.setColor(0xFF9900)
.setTimestamp();
await interaction.reply({
embeds: [embed],
flags: MessageFlags.Ephemeral
});
}
} catch (error) {
console.error(`❌ Error handling NSFW toggle for ${interaction.user.tag}:`, error);
await interaction.reply({
content: 'There was an error updating your NSFW access. Please try again later.',
flags: MessageFlags.Ephemeral
});
}
}
//=============================================================================
// COMMAND REGISTRATION
//=============================================================================
/**
* Register slash commands
*/
async function registerCommands() {
const commands = [
new SlashCommandBuilder()
.setName('color')
.setDescription('Manage your color role')
.addSubcommand((subcommand: any) =>
subcommand
.setName('select')
.setDescription('Choose a color role')
)
.addSubcommand((subcommand: any) =>
subcommand
.setName('remove')
.setDescription('Remove your current color role')
)
.toJSON(),
new SlashCommandBuilder()
.setName('nsfw')
.setDescription('Toggle your NSFW content access')
.addBooleanOption((option: any) =>
option
.setName('value')
.setDescription('Enable (true) or disable (false) NSFW access')
.setRequired(true)
)
.toJSON(),
];
// Add verification commands to the array
registerVerificationCommands(commands);
// Add message logger commands to the array
registerMessageLoggerCommands(commands);
// Add moderation commands to the array
registerModCommands(commands);
// Add Music Commands
registerMusicCommands(commands, musicManager);
try {
console.log('🔄 Started refreshing application (/) commands');
const rest = new REST({ version: '10' }).setToken(TOKEN!);
// Check if we have a specific guild ID for development
const GUILD_ID = process.env.GUILD_ID;
if (GUILD_ID) {
// Guild commands update instantly
console.log(`🔄 Registering commands to guild: ${GUILD_ID}`);
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID!, GUILD_ID!),
{ body: commands },
);
console.log(`✅ Successfully registered ${commands.length} commands to guild`);
} else {
// Global commands can take up to an hour to propagate
console.log('🔄 Registering global commands (this can take up to an hour to propagate)');
await rest.put(
Routes.applicationCommands(CLIENT_ID!),
{ body: commands },
);
console.log(`✅ Successfully registered ${commands.length} global commands`);
}
} catch (error) {
console.error('❌ Error registering commands:', error);
writeHealthStatus('offline', startTime);
}
}
//=============================================================================
// COMMAND ID LOGGING
//=============================================================================
/**
* Fetch and log all registered command IDs in mention format
*/
async function logCommandIds(client: Client) {
try {
console.log('🔄 Fetching command IDs...');
const GUILD_ID = process.env.GUILD_ID;
let commands;
if (GUILD_ID) {
const guild = await client.guilds.fetch(GUILD_ID);
commands = await guild.commands.fetch();
console.log(`\nGuild Commands (${guild.name}):`);
} else {
commands = await client.application?.commands.fetch();
console.log('\nGlobal Commands:');
}
if (!commands || commands.size === 0) {
console.log('❌ No commands found!');
safeDiscordLog('warn', 'No commands found during ID fetch', 'Commands');
return;
}
console.log(`✅ Found ${commands.size} commands\n`);
// Sort commands alphabetically by name
const sortedCommands = Array.from(commands.values()).sort((a: any, b: any) => a.name.localeCompare(b.name));
console.log('📋 COMMAND MENTIONS (Copy these to use in Discord):');
console.log('═'.repeat(60));
// Build command mentions for Discord
let commandMentions = '**Command Mentions:**\n';
sortedCommands.forEach(command => {
// Handle commands with subcommands
if ((command as any).options && (command as any).options.length > 0) {
const subcommands = (command as any).options.filter((option: any) => option.type === 1); // SUB_COMMAND type
if (subcommands.length > 0) {
console.log(`\n🔸 ${command.name.toUpperCase()} (has subcommands):`);
commandMentions += `\n**${command.name.toUpperCase()}** (subcommands):\n`;
subcommands.forEach((sub: any) => {
const mention = `</${command.name} ${sub.name}:${command.id}>`;
console.log(` ${mention}`);
commandMentions += `• ${mention}\n`;
});
} else {
const mention = `</${command.name}:${command.id}>`;
console.log(mention);
commandMentions += `• ${mention}\n`;
}
} else {
const mention = `</${command.name}:${command.id}>`;
console.log(mention);
commandMentions += `• ${mention}\n`;
}
});
console.log('\n' + '═'.repeat(60));
console.log('📊 RAW COMMAND DATA:');
console.log('═'.repeat(60));
let rawData = '**Raw Command Data:**\n```\n';
sortedCommands.forEach(command => {
const line = `${command.name.padEnd(20)} | ${command.id}`;
console.log(line);
rawData += `${line}\n`;
});
rawData += '```';
// Send to Discord safely
safeDiscordLog('info', `Command IDs fetched successfully - ${commands.size} commands found`, 'Commands');
console.log('\n=== COMMAND ID FETCH COMPLETE ===\n');
} catch (error) {
console.error('❌ Error fetching command IDs:', error);
}
}
//=============================================================================
// COLOR ROLE COMMANDS
//=============================================================================
/**
* Handle the color select subcommand
*/
async function handleColorSelectCommand(interaction: ChatInputCommandInteraction) {
// Check if we have any color categories
if (Object.keys(colorCategories).length === 0) {
await interaction.reply({
content: 'No color roles found. Please contact a server administrator.',
flags: MessageFlags.Ephemeral
});
return;
}
// Create a select menu for color categories
const selectMenu = new StringSelectMenuBuilder()
.setCustomId('color_category_select')
.setPlaceholder('Choose a color category')
.addOptions(
Object.keys(colorCategories)
.filter(category => colorCategories[category].length > 0)
.map(category =>
new StringSelectMenuOptionBuilder()
.setLabel(category)
.setDescription(`${colorCategories[category].length} colors available`)
.setValue(category)
)
);
const row = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents(selectMenu);
// Set a higher time limit for the interaction (2 minutes instead of 1)
const message = await interaction.reply({
content: 'Select a color category:',
components: [row],
flags: MessageFlags.Ephemeral,
fetchReply: true // Make sure to fetch the reply for the collector
});
// Set up a collector for the menu interaction
const filter = (i: any) => i.user.id === interaction.user.id;
const collector = message.createMessageComponentCollector({
filter,
time: 120000, // Increased timeout to 2 minutes
componentType: ComponentType.StringSelect
});
collector.on('collect', async (i: any) => {
try {
if (i.customId === 'color_category_select') {
const selectedCategory = i.values[0];
await showColorsForCategory(i, selectedCategory);
}
else if (i.customId === 'color_select') {
const roleId = i.values[0];
await assignColorRole(i, roleId);
}
} catch (error) {
// Handle any errors that occur during interaction
console.error('Error handling interaction:', error);
// Only attempt to reply if the interaction hasn't been responded to yet
if (!i.replied && !i.deferred) {
try {
await i.reply({
content: 'An error occurred while processing your selection. Please try again.',
ephemeral: true
});
} catch (replyError) {
console.error('Error sending error message:', replyError);
}
}
}
});
collector.on('end', async (collected: any, reason: any) => {
if (reason === 'time') {
try {
// Check if the message still exists and can be edited
await interaction.editReply({
content: 'Color selection timed out. Please use the command again if you still want toselect a color.',
components: []
});
} catch (error) {
console.error('Error updating message after timeout:', error);
}
}
});
}
/**
* Show colors for a specific category
*/
async function showColorsForCategory(interaction: any, category: string) {
try {
if (!colorCategories[category] || colorCategories[category].length === 0) {
await interaction.update({
content: 'No colors available in this category. Please try another one.',
components: []
}).catch((error: any) => {
console.error('Error updating interaction with no colors message:', error);
});
return;
}
// Get colors from this category
const colors = colorCategories[category];
// Discord has a 25-option limit for select menus
const maxOptionsPerMenu = 25;
// If we have more than 25 colors, we'll need to handle it
if (colors.length > maxOptionsPerMenu) {
// For simplicity, just take the first 25 for now
// In a production bot, you'd implement pagination here
const colorsToShow = colors.slice(0, maxOptionsPerMenu);
const colorSelect = new StringSelectMenuBuilder()
.setCustomId('color_select')
.setPlaceholder(`Choose a color from ${category}`)
.addOptions(
colorsToShow.map(color =>
new StringSelectMenuOptionBuilder()
.setLabel(color.name)
.setValue(color.id)
)
);
const row = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents(colorSelect);
await interaction.update({
content: `Select a color from ${category} (showing first ${maxOptionsPerMenu} of ${colors.length}):`,
components: [row]
}).catch((error: any) => {
console.error('Error updating interaction with color options:', error);
});
} else {
const colorSelect = new StringSelectMenuBuilder()
.setCustomId('color_select')
.setPlaceholder(`Choose a color from ${category}`)
.addOptions(
colors.map(color =>
new StringSelectMenuOptionBuilder()
.setLabel(color.name)
.setValue(color.id)
)
);
const row = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents(colorSelect);
await interaction.update({
content: `Select a color from ${category}:`,
components: [row]
}).catch((error: any) => {
console.error('Error updating interaction with color options:', error);
// If the error is an Unknown Interaction error, the interaction has expired
if (error instanceof DiscordAPIError && error.code === 10062) {
console.log('Interaction has expired. The user will need to run the command again.');
}
});
}
} catch (error) {
console.error('Error in showColorsForCategory:', error);
}
}
/**
* Assign the selected color role
*/
async function assignColorRole(interaction: any, roleId: string) {
try {
if (!interaction.guild) {
await interaction.update({
content: 'This command can only be used in a server!',
components: []
}).catch((error: any) => {
console.error('Error updating interaction with guild error message:', error);
});
return;
}
const member = interaction.guild.members.cache.get(interaction.user.id);
if (!member) {
await interaction.update({
content: 'Could not find you in this server!',
components: []
}).catch((error: any) => {
console.error('Error updating interaction with member error message:', error);
});
return;
}
// Find the role
const role = interaction.guild.roles.cache.get(roleId);
if (!role) {
await interaction.update({
content: 'Error: Color role not found. Please try again or contact an admin.',
components: []
}).catch((error: any) => {
console.error('Error updating interaction with role error message:', error);
});
return;
}
try {
// Remove any existing color roles
await removeExistingColorRoles(member);
// Assign the new role
await member.roles.add(role);
// Log the color change
safeDiscordLog('info', `User ${interaction.user.tag} changed color to ${role.name}`, 'ColorRoles');
// Set temporary status for color change
setTemporaryStatus(client, 'with colors', ActivityType.Playing, 8000);
// Create an embed to show the result
const embed = new EmbedBuilder()
.setTitle('Color Changed!')
.setDescription(`You now have the ${role.name} color!`)
.setColor(role.color);
await interaction.update({
content: '',
embeds: [embed],
components: []
}).catch((error: any) => {
console.error('Error updating interaction with success message:', error);
// If it's an Unknown Interaction error, just log it
if (error instanceof DiscordAPIError && error.code === 10062) {
console.log('Interaction has expired, but the role was still assigned successfully.');
}
});
} catch (error) {
console.error('Error assigning color role:', error);
// Try to update the interaction with an error message
try {
await interaction.update({
content: 'There was an error assigning the color role. Please try again later.',
components: []
});
} catch (updateError) {
console.error('Error sending error message:', updateError);
}
}
} catch (error) {
console.error('Error in assignColorRole:', error);
}
}
/**
* Handle the color remove subcommand
*/
async function handleColorRemoveCommand(interaction: ChatInputCommandInteraction, member: any) {
try {
const removed = await removeExistingColorRoles(member);
if (removed) {
safeDiscordLog('info', `User ${interaction.user.tag} removed their color role`, 'ColorRoles');
// Set temporary status for color removal
setTemporaryStatus(client, 'color removal', ActivityType.Custom, 8000, '🗑️ Color deleted');
await interaction.reply({