Discord bot unable to play song using ytdl-core

Having problem with ytdl-core. My bot can’t play anything. In my console it said Playing: (song) but it doesn’t play anything at all. Here is my code

const { Client } = require('discord.js');
const { Logger } = require('logger');
const fs = require('fs');
const ytdl = require('ytdl-core');

const client = new Client();
const logger = new Logger();

const config = require('../config/settings.json');
const queueFilename = './data/queue.txt';

let owner = undefined;
let channel = undefined;
let listeners = 0;
let dispatcher = undefined;
let curSong = undefined;

const queue = fs.readFileSync(queueFilename).toString().split('\n');
const queueLength = queue.length;

function updatePresence(songTitle) {
  // Subject to change in the future.
  const presence = songTitle ? songTitle : '◼ Nothing to play';
  client.user.setPresence({
    activity: {
      name: presence,
      type: 'PLAYING'
    }
  }).catch(err => logger.error(err));
}

async function playMusic(conn, entry = 0) {
  const song = queue[entry];

  try {
    const stream = ytdl(song, { 
      quality: 'highestaudio',
      highWaterMark: 1<<25
     });

    stream.on('info', info => {
      curSong = info.title;
      logger.info(`Playing: ${curSong}`);
      updatePresence(`► ${curSong}`);

      if (listeners <= 1) {
        dispatcher.pause();
        updatePresence(`❙ ❙ ${curSong}`);
        logger.info(`Nobody is listening in ${channel.name}, music has been paused.`);
      }
    });
  
    dispatcher = await conn.play(stream);
  
    dispatcher.on('end', () => {
      if (entry == queueLength - 1) playMusic(conn);
      else playMusic(conn, entry + 1);
    });
  
    dispatcher.on('error', err => {
      logger.error(err);
      if (entry == queueLength - 1) playMusic(conn);
      else playMusic(conn, entry + 1);
    });
  } catch (err) {
    logger.error(err);
    if (entry == queueLength - 1) playMusic(conn);
    else playMusic(conn, entry + 1);
  }
}

client.on('ready', () => {
  logger.info('Connected to Discord! - Ready.');
  updatePresence();

  client.users.fetch(config.owner_id)
    .then( user => owner = user).catch( err => logger.error(err));

  client.channels.fetch(config.channel_id)
    .then( voiceChannel => {
      if (voiceChannel.joinable) {
        voiceChannel.join()
          .then( connection => {
            logger.info(`Joined ${voiceChannel.name}.`);
            channel = voiceChannel;
            listeners = connection.channel.members.reduce((total) => total + 1, 0);
            playMusic(connection);
          }).catch( err => {
            owner.send('Something went wrong when trying to connect to the voice channel!');
            logger.error(err);
          });
      } else {
        owner.send('I cannot join the voice channel that I was supposed to join!');
      }
    }).catch( err => {
      if (err == 'DiscordAPIError: Unknown Channel') owner.send('The voice channel I tried to join no longer exists!');
      else owner.send('Something went wrong when trying to look for the channel I was supposed to join!');
      logger.error(err);
    });
});

client.on('voiceStateUpdate', (oldState, newState) => {
  if (!oldState || !newState) return;

  const oldChannel = oldState.channel ? oldState.channel.id : null;
  const newChannel = newState.channel ? newState.channel.id : null;

  if (oldChannel != newChannel) {
    const bot = newChannel ? newState.channel.members.find( member => member.id == client.user.id) : null;
    if (bot) channel = bot.voice.channel;

    function playPauseDispatcher() {
      if (dispatcher) {
        if (listeners > 1) {
          dispatcher.resume();
          updatePresence(`► ${curSong}`);
          logger.info(`Music has resumed, ${listeners - 1} member(s) are currently listening.`);
        } else {
          dispatcher.pause();
          updatePresence(`❙ ❙ ${curSong}`);
          logger.info(`Nobody is listening in ${channel.name}, music has paused.`);
        }
      }
    }

    if (newChannel == channel.id) {
      listeners = channel.members.reduce((total) => total + 1, 0);
      logger.info(`${newState.member.displayName} has joined ${channel.name}.`);
      playPauseDispatcher();
    } else if (oldChannel == channel.id) {
      listeners = channel.members.reduce((total) => total + 1, 0);
      logger.info(`${oldState.member.displayName} has left ${channel.name}.`);
      playPauseDispatcher();
    }
  }
});

