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 :)
Related
"const's"
const { SlashCommandBuilder, Permissions } = require("discord.js");
const GuildSettings = require("../models/GuildSettings");
Codding
if(!interaction.member.permissions.has([Permissions.FLAGS.ADMINISTRATOR]))
{
interaction.reply("Você não possui permissão para executar este comando");
return;
}
Erro console
TypeError: Cannot read properties of undefined (reading 'FLAGS')
Note: I appreciate if you can help me. In itself is a configuration system that saves everything in a variable. But it's not ready yet, but even this part was supposed to be at least working. As much as it's still not saving directly to a variable (which I need to test this out).
In Djsv14 you have to change your code a little bit
const { SlashCommandBuilder, PermissionsBitField } = require("discord.js");
const GuildSettings = require("../models/GuildSettings");
if(!interaction.member.permissions.has(PermissionsBitField.Flags.Administrator))
{
interaction.reply("Você não possui permissão para executar este comando");
return;
}
i have a embed on my ready.js that sends it to a channel, and its giving me this error
ValidationError: Expected the value to be an object, but received string instead
at ObjectValidator.handle (/root/ZyruzBot/node_modules/#sapphire/shapeshift/dist/index.js:1161:25)
at ObjectValidator.parse (/root/ZyruzBot/node_modules/#sapphire/shapeshift/dist/index.js:113:88)
at EmbedBuilder.setAuthor (/root/ZyruzBot/node_modules/discord.js/node_modules/#discordjs/builders/dist/messages/embed/Embed.cjs:42:37)
at sendTicketMSG (/root/ZyruzBot/events/ready.js:13:10)
at Timeout._onTimeout (/root/ZyruzBot/events/ready.js:86:7)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
validator: 's.object(T)',
given: '🎫 Cria um ticket aqui'
}
Heres the embed and the start of the code:
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: 'ready',
async execute(client) {
console.log('Bot Online!')
console.log('Bot Dev Chain');
const oniChan = client.channels.cache.get(client.config.ticketChannel)
function sendTicketMSG() {
const embed = new EmbedBuilder()
.setColor('ff0000')
.setAuthor('🎫 Cria um ticket aqui', client.user.avatarURL())
.setDescription('Aqui pode abrir um ticket para obter\n\n **__<:SupportTeam:1013602711683473499> Suporte\n <:Servers:1013601908105171014> Adquirir a sua vps\n <a:developer_bot:1013602040745824336> Adquirir o seu bot de discord\n <a:partnership:1013602912162828308> Fazer uma Parceria__**')
.setFooter(client.config.footerText, client.user.avatarURL())
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageButton()
.setCustomId('open-ticket')
.setLabel('Cria um ticket aqui')
.setEmoji('🎫')
.setStyle('PRIMARY'),
);
oniChan.send({
embeds: [embed],
components: [row]
})
}
Idk whats generating this error, if you guys know please let me know
Your error lies in the .setAuthor() Method. It seems, that you use a newer version of discord.js in which this method requests an Object with the information.
In this link is another example using an object, maybe this will resolve your issue.
EmbedBuilder
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