DiscordJS v13 Music Bot - node.js

I'm having a problem trying to get my discord bot to play songs.
It is able to enter the voice channel and search for the song, but when it enters it does not play anything, I look at the status of the player and it comes out 'buffering'.
const { joinVoiceChannel, createAudioPlayer, createAudioResource, StreamType, AudioPlayerStatus, NoSubscriberBehavior } = require('#discordjs/voice');
const { Client, Intents, Interaction } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const ytdl = require('ytdl-core');
const yrS = require('yt-search');
async function vdSearch(cancion){
const vdE = await yrS(cancion);
return vdE.videos.length > 0 ? vdE.videos[0] : null;
}
client.on('messageCreate', async(message) =>{
switch(args[0]){
case 'play':
const vdRepro = await vdSearch(args[1]);
if(!vdRepro){
message.channel.send("No se ha encontrado esa cancion");
}else{
message.channel.send("Reproduciendo: "+ vdRepro.title);
}
//CONEXION
const stream = ytdl(vdRepro.url, { filter:'audioonly' });
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
var resource = createAudioResource(stream, {inputType:StreamType.Arbitrary,});
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause,
},
});
player.play(resource);
connection.subscribe(player);
console.log(player.state);
break;
}
})
Does anyone know how I could solve it?
Thanks for taking the time to read

I would recommend that you use "Distube". Its really easy to use and great for Musik Bots.
https://distube.js.org/#/docs/JS-DisTube/v2/class/DisTube
For example the play() command in Distube is distube.play(message, "searchQuery")

Related

discord bot doesnt play music

I have a discord bot that im trying to make play music. It will join the voice channel but it wont play anything. I've tried lots of things but nothing seems to be working. Here is the code:
const ytdl = require("ytdl-core")
const ytSearch = require("yt-search")
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource
} = require('#discordjs/voice')
module.exports = {
name: "play",
description: "Plays a song of your choice.",
async execute(messageCreate, args) {
const voiceChannel = messageCreate.member.voice.channel
if (!voiceChannel) return messageCreate.channel.send("You must be in a voice channel to run this command.")
const permissions = voiceChannel.permissionsFor(messageCreate.client.user)
if (!permissions.has("CONNECT")) return messageCreate.channel.send("You do not have the sufficient permissions to do this.")
if (!permissions.has("SPEAK")) return messageCreate.channel.send("You do not have the sufficient permissions to do this.")
if (!args.length) return messageCreate.channel.send("You must specify some keywords to identify the song you are looking for.")
joinVoiceChannel({
channelId: messageCreate.member.voice.channel.id,
guildId: messageCreate.guild.id,
adapterCreator: messageCreate.guild.voiceAdapterCreator
})
const videoFinder = async (query) => {
const videoResult = await ytSearch(query)
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null
}
const video = await videoFinder(args.join(" "))
if (video) {
const stream = ytdl(video.url, {filter: "audioonly"})
const player = createAudioPlayer()
const resource = createAudioResource(stream)
async function play() {
await player.play(resource)
connection.subscribe(player)
connection.play(stream, {seek: 0, volume: 1})
.on("finish", () => {
voiceChannel.leave()
})
}
await messageCreate.reply(`:thumbsup: Now playing: ***${video.title}***.`)
} else {
messageCreate.channel.send("No video results found.")
}
}
}
I am using VS Code node.js 18.7.0 and discord.js v13. I really need help with this so anything would be appreciated.
From what I can see, you're never actually playing the video.
You define this function, 'play,' but never call it.
async function play() {
await player.play(resource)
connection.subscribe(player)
connection.play(stream, {seek: 0, volume: 1})
.on("finish", () => {
voiceChannel.leave()
})
}
From what I can tell, you're trying to make an async function so you can use the await keyword, but this isn't necessary. Just put the body of the play function into the code normally, and the stream should play to the channel.
const ytdl = require("ytdl-core")
const ytSearch = require("yt-search")
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource
} = require('#discordjs/voice')
module.exports = {
name: "play",
description: "Plays a song of your choice.",
async execute(messageCreate, args) {
const voiceChannel = messageCreate.member.voice.channel
if (!voiceChannel) return messageCreate.channel.send("You must be in a voice channel to run this command.")
const permissions = voiceChannel.permissionsFor(messageCreate.client.user)
if (!permissions.has("CONNECT")) return messageCreate.channel.send("You do not have the sufficient permissions to do this.")
if (!permissions.has("SPEAK")) return messageCreate.channel.send("You do not have the sufficient permissions to do this.")
if (!args.length) return messageCreate.channel.send("You must specify some keywords to identify the song you are looking for.")
joinVoiceChannel({
channelId: messageCreate.member.voice.channel.id,
guildId: messageCreate.guild.id,
adapterCreator: messageCreate.guild.voiceAdapterCreator
})
const videoFinder = async (query) => {
const videoResult = await ytSearch(query)
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null
}
const video = await videoFinder(args.join(" "))
if (video) {
const stream = ytdl(video.url, {filter: "audioonly"})
const player = createAudioPlayer()
const resource = createAudioResource(stream)
async function play() {
await player.play(resource)
connection.subscribe(player)
connection.play(stream, {seek: 0, volume: 1})
.on("finish", () => {
voiceChannel.leave()
})
}
await messageCreate.reply(`:thumbsup: Now playing: ***${video.title}***.`)
} else {
messageCreate.channel.send("No video results found.")
}
}
}
If you really want to keep the play function, you can fix it by calling the function right after defining it.
async function play() {
/*...*/
}
play() // Just add this line here