client.on('guildUnavailable', guild => {
  logger.warn(`Guild ${guild.name} is currently unavailable.`);
});

client.on('warn', info => {
  logger.warn(info);
});

client.on('resume', () => {
  logger.info('Client gateway resumed.');
});

client.on('invalidated', () => {
  logger.error('Client connection invalidated, terminating execution with code 1.');
  process.exit(1);
});

client.login(config.discord_token);

I used this code this it works fine. Here it is and you dont need to enter the youtube api key!
JS:

const Discord = require("discord.js");
const client = new Discord.Client();
const { prefix } = require("./config.json");
const ytdl = require("ytdl-core");
const music = require("discord.js-musicbot-plugin");

const queue = new Map();

client.once("ready", () => {
  console.log("Ready!");
});

client.once("reconnecting", () => {
  console.log("Reconnecting!");
});

client.once("disconnect", () => {
  console.log("Disconnect!");
});

client.on("message", async message => {
  if (message.author.bot) return;
  if (!message.content.startsWith(prefix)) return;

  const serverQueue = queue.get(message.guild.id);

  if (message.content.startsWith(`${prefix}play`)) {
    execute(message, serverQueue);
    return;
  } else if (message.content.startsWith(`${prefix}skip`)) {
    skip(message, serverQueue);
    return;
  } else if (message.content.startsWith(`${prefix}stop`)) {
    stop(message, serverQueue);
    return;
  }
});

async function execute(message, serverQueue) {
  const args = message.content.split(" ");

  const voiceChannel = message.member.voice.channel;
  if (!voiceChannel)
    return message.channel.send(
      "You need to be in a voice channel to play music!"
    );
  const permissions = voiceChannel.permissionsFor(message.client.user);
  if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
    return message.channel.send(
      "I need the permissions to join and speak in your voice channel!"
    );
  }

  const songInfo = await ytdl.getInfo(args[1]);
  const song = {
    title: songInfo.title,
    url: songInfo.video_url
  };

  if (!serverQueue) {
    const queueContruct = {
      textChannel: message.channel,
      voiceChannel: voiceChannel,
      connection: null,
      songs: [],
      volume: 5,
      playing: true
    };

    queue.set(message.guild.id, queueContruct);

    queueContruct.songs.push(song);

    try {
      var connection = await voiceChannel.join();
      queueContruct.connection = connection;
      play(message.guild, queueContruct.songs[0]);
    } catch (err) {
      console.log(err);
      queue.delete(message.guild.id);
      return message.channel.send(err);
    }
  } else {
    serverQueue.songs.push(song);
    return message.channel.send(`${song.title} has been added to the queue!`);
  }
}

function skip(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
  if (!serverQueue)
    return message.channel.send("There is no song that I could skip!");
  serverQueue.connection.dispatcher.end();
}

function stop(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
  serverQueue.songs = [];
  serverQueue.connection.dispatcher.end();
}

function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if (!song) {
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }

  const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on("finish", () => {
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on("error", error => console.error(error));
  dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  serverQueue.textChannel.send(`Start playing: **${song.title}**`);
}
client.login("TOKEN HERE")

also install these packages: discord.js-musicbot-plugin, ytdl-core

also make a config.json file to make this work with the prefix:

config.json:
{ "prefix": "YOUR PREFIX HERE" }

and then enjoy with your music bot like this for a example! Good luck and happy glitching! :slightly_smiling_face: :glitch:

This was 7 months ago, OP may have already solved their question and/or may not be active anymore.

4 Likes