Josh Haywood
Josh Haywood

Reputation: 81

Discord bot not joining voice channel to play audio

I have created a discord bot that is meant to join a channel and play youtube audio in that channel.

I dont recieve any errors but It doesnt join the voice channel of the user who sent a message containing '!play'. I have checked to see if it was a permissions issue and the bot has every permission aside from admin. I have also noticed that the error message doesnt trigger either. I would like any solutions to get the bot to correctly join a voice channel.

Heres the code

Ive removed the token just for this post

const Discord = require('discord.js');
const { Client, GatewayIntentBits } = Discord;

// Create a new client
const client = new Client({
  // Set the intents to include guilds and guild messages
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// Listen for messages that start with "!play"
client.on('messageCreate', message => {
  if (message.content.startsWith('!play')) {
    // Get the YouTube link from the command
    const youtubeLink = message.content.split(' ')[1];

    // If no link was provided, send an error message
    if (!youtubeLink) {
      message.channel.send('Error: No YouTube link was provided.');
      return;
    };

    // Play the music
    playMusic(message, youtubeLink);
  }
});

// Function to play music in a voice channel
function playMusic(message, youtubeLink) {
  // Join the voice channel
  const voiceChannel = message.member.voice.channel;
  voiceChannel.join().then(connection => {
    // Start playing music
    const stream = ytdl(youtubeLink, { filter: 'audioonly' });
    const dispatcher = connection.play(stream);
  });
};
// Log in to Discord using the bot's token
client.login('');

Upvotes: 0

Views: 3056

Answers (1)

MalwareMoon
MalwareMoon

Reputation: 898

First of all you need to either use SlashCommand or enable the Message Content Intent option on developer portal, to read messages (this btw. won't work if bot is on more than 100 servers, without a permission from someone in discord).

Another thing is, that playing audio from youtube is now impossible, because it's not compliant with API rules and with things like puppeteer you will soon get blocked by captcha.

Finally, for bot to join voice channel your play function should look something like this:

const audioPlayer = createAudioPlayer();

function playMusic(message, youtubeLink) {
    const channelOfFollowedMember = message.member.voice.channel
    if(!channelOfFollowedMember){ return }
    voiceConnection = joinVoiceChannel({
        channelId: channelOfFollowedMember.id,
        guildId: String(channelOfFollowedMember.guild.id),
        adapterCreator: channelOfFollowedMember.guild.voiceAdapterCreator,
        selfDeaf: false,
        selfMute: false
    })
    voiceConnection?.on(VoiceConnectionStatus.Ready, (oldState, newState) => {
        console.log('Connection is in the Ready state!');
        if(voiceConnection) {
            const stream = ytdl(youtubeLink, { filter: 'audioonly' });
            const subscription = voiceConnection.subscribe(audioPlayer);
            const dispatcher = subscription.play(stream);
        }
    });
};

But I don't know how it's going to work with ytdl utility you are using to play audio.

Upvotes: 0

Related Questions