I am just starting out and this is practically my first discord bot. I wanted to do something useful so I tried to create a music bot that via a youtube link plays the music for me, but even though this code gives no error, the bot enters the room and remains silent. I don’t know how to solve this.
const { SlashCommandBuilder } = require('discord.js');
const {AudioPlayerStatus, joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior } = require('@discordjs/voice');
const ytdl = require('ytdl-core-discord');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play music from a YouTube link')
.addStringOption(option =>
option.setName('url')
.setDescription('The YouTube URL of the video')
.setRequired(true)),
async execute(interaction, client) {
const channel = interaction.member.voice.channel;
if (!channel) return interaction.reply('Devi essere in un canale vocale per eseguire questo comando!');
// const url = interaction.options.getString('url');
const url= 'https://www.youtube.com/watch?v=BpwCJzPlz8k&ab_channel=SoloMusicLabel'
try {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const stream = ytdl(url, { filter: 'audioonly' });
const resource = createAudioResource(stream);
player.play(resource);
connection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => connection.destroy());
interaction.reply('Play the Music!');
} catch (error) {
console.error('Error:', error);
interaction.reply('There is a Error');
}
}
};