My Discord Music bot executes an object instead of text - javascript

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)

Related

UnhandledPromiseRejectionWarning: TypeError: channel.createWebhook is not a function

This is my setuplogger.js file, and the bottom part is the code I have in my index.js. This code is supposed to create a webhook for the channel set as the logschannel, this webhook will send logs for every ban that happens in the guild. But the problem is that I keep getting the .createWebhook is not a function, I couldn't figure out how to fix this error so I just came here.
if (!message.member.hasPermission("ADMINISTRATOR")) {
return message.channel.send(`***Error:*** *You do not have* ***[ADMINISTRATOR]*** *permission.*`);
}
const logEnableDisable = args[0];
const logChannel = message.mentions.channels.first();
if (!logEnableDisable) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (!logChannel) {
return message.channel.send(`***Error:*** *${prefix}setuplogger <enable/disable> <channel>*`)
}
if (logEnableDisable === 'enable') {
db.set(`${message.guild.id}_logChannel`, logChannel.id)
message.channel.send(`*Succesfully enabled logs to* ***${logChannel}.***`)
}
if (logEnableDisable === 'disable') {
const findLogchannel = db.get(`${message.guild.id}_logChannel`);
if (!findLogchannel) {
message.channel.send(`***Error:*** *Log channel has not been setup yet, use \`${prefix}setuplogger enable <channel>\`.*`)
} else {
db.delete(`${message.guild.id}_logChannel`, true)
message.channel.send(`*Succesfully removed logs from* ***${logChannel}.***`)
}
}
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
client.on("guildBanAdd", async (guild, user) => {
const channel = db.get(`${guild.id}_logChannel`);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_BAN_ADD",
});
const banLog = fetchedLogs.entries.first();
if(!banLog) return console.log("It doesn't work.")
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`)
.setTimestamp()
.setColor(color);
channel.createWebhook('Logger', { avatar: 'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png' }).then(webhook => { webhook.send(embed) });
}
});
It seems you're saving the channel's ID in the database (logChannel.id) and later, you're trying to call the createWebhook method on a string, not the channel. If you call a non-existing method on a string you'll receive an error; "channel.createWebhook is not a function":
const channel = '86924931458913231434'
const webhook = channel.createWebhook('Logger')
To solve this, you need to fetch the channel first so you can use the createWebhook method:
client.on('guildBanAdd', async (guild, user) => {
const channelID = db.get(`${guild.id}_logChannel`);
if (!channelID) return console.log('No channel ID');
try {
const channel = await client.channels.fetch(channelID);
const fetchedLogs = await guild.fetchAuditLogs({
limit: 1,
type: 'MEMBER_BAN_ADD',
});
const banLog = fetchedLogs.entries.first();
if (!banLog) return console.log("It doesn't work.");
const { executor, target } = banLog;
if (target.id === user.id) {
const embed = new Discord.MessageEmbed()
.setTitle('Ban')
.setDescription(
`**User Banned**\fModerator: ${executor}\fUser: ${target.tag}`,
)
.setTimestamp()
.setColor(color);
const webhook = await channel.createWebhook('Logger', {
avatar:
'https://cdn2.iconfinder.com/data/icons/basic-ui-elements-circle/512/notepad_note_wrrte_pencil-512.png',
});
webhook.send(embed);
}
} catch (error) {
console.log(error);
}
});

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) {
// ...
// ...

Discordjs add space between prefix and command

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);

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}**`);
}

Categories

Resources