Reputation: 6583
When I run the following script ("node musicbot.js" in cmd) and "!play ytlink" within discord itself, the bot joins the voice channel and logs both the command and the link in the console. Yet, the music does not start playing. I have installed ffmpeg, ytdl-core, and discord.js.
Can someone help me out? I do not know which part is messing it up.
const Discord = require("discord.js");
const ytdl = require("ytdl-core");
const config = require("./config.json");
const bot = new Discord.Client();
let queue = [];
function play(connection, message) {
let audio = ytdl(queue[0], {filter: "audioonly"});
let dispatcher = connection.playStream(audio);
dispatcher.on("end", function() {
queue.shift();
if (queue[0]) play(connection, message);
else {
connection.disconnect();
message.channel.send("The queue has ended");
}
});
}
bot.on("message", function(message) {
if (message.channel.type === "dm") return;
if (!message.content.startsWith(config.prefix) || message.author.bot)
return;
let arguments = message.content.split(" ");
let command = arguments[0].toLowerCase();
arguments.shift();
console.log(command);
console.log(arguments);
if (command == "!play") {
if (!arguments[0]) {
message.channel.send("Please provide a YouTube link!");
message.delete();
return;
}
if (!message.member.voiceChannel) {
message.channel.send("Please join a Voice Channel first!");
message.delete();
return;
}
queue.push(arguments[0]);
message.member.voiceChannel.join()
.then(connection => {
play(connection, message);
});
}
});
bot.on("ready", function() {
console.log("Ready");
});
bot.login(config.token);
Upvotes: 0
Views: 17317
Reputation: 379
Ok, I have two solutions for you. This first one is a block of code I have used and I can say it works from experience.
It requires ffmpeg
, opusscript
and ytdl
:
function play(connection, message){
var server = servers[message.guild.id];
server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter:
"audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function() {
if(server.queue[0]) play(connection, message);
else connection.disconnect();
});
}
This second option which I would highly recommend is a node module that has many more advanced features that are hard to implement such as:
It is easy to install and get started, here is the node page with all the information about installation etc.
Upvotes: 1