DZ-Musicbot/commands/play.js

210 lines
9.7 KiB
JavaScript

const { addToQueue, playNextInQueue } = require('../utils/queueManager');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const { EmbedBuilder } = require('discord.js');
const fs = require('fs');
const { exec } = require('child_process');
module.exports = {
name: 'play',
description: 'Play a song from YouTube, a URL, or an uploaded MP3 file',
async execute(message, args) {
const fetch = await import('node-fetch').then(module => module.default);
const searchQuery = args.join(' ');
const voiceChannel = message.member.voice.channel;
console.log(`Received command: play ${searchQuery}`);
console.log(`Voice channel: ${voiceChannel ? voiceChannel.name : 'None'}`);
if (!voiceChannel) {
console.error('User is not in a voice channel.');
return message.reply('You need to be in a voice channel to play music!');
}
let title, tempFilePath;
try {
if (message.attachments.size > 0) {
const attachment = message.attachments.first();
if (attachment.name.endsWith('.mp3')) {
title = attachment.name;
tempFilePath = path.join(__dirname, '../utils/tmp', attachment.name);
console.log(`Attachment received: ${title}`);
console.log(`Downloading attachment to: ${tempFilePath}`);
const response = await fetch(attachment.url);
const buffer = await response.buffer();
fs.writeFileSync(tempFilePath, buffer);
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Now Playing')
.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);
playNextInQueue(message.guild.id);
return;
} else {
console.error('Attachment is not an MP3 file.');
return message.reply('Only MP3 files are supported for uploads.');
}
}
if (isValidURL(searchQuery)) {
if (searchQuery.endsWith('.mp3')) {
title = path.basename(searchQuery.split('?')[0]);
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}_${title}`);
console.log(`MP3 link received: ${searchQuery}`);
console.log(`Downloading MP3 to: ${tempFilePath}`);
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);
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Now Playing')
.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);
playNextInQueue(message.guild.id);
return;
} else if (searchQuery.includes("cdn.discordapp.com")) {
title = path.basename(searchQuery.split('?')[0]);
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}_${title}`);
console.log(`Discord MP3 link received: ${searchQuery}`);
console.log(`Downloading MP3 from Discord to: ${tempFilePath}`);
const response = await fetch(searchQuery);
if (!response.ok) throw new Error('Failed to download MP3 file from Discord.');
const buffer = await response.buffer();
fs.writeFileSync(tempFilePath, buffer);
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Now Playing')
.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);
playNextInQueue(message.guild.id);
return;
} else {
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
console.log(`YouTube link received: ${searchQuery}`);
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --print title ${searchQuery}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error getting title: ${error}`);
message.reply('Failed to retrieve video title.');
return;
}
title = stdout.trim() || "Unknown Title";
console.log(`Retrieved title: ${title}`);
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --format bestaudio --output "${tempFilePath}" ${searchQuery}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error downloading file: ${error}`);
message.reply('Failed to download audio file.');
return;
}
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Now Playing')
.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);
playNextInQueue(message.guild.id);
});
});
}
} else {
console.log(`Performing YouTube search: ${searchQuery}`);
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --dump-single-json "ytsearch:${searchQuery}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error searching: ${error}`);
message.reply('Failed to search for video.');
return;
}
const info = JSON.parse(stdout);
const url = info.entries[0].webpage_url;
title = info.entries[0].title;
tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`);
console.log(`Downloading file to: ${tempFilePath}`);
exec(`yt-dlp --cookies ${path.join(__dirname, '../cookies.txt')} --format bestaudio --output "${tempFilePath}" ${url}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error downloading file: ${error}`);
message.reply('Failed to download audio file.');
return;
}
console.log(`Downloaded and saved: ${tempFilePath}`);
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Now Playing')
.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);
playNextInQueue(message.guild.id);
});
});
}
} catch (error) {
console.error('Error:', error);
message.reply('An error occurred while trying to play the music.');
}
},
};
function isValidURL(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}