Discord.js music bot stops playing - node.js

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!

Related

Playing a specific song when a user calling a command

so what I am trying to reach is when a user call a !song1 command the bot will play the specified YouTube URL for this command, I do not want any kind of search just playing the YouTube URL I put in the code, please see the code below I know it is old and I am looking for something new and no errors in future, and I am really beginner in coding bots.
I hope I explain this issue successfully, thanks in advance.
song1.js
const ytdl = require('ytdl-core');
const Discord = require('discord.js')
const client = new Discord.Client()
module.exports = {
commands: 'song1',
callback: (message) => {
const url = 'https://www.youtube.com/song1url';
if (message.content == '!song1') {
if (!message.member.voice.channel) return message.reply("you should be on a vc");
message.member.voice.channel.join().then(VoiceConnection => {
VoiceConnection.play(ytdl(url)).on("finish", () =>
VoiceConnection.disconnect());
const embed = new Discord.MessageEmbed()
.setTitle('Now Playing: song1')
.setAuthor(message.author.username)
.setTimestamp()
.setColor('#447a88')
message.reply(embed)
}).catch(e => console.log(e))
}
}
}

DiscordJS v13 Music Bot

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

Making a simple music bot for discord server, not working

Working on making a bot for a personal discord server, wanting it to simply join general voicechat when command "Blyat" is detected, play mp3 file, when its done to leave. Code:
var Discord = require('discord.js');
var client = new Discord.Client();
var isReady = true;
client.on('message', message => {
if (command === "Blyat") {
var VC = message.member.voiceChannel;
if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.playFile('C:\Users\Wyatt\Music\soviet-anthem.mp3');
dispatcher.on("finish", end => { VC.leave() });
})
.catch(console.error);
};
});
client.login('token, not putting in code, is there in real code');
Error: "ReferenceError: command is not defined
at Client. (C:\Users\jeffofBread\Desktop\Discord Bot\main.js:6:5)"
Any help or tips will be much appreciated, haven't coded in many years and have lost any knowledge I had once held.
Your problem comes from an unidentified variable. Fortunatly that is very easy to fix. All you have to do is define command before you call it.
For this we'll splice the message content into two parts. The command and any arguments that may be included like mentions or other words. We do that with:
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
Note: The args constant is an array.
Which would make your entire onMessage event look like this:
client.on('message', message => {
const prefix = "!";
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "blyat") {
var VC = message.member.voice.channel;
if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.play('C:\Users\Wyatt\Music\soviet-anthem.mp3');
dispatcher.on("finish", end => { VC.leave() });
})
.catch(console.error);
};
});

channel.send is not a function? (Discord.JS)

Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}

Sqlite Discord.js: Cannot read property 'run' of null

So I am trying to make a SQLite database for my Discord.js bot, but I keep getting this error (Cannot read property of 'run' of null) when I try to use SQLite. Non of my friends seem to have this problem, so I thought to come here. Sorry if this is like a noobish question.. I'm still a little new to this
Here is my code:
const Discord = require("discord.js");
const client = new Discord.Client();
const bot = new Discord.Client();
const sql = require("sqlite")
const fs = require("fs");
const staff = ["97122523086340096", "450241616331145217", "283438590875402240", "288755621787074560"]
const config = require("./config.json");
client.on("ready", async () => {
console.log(`${client.user.username} is ready to help servers!`)
console.log ("Warning: I am being locally hosted. During high usage times, the bot may crash.")
console.log(`I am available in 1 shard! I am in ${client.guilds.size} guilds and serving ${bot.users.size}`)
client.user.setActivity("For sat!help", {type: "WATCHING"}, {status:"dnd"});
client.user.setPresence( {status:"idle"} )
sql.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)")
});
fs.readdir("./events/", (err, files) => {
if (err) return console.error(err);
files.forEach(file => {
let eventFunction = require(`./events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, (...args) => eventFunction.run(client, ...args));
});
});
client.on("message", message => {
if (message.author.bot) return;
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
try {
let commandFile = require(`./commands/${command}.js`);
commandFile.run(bot, message, args);
} catch (err) {
return
}
});
client.on("guildCreate", guild => {
let guildp = guild.owner
guildp.send("Thanks for adding me to your server! \n To save you some time I would suggest you run the command 'sat!setup' to create the nessecary roles and channels for the bot. \n Please note that the channel is not made with perms.\n ***[PLEASE NOTE!] - I am still in beta so any issues with any part of the bot please tell us with sat!bug! \n Thanks!")
})
client.login(config.token);
You need to open connection with the database and then run the SQL query.
const sql = require("sqlite")
const db = sql.open('./database.sqlite', { Promise });
db.run("CREATE TABLE IF NOT EXISTS guild (guildId TEXT, language INTEGER, links INTEGER)");

Resources