-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindex.js
More file actions
506 lines (424 loc) · 19.9 KB
/
Copy pathindex.js
File metadata and controls
506 lines (424 loc) · 19.9 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
const { Client, GatewayIntentBits, Collection, Events, ActivityType } = require('discord.js');
const { getVoiceConnection } = require('@discordjs/voice');
const fs = require('fs');
const fsPromises = require('fs').promises;
const path = require('path');
const config = require('./config');
const PlayerStateManager = require('./src/PlayerStateManager');
const MusicPlayer = require('./src/MusicPlayer');
const chalk = require('chalk');
require("./src/commandLoader"); // Load and deploy commands
// Clean up audio cache directory on startup
async function cleanupAudioCache() {
const cacheDir = path.join(__dirname, 'audio_cache');
try {
if (fs.existsSync(cacheDir)) {
const files = await fsPromises.readdir(cacheDir);
const protectedFiles = PlayerStateManager.getProtectedCacheFiles();
let deletedCount = 0;
let skippedCount = 0;
for (const file of files) {
const absolutePath = path.join(cacheDir, file);
if (protectedFiles.has(path.resolve(absolutePath))) {
skippedCount++;
continue;
}
try {
await fsPromises.unlink(absolutePath);
deletedCount++;
} catch (err) {
console.error(chalk.red(`❌ Failed to delete ${file}:`), err.message);
}
}
} else {
fs.mkdirSync(cacheDir, { recursive: true });
}
} catch (error) {
console.error(chalk.red('❌ Failed to cleanup audio cache:'), error.message);
}
}
async function restoreSavedPlayers(client) {
const savedStates = PlayerStateManager.getAllStates();
const entries = Object.entries(savedStates || {});
if (entries.length === 0) return;
console.log(chalk.cyan(`🔄 Found ${entries.length} saved session(s) to restore...`));
for (const [guildId, state] of entries) {
try {
// Wait for guild to be available in cache
let guild = client.guilds.cache.get(guildId);
if (!guild) {
// Try fetching with retry logic for sharding
let retries = 3;
while (!guild && retries > 0) {
try {
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
guild = await client.guilds.fetch(guildId).catch(() => null);
if (guild) break;
} catch (error) {
retries--;
}
}
}
if (!guild) {
console.log(chalk.yellow(`⚠️ Guild ${guildId} not found or not accessible, removing state...`));
await PlayerStateManager.removeState(guildId);
continue;
}
const voiceChannelId = state.voiceChannelId;
const textChannelId = state.textChannelId;
if (!voiceChannelId || !textChannelId) {
await PlayerStateManager.removeState(guildId);
continue;
}
let voiceChannel = guild.channels.cache.get(voiceChannelId) || null;
if (!voiceChannel) {
voiceChannel = await guild.channels.fetch(voiceChannelId).catch(() => null);
}
let textChannel = guild.channels.cache.get(textChannelId) || null;
if (!textChannel) {
textChannel = await guild.channels.fetch(textChannelId).catch(() => null);
}
const isVoiceValid = voiceChannel && typeof voiceChannel.isVoiceBased === 'function' && voiceChannel.isVoiceBased();
const isTextValid = textChannel && typeof textChannel.isTextBased === 'function' && textChannel.isTextBased();
if (!isVoiceValid || !isTextValid) {
console.log(chalk.yellow(`⚠️ Invalid channels for guild ${guild.name}, removing state...`));
await PlayerStateManager.removeState(guildId);
continue;
}
const player = new MusicPlayer(guild, textChannel, voiceChannel);
client.players.set(guildId, player);
try {
await player.restoreFromState(state);
console.log(chalk.green(`✅ Successfully restored session for guild ${guild.name}`));
} catch (error) {
console.error(chalk.red(`❌ Failed to restore music session for guild ${guild.name} (${guildId}):`), error.message);
client.players.delete(guildId);
player.cleanup();
await PlayerStateManager.removeState(guildId);
}
} catch (error) {
console.error(chalk.red(`❌ Error during session restoration for guild ${guildId}:`), error.message);
await PlayerStateManager.removeState(guildId);
}
}
}
// Don't cleanup audio cache yet - wait until after we check saved states
setTimeout(() => {
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMembers,
]
// ShardingManager automatically sets shard ID and count via environment variables
// No need to specify shards/shardCount here - they are auto-injected
});
// Collections for commands and music players
client.commands = new Collection();
client.players = new Collection();
// Initialize Music Embed Manager
const MusicEmbedManager = require('./src/MusicEmbedManager');
client.musicEmbedManager = new MusicEmbedManager(client);
// Global reference for MusicPlayer'dan erişim
if (!global.clients) global.clients = {};
global.clients.musicEmbedManager = client.musicEmbedManager;
// Load command files
const loadCommands = () => {
const commandsPath = path.join(__dirname, 'commands');
// Create commands directory if it doesn't exist
if (!fs.existsSync(commandsPath)) {
fs.mkdirSync(commandsPath, { recursive: true });
}
try {
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
console.log(chalk.green(`✓ Loaded command: ${command.data.name}`));
} else {
console.log(chalk.yellow(`⚠ Warning: ${file} is missing required "data" or "execute" property.`));
}
}
} catch (error) {
console.log(chalk.yellow('⚠ No commands directory found, skipping command loading.'));
}
};
// Load event handlers
const loadEvents = () => {
const eventsPath = path.join(__dirname, 'events');
// Create events directory if it doesn't exist
if (!fs.existsSync(eventsPath)) {
fs.mkdirSync(eventsPath, { recursive: true });
}
try {
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
console.log(chalk.green(`✓ Loaded event: ${event.name}`));
}
} catch (error) {
console.log(chalk.yellow('⚠ No events directory found, using default events.'));
}
};
// Basic ready event
client.once(Events.ClientReady, async () => {
console.log(chalk.green(`✅ [SHARD ${client.shard?.ids[0] ?? 0}] ${client.user.tag} is online and ready!`));
console.log(chalk.cyan(`🎵 [SHARD ${client.shard?.ids[0] ?? 0}] Music bot serving ${client.guilds.cache.size} servers on this shard!`));
// Log total guild count across all shards (only if running with sharding)
// Wait a bit to ensure all shards are ready before fetching
if (client.shard) {
setTimeout(() => {
client.shard.fetchClientValues('guilds.cache.size')
.then(results => {
const totalGuilds = results.reduce((acc, guildCount) => acc + guildCount, 0);
console.log(chalk.magenta(`🌐 [SHARD ${client.shard.ids[0]}] Total servers across all shards: ${totalGuilds}`));
})
.catch(err => {
// Silently fail if shards are still spawning
if (!err.message.includes('still being spawned')) {
console.error(chalk.red('Error fetching total guild count:'), err);
}
});
}, 10000); // Wait 10 seconds for other shards to be ready
}
// Set bot activity
setInterval(() => client.user.setActivity({ name: `${config.bot.status}`, type: ActivityType.Listening }), 10000);
// Don't restore here in sharded mode - wait for shard manager to broadcast
// For non-sharded mode, restore immediately
if (!client.shard) {
console.log(chalk.cyan('⏳ Non-sharded mode: waiting for guilds to be fully cached...'));
await new Promise(resolve => setTimeout(resolve, 5000));
await client.restoreSessions();
}
});
// Add restore function to client for shard manager to call
client.restoreSessions = async function() {
console.log(chalk.cyan(`[SHARD ${client.shard?.ids?.[0] ?? 'N/A'}] 🔄 Starting session restore...`));
await restoreSavedPlayers(client);
await cleanupAudioCache();
console.log(chalk.green(`[SHARD ${client.shard?.ids?.[0] ?? 'N/A'}] ✅ Session restore complete`));
};
// Handle interactions (slash commands)
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) {
console.error(chalk.red(`❌ No command matching ${interaction.commandName} was found.`));
return;
}
try {
await command.execute(interaction, client);
} catch (error) {
console.error(chalk.red(`❌ Error executing ${interaction.commandName}:`), error);
const errorMessage = '❌ An error occurred while executing this command!';
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: errorMessage, ephemeral: true });
} else {
await interaction.reply({ content: errorMessage, ephemeral: true });
}
}
});
// Handle voice state updates for pause/resume and cleanup
client.on(Events.VoiceStateUpdate, async (oldState, newState) => {
const guild = oldState.guild;
const player = client.players.get(guild.id);
if (!player) return;
const botMember = guild.members.me;
const botId = botMember?.id ?? client.user.id;
const involvesBot = oldState.id === botId || newState.id === botId;
if (involvesBot) {
const oldChannelId = oldState.channelId;
const newChannelId = newState.channelId;
if (oldChannelId && !newChannelId) {
try {
const embedManager = client.musicEmbedManager || global.clients?.musicEmbedManager;
// Mark state as ended so UI reflects the change
player.pendingEndReason = 'forced-disconnect';
player.queue = [];
player.currentTrack = null;
if (embedManager) {
await embedManager.handlePlaybackEnd(player);
} else if (typeof player.showQueueCompleted === 'function') {
await player.showQueueCompleted();
}
} catch (error) {
console.error('❌ Failed to update playback UI after forced disconnect:', error);
} finally {
player.cleanup();
client.players.delete(guild.id);
}
return;
}
if (newChannelId && oldChannelId !== newChannelId) {
if (newState.channel) {
await player.moveToChannel(newState.channel);
player.clearInactivityTimer(false);
if (client.musicEmbedManager) {
await client.musicEmbedManager.updateNowPlayingEmbed(player);
}
}
}
const wasMuted = oldState.serverMute || oldState.serverDeaf || oldState.suppress;
const isMuted = newState.serverMute || newState.serverDeaf || newState.suppress;
if (!wasMuted && isMuted) {
const paused = player.pauseFor('mute');
if (paused && client.musicEmbedManager) {
await client.musicEmbedManager.updateNowPlayingEmbed(player);
}
} else if (wasMuted && !isMuted) {
const resumed = player.resumeFor('mute');
if (client.musicEmbedManager && (resumed || !player.pauseReasons.has('mute'))) {
await client.musicEmbedManager.updateNowPlayingEmbed(player);
}
}
}
const voiceChannelId = player.voiceChannel?.id;
if (!voiceChannelId) return;
if (oldState.channelId === voiceChannelId || newState.channelId === voiceChannelId) {
const channel = guild.channels.cache.get(voiceChannelId);
if (!channel) {
player.cleanup();
client.players.delete(guild.id);
return;
}
const listeners = channel.members.filter(member => !member.user.bot).size;
if (listeners === 0) {
const alreadyPaused = player.pauseReasons.has('alone');
player.startInactivityTimer();
if (!alreadyPaused && client.musicEmbedManager && player.currentTrack) {
await client.musicEmbedManager.updateNowPlayingEmbed(player);
}
} else {
const wasPausedForAlone = player.pauseReasons.has('alone');
player.clearInactivityTimer(true);
if (wasPausedForAlone && client.musicEmbedManager && player.currentTrack) {
await client.musicEmbedManager.updateNowPlayingEmbed(player);
}
}
}
});
// Handle process termination
process.on('SIGINT', () => {
// Disconnect from all voice channels
client.players.forEach((player, guildId) => {
player.stop();
const connection = getVoiceConnection(guildId);
if (connection) connection.destroy();
});
client.destroy();
process.exit(0);
});
// Error handling
process.on('unhandledRejection', (reason, promise) => {
console.error(chalk.red('❌ Unhandled Rejection at:'), promise, chalk.red('reason:'), reason);
// Discord API error handling
if (reason && reason.code) {
switch (reason.code) {
case 10062: // Unknown interaction
console.log(chalk.yellow('ℹ️ Interaction has expired, safely ignoring...'));
return;
case 40060: // Interaction already acknowledged
console.log(chalk.yellow('ℹ️ Interaction already acknowledged, safely ignoring...'));
return;
case 50013: // Missing permissions
console.error(chalk.red('❌ Missing permissions for Discord action'));
return;
}
}
// Voice connection errors
if (reason && reason.message && reason.message.includes('IP discovery')) {
// Clean up any voice connections
client.players.forEach(player => {
if (player && player.cleanup) {
player.cleanup();
}
});
client.players.clear();
return;
}
});
process.on('uncaughtException', (error) => {
console.error(chalk.red('❌ Uncaught Exception:'), error);
// Don't exit on Discord API errors
if (error.code === 10062 || error.code === 40060) {
console.log(chalk.yellow('ℹ️ Discord interaction error handled, continuing...'));
return;
}
// Handle fetch/network termination errors - don't crash
if (error.message && (error.message.includes('terminated') ||
error.message.includes('ECONNRESET') ||
error.message.includes('ETIMEDOUT'))) {
console.log(chalk.yellow('⚠️ Network error occurred, but bot continues running...'));
return;
}
// For other critical errors, graceful shutdown
console.log(chalk.red('🛑 Critical error occurred, shutting down...'));
// Clean up all music players
if (client && client.players) {
client.players.forEach(player => {
if (player && player.cleanup) {
player.cleanup();
}
});
client.players.clear();
}
process.exit(1);
});
// Initialize bot
const init = async () => {
try {
console.log(chalk.blue('🤖 Starting Discord Music Bot...'));
// Load commands and events
loadCommands();
loadEvents();
// Graceful shutdown handler
const gracefulShutdown = async (signal) => {
// Save all active player states before shutdown
const savePromises = [];
for (const [guildId, player] of client.players) {
if (player && typeof player.persistState === 'function') {
// Use immediate=true to bypass debouncing
savePromises.push(player.persistState('shutdown', true).catch(err => {
console.error(chalk.red(`Failed to save state for guild ${guildId}:`), err);
}));
}
}
await Promise.all(savePromises);
// Give time for saves to complete
await new Promise(resolve => setTimeout(resolve, 1000));
process.exit(0);
};
// Register shutdown handlers
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
// Windows specific handlers
if (process.platform === 'win32') {
const readline = require('readline');
if (process.stdin.isTTY) {
readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('SIGINT', () => gracefulShutdown('SIGINT'));
}
}
// Login to Discord
await client.login(config.discord.token);
} catch (error) {
console.error(chalk.red('❌ Failed to start bot:'), error);
process.exit(1);
}
};
// Start the bot
init();
module.exports = client;
}, 5000);