I am trying to make discord bot that will play some music but I can't manage to make search command correctly ( Now I need to type command .f press enter and then put that what I want to search and I want it to just .f [what i want to search]) but doesn't know how to. I tried many guides but still nothing, also I would like to have that after searching and choosin what to I meant to play bot automatically join and play it (I made it buut in weird way and I know there is easier way but I am dumb for it.
TL;DR: Search command that will search and play with ".f [what to search]".
Whole code if it wil help:
const { Client } = require("discord.js");
const config = require('./config.json')
const Discord = require("discord.js");
const ytdl = require('ytdl-core');
const search = require("youtube-search")
const opts = {
maxResults: 25,
key: config.YOUTUBE_API,
type: 'video'
}
const queue = new Map();
const client = new Client({
disableEveryone: true
});
client.on("ready", () => {
console.log(`ŻYJE I JAM JEST ${client.user.username} `);
});
client.on("message", async message => {
console.log(`${message.author.username} mówi: ${message.content}`)
});
client.on("message", async message => {
if (!message.content.startsWith('.')) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`.p`, '.play', '.pla', '.pl')) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`.s`, '.skip', '.sk', '.ski')) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`.l`, '.leave', '.le', '.lea', '.leav')) {
stop(message, serverQueue);
return;
};
if (message.content.toLowerCase() === '.f') {
let embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setDescription("Czego szukasz? Opowiedz mi dokładniej.")
.setTitle("Wyszukiwarka")
.setThumbnail('https://i.imgur.com/vs6ulWc.gif')
let embedMsg = await message.channel.send(embed);
let filter = m => m.author.id === message.author.id;
let query = await message.channel.awaitMessages(filter, { max: 1});
let results = await search(query.first().content, opts).catch(err => console.log(err))
if(results) {
let youtubeResults = results.results;
let i =0;
let titles = youtubeResults.map(result => {
i++;
return i + ") " + result.title;
});
console.log(titles);
message.channel.send({
embed : {
title: "Wybieraj mordo",
description: titles.join("\n")
}
}).catch(err => console.log(err));
filter = m => (m.author.id === message.author.id) && m.content >= 1 && m.content <= youtubeResults.length;
let collected = await message.channel.awaitMessages(filter, { max: 1 });
let selected = youtubeResults[collected.first().content - 1];
embed = new Discord.MessageEmbed()
.setColor("#00FE0C")
.setTitle(`${selected.title}`)
.setURL(`${selected.link}`)
.setDescription(`${selected.description}`)
.setThumbnail(`${selected.thumbnails.default.url}`);
message.channel.send(embed)
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
await message.channel.send(`.p ${selected.link}`).then(d_msg => { d_msg.delete({ timeout: 1500 })})
}
};
};
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"No wbij Mordunio na kanał najpierw!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"Dawaj klucze do kantorka to wbije!"
);
}
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}** został do kolejeczki dodany Byku!`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Nie zatrzymasz mnie! Ciebie tu nie ma!"
);
if (!serverQueue)
return message.channel.send("A co miałabym pominąć");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Musisz tu byyyyć byyyyyku!!"
);
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song, message) {
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(`Gram: **${song.title}**`);
};
client.login(config.TOKEN);
Related
I was coding a new music command for my discord bot and when I use -play {url}, I get an error. The error is: voice_channel.join is not a function.
I checked some websites including Stack Overflow but I did not find any useful solution. I want to update this code from discord.js v12 to discord.js v13. The code:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 0,
description: 'Advanced music bot',
async execute(message,args, cmd, client, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
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 video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.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: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}
I am using discord.js v13 and node.js 16.
vs code
Voice support is moved to a new library in v13. You will need to install it by running npm i #discordjs/voice in your console.
Then, you can import the joinVoiceChannel method from it on the top of your file:
const { joinVoiceChannel } = require('#discordjs/voice');
Once it's imported, you can replace voice_channel.join() with the following to create a connection:
const connection = joinVoiceChannel({
channelId: voice_channel.id,
guildId: voice_channel.guild.id,
adapterCreator: voice_channel.guild.voiceAdapterCreator,
});
I'm trying to build a Discord's bot using discord.js with NodeJS but i'm facing a problem. When I run the code, the dicord.js don't execute the client.on("message"), he just skips this part and go to the end of the code, like you can see in the following image:
index.js
const { Client, Intents } = require('discord.js');
const { prefix, token } = require("./config.json");
require('dotenv').config();
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const queue = new Map();
client.once("ready", c => {
console.log(`🚀 [${c.user.tag}] Running...`);
client.user.setActivity(`${prefix}play`, { type: "PLAYING" })
});
client.once("reconnecting", c => {
console.log(`🔃 [${c.user.tag}] Reconnecting...`);
});
client.once("disconnect", c => {
console.log(`[${c.user.tag}] Disconnect!`);
});
client.on("message", async message => {
console.log("I'm here!")
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.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);
May you help to solve this problem?
While it is true that the message event is deprecated, you should still be getting process warnings when using it.
The main issue is that you haven't added intents for guild messages, your bot can't see messages. Add Intents.FLAGS.GUILD_MESSAGES to your client intents.
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
For what I saw on their documentation and based on the comment from #esqew, they deprecated the message event.
You should try client.on("messageCreate")
I'm trying to build a Discord's bot using discord.js with NodeJS but i'm facing a problem. When I run the code, the dicord.js don't execute the client.on("message"), he just skips this part and go to the end of the code, like you can see in the following image:
index.js
const { Client, Intents } = require('discord.js');
const { prefix, token } = require("./config.json");
require('dotenv').config();
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const queue = new Map();
client.once("ready", c => {
console.log(`🚀 [${c.user.tag}] Running...`);
client.user.setActivity(`${prefix}play`, { type: "PLAYING" })
});
client.once("reconnecting", c => {
console.log(`🔃 [${c.user.tag}] Reconnecting...`);
});
client.once("disconnect", c => {
console.log(`[${c.user.tag}] Disconnect!`);
});
client.on("message", async message => {
console.log("I'm here!")
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.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);
May you help to solve this problem?
While it is true that the message event is deprecated, you should still be getting process warnings when using it.
The main issue is that you haven't added intents for guild messages, your bot can't see messages. Add Intents.FLAGS.GUILD_MESSAGES to your client intents.
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
For what I saw on their documentation and based on the comment from #esqew, they deprecated the message event.
You should try client.on("messageCreate")
Hello I am working on my music command. I already have a !play, !skip and !stop command but I want to make it so I can have a pause and resume command. Any Idea how to do that?
Any form of help will be appreciated
Also I am very new to coding so please help me in baby steps
here is my code
const ytdl = require("ytdl-core");
const yts = require("yt-search");
bot.on("message", async message => {
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
if (message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`${PREFIX}plays`)) {
execute(message, serverQueue).catch((_err) =>{
message.channel.send('I was not able to fulfill your request')
})
return;
} else if (message.content.startsWith(`${PREFIX}skips`)) {
skip(message, serverQueue);
return;
} else if (message.content.startsWith(`${PREFIX}stops`)) {
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!"
);
let song;
if (ytdl.validateURL(args[1])) {
const songInfo = await ytdl.getInfo(args[1]);
song = {
title: songInfo.title,
url: songInfo.video_url
};
} else {
const { videos } = await yts(args.slice(1).join(" "));
if (!videos.length) return message.channel.send("No songs were found!");
song = {
title: videos[0].title,
url: videos[0].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();
message.channel.send('Succesfully stopped all songs')
}
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(`Started playing: **${song.title}**`);
}
bot.on('message', message => {
if (!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).split(/ +/);
const command = args.shift().toLowerCase;
});
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.bot.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
let song;
if (ytdl.validateURL(args[1])) {
const songInfo = await ytdl.getInfo(args[1]);
song = {
title: songInfo.title,
url: songInfo.video_url
};
} else {
const { videos } = await yts(args.slice(1).join(" "));
if (!videos.length) return message.channel.send("No songs were found!");
song = {
title: videos[0].title,
url: videos[0].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}**`);
}
And Thank you in advance
You're going to have to make a Dispatcher like so:
let dispatcher = connection.play(song)
and the in the pause function, do
dispatcher.pause()
and for resume
dispatcher.resume()
Hello so i've followed this tutorial and added this code to my current bot to make it have a music bot function. Im wondering how to make the following code work with the youtube search function, for example right now I have to do !play URL but I would also like to be able to do !play name of song then the bot will search and play the most matched song.
I am new to javascript but I know I shouldn't be looking for handouts, but some help would be appreciated.
const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");
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 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);
You can use yt-search:
const yts = require("yt-search");
// Searches YouTube with the message content (this joins the arguments
// together because songs can have spaces)
const {videos} = await yts(args.slice(1).join(" "));
if (!videos.length) return message.channel.send("No songs were found!");
const song = {
title: videos[0].title,
url: videos[0].url
};
// rest of code...
If you want to support both URLs and searching, you can test if the first argument is a valid URL using ytdl.validateURL:
let song;
if (ytdl.validateURL(args[1])) {
const songInfo = await ytdl.getInfo(args[1]);
song = {
title: songInfo.title,
url: songInfo.video_url
};
} else {
const {videos} = await yts(args.slice(1).join(" "));
if (!videos.length) return message.channel.send("No songs were found!");
song = {
title: videos[0].title,
url: videos[0].url
};
}
// rest of code...
Both of these examples replace
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.title,
url: songInfo.video_url
};
except for const yts = require("yt-search");, which should be placed at the top with the other requires.