Discord.JS music bot instantly disconnects - discord.js

I am trying to make a Discord Music Bot (discord.js), but everytime the bot connects to the channel to play music it disconnects instantly.
This is the tutorial I have followed: https://gabrieltanner.org/blog/dicord-music-bot
There are not any errors and the ffmpeg is installed.
I am running the bot on a centos 8 VPS, and I have other bots that work fine (not music ones xD)

In the play function, delete the line that contains serverQueue.voiceChannel.leave();.
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
}
The resulting code should like this:
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
queue.delete(guild.id);
return;
}
}

Maybe you can setTimeout for this
if (!song) {
setTimeout(function () {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}, 300000);
}

Related

Bad Audio Quality With discordjs/voice

I am trying to make a Discord music bot with Discord.js v14 and #discord.js/voice and I have got it to join a voice channel and play an mp3 file. However, the audio quality is terrible (bass is VERY bad) - but the mp3 file is fine when played normally.
My code:
const connection = DiscordVoice.joinVoiceChannel({
channelId: `1021824877130424461`,
guildId: `729979584296124467`,
adapterCreator: interaction.guild.voiceAdapterCreator,
})
const player = DiscordVoice.createAudioPlayer({
behaviors: {
noSubscriber: DiscordVoice.NoSubscriberBehavior.Pause,
},
})
player.on(DiscordVoice.AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!')
});
const resource = DiscordVoice.createAudioResource(path.join(process.cwd(), `/Ready_Set_Chill.mp3`), { inlineVolume: true })
resource.volume.setVolumeLogarithmic(100)
player.play(resource)
connection.subscribe(player)
interaction.reply(`Playing.`)
Any help would be much appreciated!

How to make a raw event run only once

I have a raw event:
this.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
const channel = this.channels.cache.get(packet.d.channel_id);
if (channel.messages.cache.has(packet.d.message_id)) return;
channel.messages.fetch(packet.d.message_id).then(message => {
const emoji = packet.d.emoji.id ? `${packet.d.emoji.name}:${packet.d.emoji.id}` : packet.d.emoji.name;
const reaction = message.reactions.cache.get(emoji);
if (reaction) reaction.users.cache.set(packet.d.user_id, this.users.cache.get(packet.d.user_id));
if (packet.t === 'MESSAGE_REACTION_ADD') {
this.emit('messageReactionAdd', reaction, this.users.cache.get(packet.d.user_id));
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
this.emit('messageReactionRemove', reaction, this.users.cache.get(packet.d.user_id));
}
});
});
This event spams continuously when one reaction is added, I want to make it so if you react it will run once. How can I do this?
You should not use the raw event past discord.js version 12. As there are some issues when your bot grows.
Instead use Partials as explained in the offical Discord.js Guide
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.on('messageReactionAdd', async (reaction, user) => {
// When we receive a reaction we check if the reaction is partial or not
if (reaction.partial) {
// If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message: ', error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
// Now the message has been cached and is fully available
console.log(`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`);
// The reaction is now also fully available and the properties will be reflected accurately:
console.log(`${reaction.count} user(s) have given the same reaction to this message!`);
});
Source and more information: https://discordjs.guide/popular-topics/reactions.html#listening-for-reactions-on-old-messages

restarting server.js for new command

I make discord bot via node.js on my pc and when I start server.js and add command, the new command not working I need to turn off the server.js and turn on server.js
How I make a new command without restarting the server.js?
The server.js
let Discord = require("discord.js");
let client = new Discord.Client();
client.on('ready', () => {
console.log(`Hello ${client.user.tag}!`);
});
client.on("message", message => {
if (message.content === "hi"){
message.channel.send("hi")
} else if (message.content === "how are you") {
message.channel.send("I am fine")
} else if (message.content === "test") {
message.channel.send("okay")
} else if (message.content === "who made you?") {
message.channel.send("XX")
}
})
client.login("secret_key");
Thats how Node.js works. You can edit your file as you like but unless you restart your server the changes won't show up.
For this I recommend you Nodemon, which restarts your server every time file changes in the directory are detected.

How do you make some bot commands only work in some discord channels

This is my first time using js. I need to ban a certain word in a certain channel. I don't want the message to be deleted if it is not in the specific channel.
For Example:
I want to ban the word "goodbye" in the #greeting channel
BUT
I don't want to ban the word "goodbye" In the #farewell channel
How would I go about this?
Thanks.
By the way I wanted to use example code, but none of it made any sense.
I wrote a simple example for you on how to achieve this:
const Discord = require("discord.js");
const Client = new Discord.Client();
const ForbiddenWords = {
"ChannelID": ["goodbaye", "bye"] // Greeting channel
};
Client.on("ready", () => {
console.log(`${Client.user.tag} is ready!`);
});
Client.on("message", (message) => { // Fired when the bot detects a new message.
if (message.author.bot) {return false}; // Checking if the message author is a bot.
if (ForbiddenWords[message.channel.id]) { // Checking if the current channel has any forbidden words in the ForbiddenWords Object
if (ForbiddenWords[message.channel.id].some(word => message.content.toString().toLowerCase().includes(word))) { // Checking if the message contains any forbidden words
message.delete(); // Deleting the message.
};
};
});
Client.login(process.env.DISCORD_AUTH_TOKEN);

How to do restart function with client.destroy and client.login when you already have a listener?

I've done a shutdown command, but now I want to create a restart command that destroy's my client, then reconnects to the websocket. I'm just having a bit of trouble with it since I have command/event handlers set up with a ready listener.
I typed the code out, and started getting errors for the specific command. Or, i'd get the bot up and it would crash upon trying to use the command.
const { prefix } = require("../../botconfig.json");
module.exports = {
config: {
name: "restart",
description: "restarts the bot",
usage: "wrestart",
category: "moderation",
accessableby: "Bot Owner",
aliases: ["rs"]
},
run: async (bot, message, args) => {
if(message.author.id != "id") return message.channel.send("You're not bot the owner!")
try {
//I want to do the destroy/login command here...
//client.destroy()
//client.login('token') <--- and do I really have to define the token if I already have it in my botconfig?
} catch(e) {
message.channel.send(`ERROR: ${e.message}`)
}
}
}
I want to issue a command "wrestart" and it restart my application. Results so far are basically typing the code and getting it incorrect...so starting from scratch basically.
Use:
const token = bot.token; // Copies the token into the Variable
bot.destroy(); // Stops the Bot
bot.login(token); // Uses the token we saved before to reauth
I was able to figure it out with this...
run: async (client, message, args) => {
if(message.author.id != "299957385215344640") return message.channel.send("You're not bot the owner! https://i.imgur.com/8ep8YbI.gif")
try {
message.channel.send("<a:Loading:575715719103381506> Attempting a restart...").then(msg => {
//msg.react('🆗');
setTimeout(function(){
msg.edit("<:CheckMark:550460857625346066> I should be back up now!");
}, 10000);
})
.then(client.destroy())
.then(client.login('tokengoeshere'))
} catch(e) {
message.channel.send(`ERROR: ${e.message}`)
}
}
This is what I use for my bot, a simple one line of code.
client.destroy().then(client.login(process.env.BOT_TOKEN))

Resources