const { SlashCommandBuilder } = require('@discordjs/builders');
const { joinVoiceChannel, createAudioPlayer, createAudioResource, AudioPlayerStatus, VoiceConnectionStatus } = require('@discordjs/voice');
const fs = require('fs');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play audio in your voice channel')
.addStringOption(option =>
option.setName('audio')
.setDescription('Enter audio URL or name')
.setRequired(true)),
async execute(interaction) {
const voiceChannel = interaction.member.voice.channel;
if (!voiceChannel) {
return await interaction.reply('You need to be in a voice channel to use this command!');
}
const audioUrl = interaction.options.getString('audio');
const stream = fs.createReadStream(audioUrl);
try {
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: interaction.guild.id,
adapterCreator: interaction.guild.voiceAdapterCreator,
selfDeaf: false,
selfMute: false,
debug: true
});
connection.on(VoiceConnectionStatus.Ready, () => {
console.log(`Connected to ${voiceChannel.name}`);
});
connection.on(VoiceConnectionStatus.Disconnected, (error) => {
console.log(`Disconnected from ${voiceChannel.name}: ${error.message}`);
});
connection.on('debug', console.log)
connection.on('error', console.error);
const player = createAudioPlayer({
debug: true
});
player.on('debug', console.log)
player.on('error', console.error);
player.on(AudioPlayerStatus.Playing, () => {
console.log('Audio playback started');
});
stream.on('error', console.error);
player.on(AudioPlayerStatus.Idle, () => {
console.log('Audio playback finished');
connection.destroy();
});
const resource = createAudioResource(stream);
player.play(resource);
connection.subscribe(player);
await interaction.reply(`Now playing: ${audioUrl}`);
} catch (error) {
console.error('Error in play command:', error);
await interaction.reply('Failed to play the audio.');
}
},
};