So, I got a question. Is it possible to have a embed welcome message in a Discord bot that gets deleted after a few seconds?

var TOKEN = ""
const client = ("TOKEN");
const { Client, MessageEmbed } = require('discord.js');
const channel = ("CHANNELID");
const embed = new MessageEmbed()
('guildMemberAdd', member => {
const embed = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(`Welcome ${member}! You are the ${membercount}th member!`)
.setImage(member.user.avatarURL)
})
That is my current code for this but, I'm unsure because there are some errors to it.
Yes it is possible.
Please don't use this code, it will not work based on how you have it coded now
var TOKEN = ""
const client = ("TOKEN");
const { Client, MessageEmbed } = require('discord.js');
const channel = ("CHANNELID");
const embed = new MessageEmbed()
('guildMemberAdd', member => {
const embed = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(`Welcome ${member}! You are the ${membercount}th member!`)
.setImage(member.user.avatarURL)
})
Please use the code below:
// var TOKEN = "" //token is never a variable
// const client = ("TOKEN"); //please find a different way to code this as this will cause confusion later on
const TOKEN = ""
const { Client, MessageEmbed } = require('discord.js');
const client = new Client({
intents: [], // pick the intents you need here https://discord.com/developers/docs/topics/gateway#list-of-intents
})
client.login(TOKEN)
client.on('guildMemberAdd', member => {
const welcomeChannel = client.channels.cache.get("channel_id")
const membercount = member.guild.members.cache.filter(member => !member.user.bot).size
const timeout = 30 * 1000 //30 being how many seconds till the message is deleted.
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle(`${member.displayName} has joined us!`)
.setDescription(`Welcome ${member}!\nYou are member number ${membercount}!`)
.setThumbnail(member.displayAvatarURL())
welcomeChannel.send({
embeds: [embed]
}).then((message) => {
setTimeout(() => {
message.delete()
}, timeout);
})
})
Yes, you can!
just use
.then(msg => {
setTimeout(() => {
msg.delete().catch(() => null)
}, 5000)
})

Discord.js music bot stops playing

