DZ-Musicbot/commands/play.js

364 lines
18 KiB
JavaScript
Raw Normal View History

2024-08-17 11:11:10 -04:00
const { addToQueue, playNextInQueue } = require('../utils/queueManager');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
2024-08-17 11:57:00 -04:00
const { EmbedBuilder } = require('discord.js');
2024-08-17 12:26:42 -04:00
const fs = require('fs');
2024-08-17 20:55:49 -04:00
const { exec, spawn, execSync } = require('child_process');
2024-08-17 11:11:10 -04:00
2024-08-18 04:49:20 -04:00
const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
function spawnFFmpegProcess(args, callback, retries = 0) {
const ffmpegProcess = spawn('ffmpeg', args);
ffmpegProcess.on('close', (code) => {
if (code === 0) {
callback(null);
} else if (retries < MAX_RETRIES) {
console.warn(`FFmpeg process failed, retrying (${retries + 1}/${MAX_RETRIES})...`);
setTimeout(() => {
spawnFFmpegProcess(args, callback, retries + 1);
}, RETRY_DELAY);
} else {
callback(new Error(`FFmpeg process failed after ${MAX_RETRIES} retries.`));
}
});
ffmpegProcess.on('error', (err) => {
if (retries < MAX_RETRIES) {
console.warn(`FFmpeg process error, retrying (${retries + 1}/${MAX_RETRIES})...`, err);
setTimeout(() => {
spawnFFmpegProcess(args, callback, retries + 1);
}, RETRY_DELAY);
} else {
callback(err);
}
});
}
2024-08-17 11:11:10 -04:00
module.exports = {
name: 'play',
2024-08-17 19:48:51 -04:00
description: 'Play a song from YouTube, a URL, or an uploaded media file',
2024-08-17 20:13:09 -04:00
aliases: ['p'],
2024-08-17 11:11:10 -04:00
async execute(message, args) {
2024-08-17 17:03:28 -04:00
const fetch = await import('node-fetch').then(module => module.default);
2024-08-17 11:11:10 -04:00
const searchQuery = args.join(' ');
const voiceChannel = message.member.voice.channel;
2024-08-17 17:05:26 -04:00
console.log(`Received command: play ${searchQuery}`);
console.log(`Voice channel: ${voiceChannel ? voiceChannel.name : 'None'}`);
2024-08-17 11:11:10 -04:00
if (!voiceChannel) {
2024-08-17 17:05:26 -04:00
console.error('User is not in a voice channel.');
2024-08-17 11:11:10 -04:00
return message.reply('You need to be in a voice channel to play music!');
}
2024-08-17 20:05:43 -04:00
let title, tempFilePath, videoUrl = null, thumbnailUrl = null;
2024-08-17 18:34:28 -04:00
let loadingMessage;
2024-08-17 11:11:10 -04:00
2024-08-17 11:57:00 -04:00
try {
2024-08-17 20:55:49 -04:00
const getDuration = (filePath) => {
try {
const output = execSync(`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${filePath}"`).toString().trim();
const durationSeconds = parseFloat(output);
const minutes = Math.floor(durationSeconds / 60);
const seconds = Math.floor(durationSeconds % 60);
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
} catch (error) {
console.error('Error getting track duration:', error);
return 'Unknown';
}
};
2024-08-17 12:26:42 -04:00
if (message.attachments.size > 0) {
const attachment = message.attachments.first();
2024-08-17 20:05:43 -04:00
const attachmentName = attachment.name.toLowerCase();
2024-08-17 12:26:42 -04:00
2024-08-17 20:05:43 -04:00
if (attachmentName.endsWith('.mp3')) {
2024-08-17 12:26:42 -04:00
title = attachment.name;
2024-08-17 20:05:43 -04:00
tempFilePath = path.join(__dirname, '../utils/tmp', attachment.name);
2024-08-17 16:37:26 -04:00
console.log(`Attachment received: ${title}`);
2024-08-17 20:05:43 -04:00
console.log(`Downloading attachment to: ${tempFilePath}`);
2024-08-17 12:26:42 -04:00
const response = await fetch(attachment.url);
const buffer = await response.buffer();
2024-08-17 20:05:43 -04:00
fs.writeFileSync(tempFilePath, buffer);
2024-08-17 19:48:51 -04:00
2024-08-17 20:05:43 -04:00
console.log(`Downloaded and saved: ${tempFilePath}`);
2024-08-17 16:37:26 -04:00
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 12:26:42 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
2024-08-17 19:15:09 -04:00
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 12:26:42 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
2024-08-17 17:05:26 -04:00
console.log('Adding to queue and attempting to play.');
2024-08-17 20:05:43 -04:00
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
2024-08-17 16:52:44 -04:00
playNextInQueue(message.guild.id);
2024-08-17 20:05:43 -04:00
return;
} else if (attachmentName.endsWith('.mp4') || attachmentName.endsWith('.webm') || attachmentName.endsWith('.mov')) {
title = attachment.name;
const convertedFileName = `${uuidv4()}.mp3`;
tempFilePath = path.join(__dirname, '../utils/tmp', convertedFileName);
console.log(`Attachment received: ${title}`);
console.log(`Converting and downloading attachment to: ${tempFilePath}`);
const response = await fetch(attachment.url);
const buffer = await response.buffer();
const tempVideoPath = path.join(__dirname, '../utils/tmp', attachment.name);
fs.writeFileSync(tempVideoPath, buffer);
2024-08-18 04:49:20 -04:00
spawnFFmpegProcess(['-i', tempVideoPath, '-f', 'mp3', '-ab', '192000', '-vn', tempFilePath], (err) => {
if (err) {
console.error('Error converting file:', err);
message.reply('Failed to convert the video file.');
return;
}
2024-08-17 20:05:43 -04:00
console.log(`Converted and saved: ${tempFilePath}`);
fs.unlinkSync(tempVideoPath);
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 20:05:43 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 20:05:43 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id);
});
2024-08-17 12:26:42 -04:00
return;
} else {
2024-08-17 20:05:43 -04:00
console.error('Attachment is not a supported media file.');
return message.reply('Only MP3, MP4, WEBM, and MOV files are supported for uploads.');
2024-08-17 12:26:42 -04:00
}
}
2024-08-17 11:57:00 -04:00
if (isValidURL(searchQuery)) {
2024-08-17 16:52:44 -04:00
if (searchQuery.endsWith('.mp3')) {
2024-08-17 16:37:26 -04:00
title = path.basename(searchQuery.split('?')[0]);
2024-08-17 16:52:44 -04:00
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}_${title}`);
2024-08-17 12:26:42 -04:00
2024-08-17 16:52:44 -04:00
console.log(`MP3 link received: ${searchQuery}`);
console.log(`Downloading MP3 to: ${tempFilePath}`);
2024-08-17 16:13:24 -04:00
2024-08-17 16:37:26 -04:00
const response = await fetch(searchQuery);
if (!response.ok) throw new Error('Failed to download MP3 file.');
const buffer = await response.buffer();
fs.writeFileSync(tempFilePath, buffer);
2024-08-17 16:13:24 -04:00
2024-08-17 16:37:26 -04:00
console.log(`Downloaded and saved: ${tempFilePath}`);
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 16:37:26 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
2024-08-17 19:15:09 -04:00
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 16:37:26 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
2024-08-17 17:05:26 -04:00
console.log('Adding to queue and attempting to play.');
2024-08-17 20:05:43 -04:00
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
2024-08-17 16:52:44 -04:00
playNextInQueue(message.guild.id);
2024-08-17 16:37:26 -04:00
return;
2024-08-17 16:52:44 -04:00
} else if (searchQuery.includes("cdn.discordapp.com")) {
2024-08-17 16:37:26 -04:00
title = path.basename(searchQuery.split('?')[0]);
2024-08-17 20:05:43 -04:00
const isVideo = searchQuery.endsWith('.mp4') || searchQuery.endsWith('.webm') || searchQuery.endsWith('.mov');
const fileExtension = isVideo ? 'mp3' : 'original';
const convertedFileName = `${uuidv4()}.${fileExtension}`;
tempFilePath = path.join(__dirname, '../utils/tmp', convertedFileName);
2024-08-17 16:37:26 -04:00
2024-08-17 20:05:43 -04:00
console.log(`Discord media link received: ${searchQuery}`);
console.log(`Downloading media from Discord to: ${tempFilePath}`);
2024-08-17 16:37:26 -04:00
const response = await fetch(searchQuery);
2024-08-17 20:05:43 -04:00
if (!response.ok) throw new Error('Failed to download media file from Discord.');
2024-08-17 16:37:26 -04:00
const buffer = await response.buffer();
2024-08-17 20:05:43 -04:00
if (isVideo) {
const tempVideoPath = path.join(__dirname, '../utils/tmp', path.basename(searchQuery.split('?')[0]));
fs.writeFileSync(tempVideoPath, buffer);
2024-08-18 04:49:20 -04:00
spawnFFmpegProcess(['-i', tempVideoPath, '-f', 'mp3', '-ab', '192000', '-vn', tempFilePath], (err) => {
if (err) {
console.error('Error converting file:', err);
message.reply('Failed to convert the video file.');
return;
}
2024-08-17 20:05:43 -04:00
console.log(`Converted and saved: ${tempFilePath}`);
fs.unlinkSync(tempVideoPath);
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 20:05:43 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 20:05:43 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id);
});
2024-08-17 19:48:51 -04:00
} else {
2024-08-17 20:05:43 -04:00
fs.writeFileSync(tempFilePath, buffer);
console.log(`Downloaded and saved: ${tempFilePath}`);
2024-08-17 16:37:26 -04:00
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 20:05:43 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 20:05:43 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
2024-08-17 16:37:26 -04:00
2024-08-17 20:05:43 -04:00
message.channel.send({ embeds: [embed] });
2024-08-17 16:37:26 -04:00
2024-08-17 20:05:43 -04:00
console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id);
}
2024-08-17 16:37:26 -04:00
return;
} else {
2024-08-17 17:05:26 -04:00
console.log(`YouTube link received: ${searchQuery}`);
2024-08-17 18:34:28 -04:00
videoUrl = searchQuery;
2024-08-17 20:05:43 -04:00
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --print-json --skip-download ${searchQuery}`, async (error, stdout, stderr) => {
2024-08-17 16:13:24 -04:00
if (error) {
2024-08-17 20:05:43 -04:00
console.error(`Error getting video info: ${error}`);
message.reply('Failed to retrieve video info.');
2024-08-17 16:13:24 -04:00
return;
}
2024-08-17 20:05:43 -04:00
const info = JSON.parse(stdout);
title = info.title || "Unknown Title";
thumbnailUrl = info.thumbnail || null;
2024-08-17 16:37:26 -04:00
console.log(`Retrieved title: ${title}`);
2024-08-17 20:05:43 -04:00
console.log(`Thumbnail URL: ${thumbnailUrl}`);
2024-08-17 16:13:24 -04:00
2024-08-17 18:47:13 -04:00
loadingMessage = await message.channel.send(`**Loading...** ${title}`);
2024-08-17 18:36:59 -04:00
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
2024-08-17 18:34:28 -04:00
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --format bestaudio --output "${tempFilePath}" ${searchQuery}`, async (error, stdout, stderr) => {
2024-08-17 16:37:26 -04:00
if (error) {
console.error(`Error downloading file: ${error}`);
message.reply('Failed to download audio file.');
return;
}
2024-08-17 16:13:24 -04:00
2024-08-17 17:05:26 -04:00
console.log(`Downloaded and saved: ${tempFilePath}`);
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 18:34:28 -04:00
if (loadingMessage) {
await loadingMessage.delete();
}
2024-08-17 16:37:26 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
2024-08-17 19:15:09 -04:00
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 20:05:43 -04:00
.setThumbnail(thumbnailUrl)
2024-08-17 16:37:26 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
2024-08-17 17:05:26 -04:00
console.log('Adding to queue and attempting to play.');
2024-08-17 20:05:43 -04:00
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, videoUrl, message.author.username, message.author.displayAvatarURL(), thumbnailUrl);
2024-08-17 16:52:44 -04:00
playNextInQueue(message.guild.id);
2024-08-17 16:37:26 -04:00
});
2024-08-17 16:13:24 -04:00
});
2024-08-17 16:37:26 -04:00
}
2024-08-17 11:57:00 -04:00
} else {
2024-08-17 18:34:28 -04:00
loadingMessage = await message.channel.send(`Searching for: **${searchQuery}**...`);
2024-08-17 17:05:26 -04:00
console.log(`Performing YouTube search: ${searchQuery}`);
2024-08-17 16:55:41 -04:00
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --dump-single-json "ytsearch:${searchQuery}"`, (error, stdout, stderr) => {
2024-08-17 16:13:24 -04:00
if (error) {
console.error(`Error searching: ${error}`);
message.reply('Failed to search for video.');
return;
}
2024-08-17 15:58:45 -04:00
2024-08-17 16:13:24 -04:00
const info = JSON.parse(stdout);
2024-08-17 16:37:26 -04:00
const url = info.entries[0].webpage_url;
2024-08-17 16:13:24 -04:00
title = info.entries[0].title;
2024-08-17 20:05:43 -04:00
thumbnailUrl = info.entries[0].thumbnail;
2024-08-17 12:26:42 -04:00
2024-08-17 16:13:24 -04:00
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
console.log(`Downloading file to: ${tempFilePath}`);
2024-08-17 18:34:28 -04:00
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --format bestaudio --output "${tempFilePath}" ${url}`, async (error, stdout, stderr) => {
2024-08-17 16:13:24 -04:00
if (error) {
console.error(`Error downloading file: ${error}`);
message.reply('Failed to download audio file.');
return;
}
2024-08-17 17:05:26 -04:00
console.log(`Downloaded and saved: ${tempFilePath}`);
2024-08-17 20:55:49 -04:00
const duration = getDuration(tempFilePath);
2024-08-17 18:34:28 -04:00
if (loadingMessage) {
await loadingMessage.delete();
}
2024-08-17 16:13:24 -04:00
const embed = new EmbedBuilder()
.setColor('#0099ff')
2024-08-17 19:15:09 -04:00
.setTitle('Added To Queue')
2024-08-17 20:55:49 -04:00
.setDescription(`**${title}** (${duration})`)
2024-08-17 20:05:43 -04:00
.setThumbnail(thumbnailUrl)
2024-08-17 16:13:24 -04:00
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp();
message.channel.send({ embeds: [embed] });
2024-08-17 17:05:26 -04:00
console.log('Adding to queue and attempting to play.');
2024-08-17 20:05:43 -04:00
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, url, message.author.username, message.author.displayAvatarURL(), thumbnailUrl);
2024-08-17 16:52:44 -04:00
playNextInQueue(message.guild.id);
2024-08-17 16:13:24 -04:00
});
});
2024-08-17 11:11:10 -04:00
}
} catch (error) {
2024-08-17 16:13:24 -04:00
console.error('Error:', error);
2024-08-17 18:34:28 -04:00
if (loadingMessage) await loadingMessage.delete();
2024-08-17 16:13:24 -04:00
message.reply('An error occurred while trying to play the music.');
2024-08-17 11:11:10 -04:00
}
},
};
function isValidURL(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
2024-08-17 19:30:48 -04:00
}