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))
}
}
}
Related
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!
enter image description herethis bot has been working for about 2 weeks and suddenly it wont go online? The terminal isn't spitting out any errors at all. It isn't even logging the ready message. I'm quite new to this so if you do need any further information just let me know :)
edit:: I've restored the token a few times and reinvited the bot myself but that isn't fixing it :/
The client.js file:
const {Client, Intents, Collection } = require('discord.js');
require('dotenv').config();
const client = new Client ({intents: [Intents.FLAGS.GUILDS]});
const fs = require('fs');
client.commands = new Collection();
const functions = fs.readdirSync("./src/functions").filter(file => file.endsWith(".js"));
const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js"));
const commandFolders = fs.readdirSync("./src/commands");
(async () => {
for(file of functions){
require(`./functions/${file}`)(client);
}
client.handleEvents(eventFiles, "./src/events");
client.handleCommands(commandFolders, "./src/commands");
client.on("ready", () => {
client.user.setActivity('discord.js', { type: 'WATCHING' });
});
client.login(process.env.token);
});
In this piece of code, you are making an async anonymous function. However, you are just defining it. You are not calling it! That means that none of your commands nor events are being loaded. In order to make them load, you must call the function.
(async () => {
// your loader code here
client.login(process.env.token);
// notice the extra () here. That is calling the function.
})();
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);
};
});
I am in the process of creating a Would You Rather command for my bot.
I have everything in place, except one feature I can't work out how to implement.
I would love to have it so that when someone reacts with their answer (🅰️ or 🅱️) the bot then edits the embed and puts the user who replied under their answer like this:
The code I currently have is:
case "wyr":
embed.setColor('#fc2803')
embed.setTitle('Would You Rather?')
embed.setDescription(':a: **Be able to fly** \n \n :b: **Breathe underwater**')
message.channel.send(embed).then(m => m.react('🅰️')).then(r => r.message.react('🅱️'));
You can easily implement this using the discord.js-collector package.
But if you want to make it using plaine discord.js, then you will have to listen to reactions when sending the embed, and then edit it to what you want like in the example i will give.
Simple Example Using The discord.js-collector package:
Code Here
And Live Preview Here
Simple Example Using Plaine Discord.js:
const Discord = require("discord.js");
const embed = new Discord.MessageEmbed()
.setTitle("Hello There!");
const embedtosend = await message.channel.send(embed).then(m => m.react('🅰️')).then(r => r.message.react('🅱️'));
const filter = (reaction, user) => {
return ['🅰️', '🅱️'].includes(reaction.emoji.name) && user.id === message.author.id;
};
message.awaitReactions(filter, { max: 2, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '🅰️') {
const someotherembed = new Discord.MessageEmbed()
.setTitle("This Is A Different Hello There!");
embedtosend.edit(someotherembed)
} else if (reaction.emoji.name === '🅱️') {
const anotherembed = new Discord.MessageEmbed()
.setTitle("This Is A Different Embed!");
embedtosend.edit(anotherrembed)
}
});
I haven't tested this code, so it might not work...
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
}