Discordjs add space between prefix and command - javascript

I created a music bot that streams music when someone taps !play in-text channel
Now I want to switch !play with please play but it response only with pleaseplay with no space between them and when I tried to change the code:
const prefix = 'please'; //before
const prefix = 'please '; //after
but it doesn't work at all with an error
log (node:5296) UnhandledPromiseRejectionWarning: Error: No video id found:
const {Client, Attachment, Message} = require('discord.js');
const {token} = require("./config.json");
const bot = new Client();
const prefix = 'please ';
const ytdl = require("ytdl-core");
const request = require('request');
const cheerio = require('cheerio');
const queue = new Map();
bot.on('ready', () => {
console.log('Client is online!');
bot.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;
} else {
message.channel.send("You need to enter a valid command!");
}
});
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(`streaming: **${song.title}**`);
}
bot.login(token);

The problem is that your arguments are split based on the space character.
const args = message.content.split(" ");
args[1] is being referenced to get the text after the command name, but with the space in the command, args[1] will always be "play" (or whichever command they are using)
A quick fix would be to change args[1] to args[2]
const songInfo = await ytdl.getInfo(args[2]);

Edit: Full upgraded code... also clear like a crystal.
const {Client, Attachment, Message} = require('discord.js');
const {token} = require("./config.json");
const bot = new Client();
const prefix = 'please';
const ytdl = require("ytdl-core");
const request = require('request');
const cheerio = require('cheerio');
const queue = new Map();
bot.on('ready', () => {
console.log('Client is online!');
}
bot.on("message", async message => {
let content = message.content.split(' ');
if (message.author.bot) return;
if (content.shift() !== prefix) return;
const serverQueue = queue.get(message.guild.id);
switch (content.shift()) {
case 'play': exec(content, message, serverQueue); break;
case 'skip': skip(content, message, serverQueue); break;
case 'stop': stop(content, message, serverQueue); break;
default: message.channel.send("You need to enter a valid command!");
}
});
async function exec (ctx, msg, que) {
const voiceChannel = msg.member.voice.channel;
if (!voiceChannel)
return msg.channel.send(
"You need to be in a voice channel to play music!"
);
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK"))
return msg.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
const songInfo = await ytdl.getInfo(ctx.join(' '));
const song = {
title: songInfo.title,
url: songInfo.video_url
};
if (!que) {
const queueContruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(msg.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(msg.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(msg.guild.id);
return msg.channel.send(err);
}
} else {
que.songs.push(song);
return msg.channel.send(`${song.title} has been added to the queue!`);
}
}
await function play(gui, sng) {
const serverQueue = queue.get(gui.id);
if (!sng) {
serverQueue.voiceChannel.leave();
queue.delete(gui.id);
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(sng.url))
.on("finish", () => {
serverQueue.songs.shift();
play(gui, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`streaming: **${sng.title}**`);
}
async function stop(ctx, msg, que) {
if (!msg.member.voice.channel)
return msg.channel.send(
"You have to be in a voice channel to stop the music!"
);
que.songs = [];
que.connection.dispatcher.end();
}
async function skip(ctx, msg, que) {
if (!msg.member.voice.channel)
return msg.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!que)
return msg.channel.send("There is no song that I could skip!");
que.connection.dispatcher.end();
}
bot.login(token);

Related

discord.js / ytdl-core play command

this is my second question today. I'm using discord.js v13. Earlier I looked into finding out how to make audio play from the bot, and now I am attempting to make a queue work for my discord.js bot. My problem is getting the queue defined from index.js correctly. I will provide the error log along with my code.
error logs: https://i.imgur.com/ScDcJHK.jpg
index.js
const fs = require('fs');
const { Collection, Client, Intents } = require('discord.js');
const Levels = require('discord-xp');
require('dotenv').config();
const client = new Client({
presence: {
status: 'idle',
afk: false,
activities: [{
name: 'The Official Xontavs',
type: 'WATCHING'
}],
},
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS]
});
client.queue = new Map();
const mongoose = require('./database/mongoose.js');
Levels.setURL(`mongodb+srv://discordbot:${process.env.PASS}#bot.z8ki0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
['aliases', 'commands'].forEach(x => client[x] = new Collection());
['command', 'event'].forEach(x => require(`./handlers/${x}`)(client));
mongoose.init();
client.login(process.env.CLIENT_TOKEN); // SECRET TOKEN
play.js
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { getVoiceConnection, joinVoiceChannel, AudioPlayerStatus, createAudioResource, getNextResource, createAudioPlayer, NoSubscriberBehavior } = require('#discordjs/voice');
const { createReadStream} = require('fs');
module.exports = {
name: "play",
category: "music",
description: "plays a song",
usage: "<id | mention>",
run: async (client, message, args, queue) => {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You are not in a voice channel.');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT', 'SPEAK')) return message.channel.send('You do not have the correct permissions');
if(!args.length) return message.channel.send('You need to send the second argument');
const server_queue = queue.get(message.guild.id);
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voiceChannel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('Error connecting');
throw err;
}
} else {
server_queue.songs.push(song);
return message.channel.send(`**${song.title}** added to queue.`);
}
//audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
//audioPlayer.on(AudioPlayerStatus.Idle, () => {
//audioPlayer.stop();
//connection.destroy();
//message.channel.send('Leaving VC');
//});
}
}
const video_player = async (guild, song, queue) => {
const song_queue = queue.get(guild.id);
if(!song) {
connection.destroy();
queue.delete(guild.id);
return;
}
const audioPlayer = createAudioPlayer();
song_queue.connection.subscribe(audioPlayer);
const stream = ytdl(song.url, { filter: 'audioonly' });
audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
audioPlayer.on(AudioPlayerStatus.Idle, () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
song_queue.text_channel.send(`Now playing **${song.title}**`)
}
messageCreate.js (if needed)
const del = require('../../functions.js');
const Levels = require('discord-xp');
require('dotenv').config();
const prefix = process.env.PREFIX;
const queue = new Map();
module.exports = async (Discord, client, message) => {
if (message.author.bot || !message.guild) return;
const randomXP = Math.floor(Math.random() * 14) + 1; //1-15
const hasLeveledUP = await Levels.appendXp(message.author.id, message.guild.id, randomXP);
if (hasLeveledUP) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(`${message.member} is now level ${user.level}.`);
}
//const args = message.content.startsWith(prefix) ? message.content.slice(prefix.length).trim().split(/ +/g) : message.content.replace(/[^\s]*/, '').trim().split(/ +/g);
const args = message.content.slice(prefix.length).trim().split(" ");
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd) || client.commands.find(c => c.aliases?.includes(cmd));
if (command) {
command.run(client, message, args, queue);
}
}
Any help is appreciated because I'm really not smart and I'm still trying to learn how all this stuff works, especially with discord.js v13
In
video_player(message.guild, queue_constructor.songs[0]);
You only put two parameters and as you said in the comments, you only had to change it to this to fix your problem
video_player(message.guild, queue_constructor.songs[0], queue, audioPlayer)

undefined song when I run the play command

I'm trying to build a music discord bot with yt-search but it gives me undefined whenever I play the song and it joins the voice channel without playing the song. I'm trying to use yt-search to find the video I want or only the URL then pass it to ytdl to run it with the URL given from yt-search but I think I'm wrong in some points. I don't know where, could you please fix my code ?
Image to show the problem:
My code:
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");
const yts = require("yt-search");
const client = new Discord.Client();
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;
} else {
message.channel.send("You need to enter a valid command!");
}
});
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 r = await yts(args[1,2]);
const video = r.videos.slice( 0, 1 );
console.log(video);
const songInfo = await ytdl.getInfo(video.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.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!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could stop!");
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);
There are two errors. I'm not sure what you think args[1,2] is but it's the same as args[2] which is the third item of the args array. By reading your code, I think you want to use a string here, the search term. By removing the first item (the command) from the args array and joining the rest of them, you will receive a string you can use as keywords. Check out the example below:
const message = { content: '!play some music I want'}
const args = message.content.split(' ')
console.log({ args })
// => ["!play", "some", "music", "I", "want"]
console.log({ 'args[1, 2]': args[1, 2] })
// => "music"
console.log({ 'search': args.slice(1).join(' ') })
// => "some music I want"
The other error is that await yts(query) returns an array of results and when you define the video variable you use r.videos.slice(0, 1). The .slice() method returns a new array with the first item of r.videos.
As the video variable is an array, video.url is undefined. You could fix it by using the first item instead as it will have a url property. You should also check if there are any search results.
Check out the updated code below:
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 query = args.slice(1).join(' ');
const results = await yts(query);
if (!results.videos.length)
return message.channel.send(`No results for \`${query}\``);
const firstVideo = results.videos[0];
const songInfo = await ytdl.getInfo(firstVideo.url);
const song = {
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
};
console.log(song);
if (!serverQueue) {
// ...
// ...

Erro:SyntaxError: Unexpected token ':' in MUSIC BOT

I am creating a music bot, and one command of he is prefix + "play", and in the chat I put "!play + [a youtube link]", but this error appeared on the console. The code of "play" is:
===================================================================
const Discord = require('discord.js');
const ytdl = require("ytdl-core");
module.exports.run = async (bot, message, args) => {
name: "play",
description: "Play a song in your channel!",
async execute(message) {
try {
const args = message.content.split(" ");
const queue = message.client.queue;
const serverQueue = message.client.queue.get(message.guild.id);
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.videoDetails.title,
url: songInfo.videoDetails.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;
this.play(message, 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!`
);
}
} catch (error) {
console.log(error);
message.channel.send(error.message);
}
},
play(message, song) {
const queue = message.client.queue;
const guild = message.guild;
const serverQueue = queue.get(message.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();
this.play(message, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Starting play: **${song.title}**`);
}
};
===================================================================
The error is: "Erro:SyntaxError: Unexpected token ':'".
Someone can help me plese?
If its supposed to return an object, put parentheses around it, like this:
// From
module.exports.run = async (bot, message, args) => {
...
};
// To
module.exports.run = async (bot, message, args) => ({
...
});
``

(node:656) UnhandledPromiseRejectionWarning: ReferenceError: prefix is not defined error

I'm currently trying to get my Discord bot to play music in the Discord, I have all this code typed up and it's coming up with this error:
(node:656) UnhandledPromiseRejectionWarning: ReferenceError: prefix is not defined
I've tried fixing it but can't. I'm using JavaScript and the program I'm using is Visual Studio Code.
Here's the code:
const {Client, MessageEmbed} = require('discord.js');
const bot = new Client();
const queue = new Map();
const ytdl = require("ytdl-core");
const token = 'HIDDEN FOR PRIVACY';
const PREFIX = '!';
var version = "1.0.0"
bot.on('ready', () =>{
console.log('Krum has started');
bot.user.setActivity(`!help | Krums Bot`);
})
//ATTEMPT AT PLAYING MUSIC--LOOKING FOR FIX--NOT WORKING CURRENTLY
bot.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;
} else {
message.channel.send("You need to enter a valid command!");
}
});
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}**`);
}

My Discord Music bot executes an object instead of text

I tried to make a music bot, but it wont execute the song. Below is the code for the section which should gather the information and execute the song.
Can someone help me get this right? I'm not sure how to fix this issue as I don't know where the error starts.
I pasted also the handleVideo and the play class in the end so you know what happens there.
if (command === 'play') {
const voiceChannel = message.member.voiceChannel;
if (!voiceChannel) return message.channel.send('I\'m sorry but you need to be in a voice channel to play music!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) {
return message.channel.send('I cannot connect to your voice channel, make sure I have the proper permissions!');
}
if (!permissions.has('SPEAK')) {
return message.channel.send('I cannot speak in this voice channel, make sure I have the proper permissions!');
}
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
}
return message.channel.send(`✅ Playlist: **${playlist.title}** has been added to the queue!`);
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 10);
let index = 0;
message.channel.send(`
__**Song selection:**__
${videos.map(video2 => `**${++index} -** ${video2.title}`).join('\n')}
Please provide a value to select one of the search results ranging from 1-10.
`);
// eslint-disable-next-line max-depth
try {
var response = await message.channel.awaitMessages(msg2 => msg2.content > 0 && msg2.content < 11, {
maxMatches: 1,
time: 10000,
errors: ['time']
});
} catch (err) {
console.error(err);
return message.channel.send('No or invalid value entered, cancelling video selection.');
}
const videoIndex = parseInt(response.first().content);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return message.channel.send('🆘 I could not obtain any search results.');
}
}
return handleVideo(video, message, voiceChannel);
}
}
async function handleVideo(video, message, voiceChannel, playlist = false) {
const serverQueue = queue.get(message.guild.id);
console.log(video);
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`
};
if (!serverQueue) {
const queueConstruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(message.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`I could not join the voice channel: ${error}`);
queue.delete(message.guild.id);
return message.channel.send(`I could not join the voice channel: ${error}`);
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
if (playlist) return undefined;
else return message.channel.send(`✅ **${song.title}** has been added to the queue!`);
}
return undefined;
});
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
console.log(serverQueue.songs);
const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
.on('end', reason => {
if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
else console.log(reason);
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}**`);
}
The error message:
TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object
at validateString (internal/validators.js:125:11)
at normalizeSpawnArguments (child_process.js:411:3)
at Object.spawn (child_process.js:545:16)
at new FfmpegProcess (C:\Users\user\Desktop\ExoBot-master\node_modules\prism-media\src\transcoders\ffmpeg\FfmpegProcess.js:14:33)
at FfmpegTranscoder.transcode (C:\Users\user\Desktop\ExoBot-master\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:34:18)
at MediaTranscoder.transcode (C:\Users\user\Desktop\ExoBot-master\node_modules\prism-media\src\transcoders\MediaTranscoder.js:27:31)
at Prism.transcode (C:\Users\user\Desktop\ExoBot-master\node_modules\prism-media\src\Prism.js:13:28)
at AudioPlayer.playUnknownStream (C:\Users\user\Desktop\ExoBot-master\node_modules\discord.js\src\client\voice\player\AudioPlayer.js:97:35)
at VoiceConnection.playStream (C:\Users\user\Desktop\ExoBot-master\node_modules\discord.js\src\client\voice\VoiceConnection.js:478:24)
at play (C:\Users\user\Desktop\ExoBot-master\bot.js:322:44)

Categories

Resources