Command to ban by mention in discord - javascript

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;

Related

how to make an slash command with random answers?

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

Discord.js Error with my embed and idk how to resolve it

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

DiscordJS Error - ReferenceError: member is not defined

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

SyntaxError: Unexpected token '{' Discord.js

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.

Delete an embed when a reaction is added

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.

Categories

Resources