My discord.js music bot randomly stops playing music.
Here's the error report:
Emitted 'error' event on B instance at:
at OggDemuxer.t (/Users/myName/Bot/node_modules/#discordjs/voice/dist/index.js:8:288)
It says the error type is an "ECONNRESET" (code: 'ECONNRESET')
After this error the bot shortly goes offline and the code stops running (all commands don't work)
The code that I use to play music is as follows:
const { Client, Intents, MessageEmbed } = require('discord.js');
const { token } = require('./config.json');
const { joinVoiceChannel, createAudioPlayer, createAudioResource } = require('#discordjs/voice');
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
client.once('ready', () => {
console.log('Ready!');
});
const videoFinder = async (search) => {
const videoResult = await ytSearch(search)
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
client.on('messageCreate', msg => {
if(msg.content === '!join') {
connection = joinVoiceChannel({
channelId: msg.member.voice.channel.id,
guildId: msg.guild.id,
adapterCreator: msg.guild.voiceAdapterCreator
})
if (msg.content.substring(0, 6) === '!play ') {
let searchContent = msg.content.substring(6)
async function playChosen() {
let ourVideo = await videoFinder(searchContent)
const stream = ytdl(ourVideo.url, { filter: 'audioonly' })
const player = createAudioPlayer()
let resource = createAudioResource(stream)
player.play(resource)
connection.subscribe(player)
}
playChosen()
}
}
client.on('error', error => {
console.error('The WebSocket encountered an error:', error);
});
client.login(token);
I know the code is kinda messy, but if anybody could help, I'd really appreciate it! Also, I use discord.js v13, and the bot will typically play part of the song before this error comes up.
Yet again, I've posted a question that I quickly found an answer to lol. The problem here was being caused by ytdl-core, which would just randomly shut off for some reason. Play-dl worked much better to combat this. Here's a link to the place where I got this info:
Discord.js/voice How to create an AudioResource?
play-dl link:
https://www.npmjs.com/package/play-dl
example:
https://github.com/play-dl/play-dl/blob/5a780517efca39c2ffb36790ac280abfe281a9e6/examples/YouTube/play%20-%20search.js
for the example I would suggest still using yt-search to obtain the url as I got some wonky results using their search method. Thank you!

Setting up chatbot command in discord.js 12

i wanted to make a chatbot command like a example of command
?bsetchatbot [channel name]
heres a syntax of the command and here what code i used
note - i already impoted required modules
const Chat = require("easy-discord-chatbot");
const chat = new Chat({ name: "Blabbermouth" });
if (message.content === "?bsetchatbot") {
channelname = message.mentions.channels.first()
if(!channelname) {
return message.channel.send("Pleease Mention A channel!")
}
if(message.channel.name === `${channelname}` && !message.author.bot) {
let reply = await chat.chat(message.content)
message.channel.send(reply)
}
message.channel.send(`Chat Bot Channel is set as ${channelname}`)
}
The problem is that you don't save the channel where people can chat with the bot. I recommend to save the channel with the ValueSaver package as you can can save it and import it again when your server shut down. Here is an example
const { ValueSaver } = require('valuesaver');
const channels = new ValueSaver();
channels.import(`channels`); // Import the ValueSaver named 'channels' if a save exists with this name
const { Client } = require('discord.js');
const Chat = require('easy-discord-chatbot');
const chat = new Chat({name: 'Blabbermouth'});
const client = new Client();
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag} on ${new Date().toString()}`);
});
client.on('message', async message => {
if(message.author.bot || message.channel.type === `DM`) return;
let args = message.content.substring(1).split(" ");
const _channelid = channels.get(message.guild.id); // Get the channel id
if(_channelid){ // If there has been set a channel
if(message.channel.id === _channelid){ // If the channel is the chat channel
let reply = await chat.chat(encodeURI(message.content));
message.channel.send(reply).catch(console.log)
}
}
if(message.content.startsWith('?')){
switch(args[0].toLowerCase()){
case 'bsetchatbot':
const channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`Please mention a channel to set the chat channel`).catch(console.log);
channels.set(message.guild.id, channel.id); // Access the channel id by the guild id
channels.save(`channels`); // Create a new save with the name 'channels'
break;
}
}
});
client.login('Your Token');
ValueSaver: https://npmjs.com/package/valuesaver

Play discord command

Hello I have been having a problem with a play command with discord. I am unsure of what the problem is and if it is possible please help. I will be honest I got this code from somewhere else but its for a private server. Please help fix this thank you. Anyway I have been trying to create a play, stop, skip, nowplaying command for ages and if this works it would be amazing thank you.
Console Error:
TypeError: Cannot read property 'get' of undefined
Code:
const ytdl = require("ytdl-core");
module.exports = {
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(`Start playing: **${song.title}**`);
}
};
You should look where you got the code from, maybe you missed a part?
specifically where they define client.queue
usually most of the people define it like
client.queue = new Map()
or discord.js collection class (Extended from map)
in your main bot file (index.js, bot.js etc).
You could either check where you got code from or try adding this to where you define client in your main bot file

Resources