I am currently coding my discord bot I have already set these moderation and fun functions for her, I wanted my bot to make music so I made my orders but I stumble on a problem and I can't find where this comes, so i turn to you hoping that you can help me. here is my code:
exports.run(message) {
const serverQueue = message.client.queue.get(message.guild.id);
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return message.channel.send("⏸ La musique est en pause !")
}
return message.channel.send(
"Il n'y a aucune musique qui est en train de jouer !"
);
}
module.exports = Pause;
You forgot the Arrow Function (=>)
exports.run(message) => {
const serverQueue = message.client.queue.get(message.guild.id);
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return message.channel.send("⏸ La musique est en pause !")
}
return message.channel.send(
"Il n'y a aucune musique qui est en train de jouer !"
);
}
module.exports = Pause;
Please consider learning JavaScript and to find Errors yourself.
Related
My code does not return an error but when I call it on discord, it does not responding.
import { SlashCommandBuilder, EmbedBuilder, CommandInteraction } from "discord.js";
import { SlashCommand } from "../types";
export const command: SlashCommand = {
name: "dé",
data: new SlashCommandBuilder().setName("dé").setDescription("DUEL"),
execute: async (interaction) => {
const liste = [
"`1, tu as fait une réussite critique`",
"`2, tu as fait une réussite moyenne`",
"`3, tu as fait une réussite moyenne`",
"`4, tu as fait une petite réussite`",
"`5, tu as fait un petit échec`",
"`6, tu as fait un echec critique`",
"`7, quelque chose de drôle va arriver`",
"`8, ça provoque l'effet d'un autre sort`",
];
await interaction.reply({
embeds: [new EmbedBuilder().setDescription(liste[Math.floor(Math.random() * liste.length)])],
});
},
};
I would like to make an slashcommand that answers one of these eight answers at random.
I copied your code and checked myself, it works. So the problem is something else, didn't you forget to configure intents? Because it depends on whether the bot can write to the guild.
For example, you can set up the client in this way:
export const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageTyping
]})
You also need to go to https://discord.com/developers/applications/. There, click on the "Bot" tab and turn on all the checkboxes on Privileged Gateway Intents
P.S. Below I'm just proving that the code works. execute is a slash command
When I try to execute this code (for a warn system in Discord.JS), I have this error
ReferenceError: member is not defined
name: 'warn',
description: 'Pour warn un membre',
execute(message, args, Client){
if(!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Tu n'as pas les permissions de warn un membre");
if(message.channel.type == "dm") return;
let mention = message.mentions.members.first();
const reason = args.slice(1).join(' ')
if(mention == undefined){
message.reply("Membre non-menntionné ou mal mentionné");
}
else {
if (!reason) return message.channel.send("Veuillez indiquer une raison")
if (!Client.warn.warns[member.id]) Client.warn.warns[member.id] = []
Client.warn.warns[member.id].unshift({
reason,
date: Date.now(),
mod: message.author.id
})
fs.writeFileSync('./commands/bdd/warns.js', JSON.stringify[Client.warn])
message.channel.send(`${member} a été warn pour ${reason}`)
}
},
};
Can you help me ?
Thanks
You defined your member as mention, in the line:
let mention = message.mentions.members.first();, however, you use member in for example if (!Client.warn.warns[member.id]). If you change all the member which should be mention to mention, it's fixed :)
Hello I made a ban command, but on the line: I put:
which corresponds to the first mention of the message.
Except that the mention can be anywhere, so I'm looking for how to make the bot detect that the mention is at the beginning or not.
Any help is appreciated.
Thank you for taking the time to read this and I wish you a good day.
module.exports.run = async(client, message, args) => {
const Discord = require("discord.js");
const Breason = message.content.slice(22);
let target = message.mentions.users.first();
if(!message.guild.me.permissionsIn(message.channel.id).has("SEND_MESSAGES")) return;
if(!message.guild.me.permissionsIn(message.channel.id).has("EMBED_LINKS")) return;
if(!message.guild.member(client.user).hasPermission("BAN_MEMBERS")) return message.channel.send("Je n'ai pas la permsission de ban ce membre.")
if(!message.guild.member(message.author).hasPermission("BAN_MEMBERS")) return message.channel.send("Vous n'avez pas la permission de ban")
if(bUser === message.author.id) return message.channel.send("Vous ne pouvez pas vous auto-ban.")
if(!bUser) return message.channel.send("Veuillez mentionnez un utilisateur à bannir.")
if(!Breason) return message.channel.send("Ho ! Il manque une raison, serait ce un abus de privilèges ?:thinkinghard: ")
message.guild.members.ban(bUser, {reason: Breason})
const embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setTitle("Un membre à été banni !")
.addField("Membre banni :", bUser.tag, true)
.addField("Banni par:", message.author.tag, true)
.addField("Pour la raison:", Breason, true)
.setFooter("Une nouvelle personne a été banni !")
.setTimestamp()
message.channel.send(embed)
bUser.send(embed)
};
module.exports.help = {
name: "ban",
aliases: ["Bane", "banne"],
description: "Ban l'utilisateur mentionner.",
usage: "ban <user.mention> <raison>"
};
If my explanations are not clear, let me know and I will be happy to correct.
Assuming that args is an array of arguments from message.content (separated by whitespace),
let target = args[0].includes(message.mentions.users.first().id) ? message.mentions.users.first() : null;
module.exports.run = (client, message, args) => {
if (message.member.roles.some(role => role.name === process.env.MODO)) {
const user = message.mentions.users.first();
// Parse Amount
const amount = !!parseInt(message.content.split(' ')[1]) ? parseInt(message.content.split(' ')[1]) : parseInt(message.content.split(' ')[2])
if (!amount) return message.reply('Vous devez spécifier un montant à supprimer !');
if (!amount && !user) return message.reply('Vous devez spécifier un utilisateur et le montant, ou juste une quantité de messages à purger !');
if (amount > 100) return message.reply('Malheureusement, discord ne permet pas la Suppression de plus de 100 messages en une fois ...');
// Fetch 100 messages (will be filtered and lowered up to max amount requested)
message.channel.fetchMessages({
limit: amount,
}).then((messages) => {
if (user) {
const filterBy = user ? user.id : Client.user.id;
messages = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
}
message.channel.bulkDelete(messages).catch(error => console.log(error.stack));
});
var purge = new Discord.RichEmbed()
.setAuthor(`Suppression de ${amount} Messages dans le salon ${message.channel.name}`)
.setFooter("Requête par " + message.member.user.tag, message.member.user.avatarURL)
.setTimestamp()
.setColor(0xF03434)
message.channel.send(purge).then(message => {
message.react('🗑')
client.on('messageReactionAdd', (reaction, user) => {
// on vérifie que ce soit bien la bonne réaction et on ne compte pas celui du bot
if (reaction.emoji.name === '🗑' && user.id !== client.user.id) {
message.delete()
}
})
});
}
}
What I would like is that at the level of the 'final' embed, when it tells me that the purge has been done, there is a reaction '🗑' and when we click it removes the message.
The problem is that the current code removes all the embed of the same type.
If I click on the reaction of the first embed, it also removes the second, and does not delete anything else...
Attaching a listener to the client's messageReactionAdd event is what's causing this; any reaction emits this event, and your code is executed for each one after a single purge. As long as the reaction is 🗑 and the user isn't the client, Message.delete() will be called on message.
(node: 10752) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at item.request.gen.end (/Users/jeremy/Desktop/BERRYBOT/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15)
at then (/Users/jeremy/Desktop/BERRYBOT/node_modules/snekfetch/src/index.js:215:21)
at process._tickCallback (internal / process / next_tick.js: 68: 7)
(node: 10752) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated from the inside of the outside world, but it was not handled by .catch (). (rejection id: 14)
After adding that reaction that deletes the wrong message, it no longer exists. When you try to delete it again, this error will be thrown.
Furthermore, your code isn't waiting for the messages to be purged before sending the reply. Because of this, the message can be sent before and subsequently deleted by the TextChannel.bulkDelete() call. Then, when you try to react to the same message via Message.react(), your error is thrown because it no longer exists.
To make sure the code is executed in the proper order, make sure you're using your then() chains properly, or utilize the beauty of async/await.
Reorganizing the code, still using then() methods:
message.channel.fetchMessages({ limit: amount })
.then(fetchedMessages => {
const filterBy = user ? user.id : Client.user.id;
const toPurge = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
message.channel.bulkDelete(toPurge)
.then(deletedMessages => {
var embed = new Discord.RichEmbed()
.setAuthor(`Suppression de ${deletedMessages.size} Messages dans le salon ${message.channel.name}`)
.setFooter(`Requête par ${message.author.tag}`, message.author.avatarURL)
.setTimestamp()
.setColor(0xF03434)
message.channel.send(embed)
.then(reply => {
reply.react('🗑');
const filter = (reaction, user) => reaction.emoji.name === '🗑' && user.id !== client.user.id;
reply.createReactionCollector(filter, { maxMatches: 1 })
.on('collect', () => reply.delete());
});
});
})
.catch(console.error);
Alternatively, using await:
// You must define your callback function as async to use the 'await' keyword! It should look like...
// async (client, message, args) => { ... }
try {
const fetchedMessages = await message.channel.fetchMessages({ limit: amount });
const filterBy = user ? user.id : Client.user.id;
const toPurge = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
const deletedMessages = await message.channel.bulkDelete(toPurge);
var embed = new Discord.RichEmbed()
.setAuthor(`Suppression de ${deletedMessages.size} Messages dans le salon ${message.channel.name}`)
.setFooter(`Requête par ${message.author.tag}`, message.author.avatarURL)
.setTimestamp()
.setColor(0xF03434)
const reply = await message.channel.send(embed)
await reply.react('🗑');
const filter = (reaction, user) => reaction.emoji.name === '🗑' && user.id !== client.user.id;
reply.createReactionCollector(filter, { maxMatches: 1 })
.on('collect', async () => await reply.delete());
} catch(err) {
console.error(err);
}
You'll notice this code is using ReactionCollectors as opposed to attaching listeners to the messageReactionAdd event. The former are meant for this usage and will prevent memory leaks. Also, I've changed some of the variable names to make the code easier to read and understand. A few other very minor improvements are present as well.
So I'm making a discord bot for my server and I'm having some issues with my music code!
The code is located here.
When I run the bot it works well, but when I do the !play command it throws the following error:
Error: FFMPEG not found
If someone could help me, I would be thankful. Thank you for your time.
client.on('message', async msg => {
if (msg.author.bot) return undefined;
if (!msg.content.startsWith(prefix)) return undefined;
const args = msg.content.split(' ');
if (msg.content.startsWith(`${prefix}play`)) {
const voiceChannel = msg.member.voiceChannel;
if (!voiceChannel) return msg.channel.send('Tens de estár numa sala para eu poder entrar!');
const permissions = voiceChannel.permissionsFor(msg.client.user);
if (!permissions.has('CONNECT')) {
return msg.channel.send('Só podes tocar musica no canal de Musica!')
}
if (!permissions.has('SPEAK')) {
return msg.channel.send('Não posso tocar musica nesse canal!')
}
try {
var connection = await voiceChannel.join();
} catch (error) {
console.error(`Não consigo entrar no canal porque: ${error}`);
return msg.channel.send(`Não consigo entrar no canal de voz: ${error}`);
}
const dispatcher = connection.playStream(ytdl(args[1]))
.on('end', () => {
console.log('Acabou a musica');
voiceChannel.leave();
})
.on('error', error => {
console.error(error);
});
dispatcher.setVolumeLogarithmic(5 / 5);
} else if (msg.content.startsWith(`${prefix}stop`)) {
if (msg.member.voiceChannel) return msg.channel.send('Não estás no canal');
msg.member.voiceChannel.leave();
return undefined;
}
});
client.login(token);`
It seems that you have not installed ffmpeg.
You can find an easy tutorial on how to install and add ffmpeg to path here:
https://www.wikihow.com/Install-FFmpeg-on-Windows
After you have installed ffmpeg, it will also need to be installed with npm like so:
npm install ffmpeg