Fix convert

This commit is contained in:
Wizzard 2024-08-17 20:05:43 -04:00
parent 281240f35d
commit f24da4ef20
1 changed files with 126 additions and 53 deletions

View File

@ -3,8 +3,7 @@ const { v4: uuidv4 } = require('uuid');
const path = require('path'); const path = require('path');
const { EmbedBuilder } = require('discord.js'); const { EmbedBuilder } = require('discord.js');
const fs = require('fs'); const fs = require('fs');
const { exec } = require('child_process'); const { exec, spawn } = require('child_process');
const { execSync } = require('child_process');
module.exports = { module.exports = {
name: 'play', name: 'play',
@ -22,35 +21,26 @@ module.exports = {
return message.reply('You need to be in a voice channel to play music!'); return message.reply('You need to be in a voice channel to play music!');
} }
let title, tempFilePath, videoUrl = null; let title, tempFilePath, videoUrl = null, thumbnailUrl = null;
let loadingMessage; let loadingMessage;
try { try {
if (message.attachments.size > 0) { if (message.attachments.size > 0) {
const attachment = message.attachments.first(); const attachment = message.attachments.first();
const extension = path.extname(attachment.name).toLowerCase(); const attachmentName = attachment.name.toLowerCase();
if (['.mp3', '.mp4', '.webm', '.mov'].includes(extension)) { if (attachmentName.endsWith('.mp3')) {
title = attachment.name; title = attachment.name;
const originalFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}_${title}`); tempFilePath = path.join(__dirname, '../utils/tmp', attachment.name);
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
console.log(`Attachment received: ${title}`); console.log(`Attachment received: ${title}`);
console.log(`Downloading attachment to: ${originalFilePath}`); console.log(`Downloading attachment to: ${tempFilePath}`);
const response = await fetch(attachment.url); const response = await fetch(attachment.url);
const buffer = await response.buffer(); const buffer = await response.buffer();
fs.writeFileSync(originalFilePath, buffer); fs.writeFileSync(tempFilePath, buffer);
console.log(`Downloaded and saved: ${originalFilePath}`); console.log(`Downloaded and saved: ${tempFilePath}`);
if (extension !== '.mp3') {
console.log(`Converting ${extension} to MP3...`);
execSync(`ffmpeg -i "${originalFilePath}" -q:a 0 -map a "${tempFilePath}"`);
fs.unlinkSync(originalFilePath);
} else {
tempFilePath = originalFilePath;
}
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor('#0099ff') .setColor('#0099ff')
@ -62,12 +52,57 @@ module.exports = {
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.'); console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL()); addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id); playNextInQueue(message.guild.id);
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);
const ffmpegProcess = spawn('ffmpeg', [
'-i', tempVideoPath,
'-f', 'mp3',
'-ab', '192000',
'-vn',
tempFilePath
]);
ffmpegProcess.on('close', () => {
console.log(`Converted and saved: ${tempFilePath}`);
fs.unlinkSync(tempVideoPath);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Added To Queue')
.setDescription(`**${title}**`)
.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);
});
ffmpegProcess.on('error', (err) => {
console.error('Error converting file:', err);
message.reply('Failed to convert the video file.');
});
return; return;
} else { } else {
console.error('Attachment is not a supported file type.'); console.error('Attachment is not a supported media file.');
return message.reply('Only MP3, MP4, and WEBM files are supported for uploads.'); return message.reply('Only MP3, MP4, WEBM, and MOV files are supported for uploads.');
} }
} }
@ -96,31 +131,38 @@ module.exports = {
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.'); console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL()); addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id); playNextInQueue(message.guild.id);
return; return;
} else if (searchQuery.includes("cdn.discordapp.com")) { } else if (searchQuery.includes("cdn.discordapp.com")) {
title = path.basename(searchQuery.split('?')[0]); title = path.basename(searchQuery.split('?')[0]);
const originalFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}_${title}`); const isVideo = searchQuery.endsWith('.mp4') || searchQuery.endsWith('.webm') || searchQuery.endsWith('.mov');
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`); const fileExtension = isVideo ? 'mp3' : 'original';
const convertedFileName = `${uuidv4()}.${fileExtension}`;
tempFilePath = path.join(__dirname, '../utils/tmp', convertedFileName);
console.log(`Discord CDN link received: ${searchQuery}`); console.log(`Discord media link received: ${searchQuery}`);
console.log(`Downloading file from Discord to: ${originalFilePath}`); console.log(`Downloading media from Discord to: ${tempFilePath}`);
const response = await fetch(searchQuery); const response = await fetch(searchQuery);
if (!response.ok) throw new Error('Failed to download file from Discord.'); if (!response.ok) throw new Error('Failed to download media file from Discord.');
const buffer = await response.buffer(); const buffer = await response.buffer();
fs.writeFileSync(originalFilePath, buffer);
console.log(`Downloaded and saved: ${originalFilePath}`); if (isVideo) {
const tempVideoPath = path.join(__dirname, '../utils/tmp', path.basename(searchQuery.split('?')[0]));
fs.writeFileSync(tempVideoPath, buffer);
if (!originalFilePath.endsWith('.mp3')) { const ffmpegProcess = spawn('ffmpeg', [
console.log(`Converting to MP3...`); '-i', tempVideoPath,
execSync(`ffmpeg -i "${originalFilePath}" -q:a 0 -map a "${tempFilePath}"`); '-f', 'mp3',
fs.unlinkSync(originalFilePath); '-ab', '192000',
} else { '-vn',
tempFilePath = originalFilePath; tempFilePath
} ]);
ffmpegProcess.on('close', () => {
console.log(`Converted and saved: ${tempFilePath}`);
fs.unlinkSync(tempVideoPath);
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor('#0099ff') .setColor('#0099ff')
@ -132,22 +174,50 @@ module.exports = {
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.'); console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL()); addToQueue(message.guild.id, tempFilePath, title, voiceChannel, null, message.author.username, message.author.displayAvatarURL(), null);
playNextInQueue(message.guild.id); playNextInQueue(message.guild.id);
});
ffmpegProcess.on('error', (err) => {
console.error('Error converting file:', err);
message.reply('Failed to convert the video file.');
});
} else {
fs.writeFileSync(tempFilePath, buffer);
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Added To Queue')
.setDescription(`**${title}**`)
.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);
}
return; return;
} else { } else {
console.log(`YouTube link received: ${searchQuery}`); console.log(`YouTube link received: ${searchQuery}`);
videoUrl = searchQuery; videoUrl = searchQuery;
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --print title ${searchQuery}`, async (error, stdout, stderr) => { exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --print-json --skip-download ${searchQuery}`, async (error, stdout, stderr) => {
if (error) { if (error) {
console.error(`Error getting title: ${error}`); console.error(`Error getting video info: ${error}`);
message.reply('Failed to retrieve video title.'); message.reply('Failed to retrieve video info.');
return; return;
} }
title = stdout.trim() || "Unknown Title"; const info = JSON.parse(stdout);
title = info.title || "Unknown Title";
thumbnailUrl = info.thumbnail || null;
console.log(`Retrieved title: ${title}`); console.log(`Retrieved title: ${title}`);
console.log(`Thumbnail URL: ${thumbnailUrl}`);
loadingMessage = await message.channel.send(`**Loading...** ${title}`); loadingMessage = await message.channel.send(`**Loading...** ${title}`);
@ -170,13 +240,14 @@ module.exports = {
.setColor('#0099ff') .setColor('#0099ff')
.setTitle('Added To Queue') .setTitle('Added To Queue')
.setDescription(`**${title}**`) .setDescription(`**${title}**`)
.setThumbnail(thumbnailUrl)
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() }) .setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp(); .setTimestamp();
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.'); console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, videoUrl, message.author.username, message.author.displayAvatarURL()); addToQueue(message.guild.id, tempFilePath, title, voiceChannel, videoUrl, message.author.username, message.author.displayAvatarURL(), thumbnailUrl);
playNextInQueue(message.guild.id); playNextInQueue(message.guild.id);
}); });
}); });
@ -195,6 +266,7 @@ module.exports = {
const info = JSON.parse(stdout); const info = JSON.parse(stdout);
const url = info.entries[0].webpage_url; const url = info.entries[0].webpage_url;
title = info.entries[0].title; title = info.entries[0].title;
thumbnailUrl = info.entries[0].thumbnail;
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`); tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
console.log(`Downloading file to: ${tempFilePath}`); console.log(`Downloading file to: ${tempFilePath}`);
@ -216,13 +288,14 @@ module.exports = {
.setColor('#0099ff') .setColor('#0099ff')
.setTitle('Added To Queue') .setTitle('Added To Queue')
.setDescription(`**${title}**`) .setDescription(`**${title}**`)
.setThumbnail(thumbnailUrl)
.setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() }) .setFooter({ text: `Requested by ${message.author.username}`, iconURL: message.author.displayAvatarURL() })
.setTimestamp(); .setTimestamp();
message.channel.send({ embeds: [embed] }); message.channel.send({ embeds: [embed] });
console.log('Adding to queue and attempting to play.'); console.log('Adding to queue and attempting to play.');
addToQueue(message.guild.id, tempFilePath, title, voiceChannel, url, message.author.username, message.author.displayAvatarURL()); addToQueue(message.guild.id, tempFilePath, title, voiceChannel, url, message.author.username, message.author.displayAvatarURL(), thumbnailUrl);
playNextInQueue(message.guild.id); playNextInQueue(message.guild.id);
}); });
}); });