const { addToQueue, playNextInQueue } = require('../utils/queueManager'); const ytDlpExec = require('yt-dlp-exec'); const { v4: uuidv4 } = require('uuid'); const path = require('path'); module.exports = { name: 'play', description: 'Play a song from YouTube', async execute(message, args) { const searchQuery = args.join(' '); const voiceChannel = message.member.voice.channel; if (!voiceChannel) { return message.reply('You need to be in a voice channel to play music!'); } if (!searchQuery) { return message.reply('Please provide a YouTube link or a song name.'); } let url; if (isValidURL(searchQuery)) { url = searchQuery; } else { try { const searchResult = await ytDlpExec(`ytsearch:${searchQuery}`, { dumpSingleJson: true, noPlaylist: true, format: 'bestaudio/best', quiet: true, }); url = searchResult.webpage_url; } catch (error) { console.error('yt-dlp search error:', error); return message.reply('Could not find the song. Please try again.'); } } const tempFilePath = path.join(__dirname, '../utils/tmp', `${uuidv4()}.mp3`); try { await ytDlpExec(url, { cookies: path.join(__dirname, '../cookies.txt'), format: 'bestaudio', output: tempFilePath, quiet: true, }); addToQueue(message.guild.id, tempFilePath); playNextInQueue(message.guild.id, voiceChannel); } catch (error) { console.error('yt-dlp error:', error); message.reply('Failed to download video with yt-dlp.'); } }, }; function isValidURL(string) { try { new URL(string); return true; } catch (_) { return false; } }