This is the code I have so far there are no errors while it runs and the bot joins the channel and even displays the song names in the logs but no audio plays. I’ve tried upgrading node, npm, discord.js and all other packages to the latest version. I fixed some issues regarding syntax since most examples use discord.js version < 12 but I still have had no luck. Any assistance would be much appreciated.
const { Client, GatewayIntentBits, Partials} = require('discord.js');
const ytdl = require('ytdl-core');
const { createAudioPlayer, createAudioResource , StreamType, demuxProbe, joinVoiceChannel, NoSubscriberBehavior, AudioPlayerStatus, VoiceConnectionStatus, getVoiceConnection } = require('@discordjs/voice')
const play = require('play-dl')
const client = new Client({
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],partials: ['CHANNEL', 'MESSAGE']
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (message) => {
console.log('message: ',message.content);
if (message.author.bot) return;
if (message.content.toLocaleLowerCase() === '/leave') { //Here's how to leave from voice channel
const connection = getVoiceConnection(message.guild.id)
if(!connection) return message.channel.send("I'm not in a voice channel!")
connection.destroy();
console.log('Disconnected from voice!');
}
if (message.content.startsWith('/play')) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) {
return message.reply('Please join a voice channel to use this command.');
}
const url = message.content.slice(6).trim();
if (!ytdl.validateURL(url)) {
return message.reply('Invalid YouTube URL.');
}
console.log("Establishing connection");
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
console.log("Getting play urls from command");
let args = message.content.split('play ')[1].split(' ')[0]
console.log(args);
console.log("After waiting for stream");
let yt_info = await play.video_info(args)
console.log(yt_info.video_details.title)
let stream = await play.stream_from_info(yt_info)
// const stream = ytdl(url, { filter: 'audioonly' })
console.log("Creating Resource");
let resource = createAudioResource(stream.stream, {
inputType: stream.type
});
console.log("Creating Audio Player");
let player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play
}
});
console.log("Attempting to play");
player.play(resource);
connection.subscribe(player);
}
});
client.login('Discord Token');