Discord.js v12 踢人/封禁命令:权限限制与自定义原因实现问询
Fixing Your Discord.js v12 Kick & Ban Commands (Permissions + Custom Reasons)
Got it, let's tweak your existing commands to add the permission restrictions and custom reason support you need. I'll also clean up the code a bit by combining both commands into a single message event listener to keep things organized.
Key Changes We'll Make
- Permission Check: Only let users with kick/ban permissions (or a specific role) run these commands
- Custom Reason Support: Let users specify a reason that shows up in audit logs and your bot's messages
- Cleaner Code: Combine both command handlers into one event listener to avoid redundancy
Full Updated Code
client.on('message', message => { // Ignore DMs and bot messages to avoid unnecessary processing if (!message.guild || message.author.bot) return; // Kick Command Logic if (message.content.startsWith('!kick')) { // Check if the command user has permission to kick members if (!message.member.hasPermission('KICK_MEMBERS')) { return message.reply('Lo siento, no tienes permisos para usar este comando!'); } // Split message into arguments to extract user and reason const args = message.content.slice('!kick'.length).trim().split(/ +/); const targetUser = message.mentions.users.first(); // Use all text after the mention as reason; default if none is provided const kickReason = args.slice(1).join(' ') || 'Sin razón especificada'; // Validate if a user was mentioned if (!targetUser) { return message.reply("Pero hombre, mencioname al pobrecito que vas a kickear..."); } const targetMember = message.guild.member(targetUser); // Check if the user is actually in the guild if (!targetMember) { return message.reply("El jugador no está en el Guild!"); } // Attempt to kick the member targetMember.kick(kickReason) .then(() => { message.reply(`Has kickeado a: ${targetUser.tag} | Razón: ${kickReason}`); }) .catch(err => { message.reply('No he podido kickear al miembro. Probablemente tiene permisos más altos que yo!'); console.error(err); }); } // Ban Command Logic if (message.content.startsWith('!ban')) { // Check if the command user has permission to ban members if (!message.member.hasPermission('BAN_MEMBERS')) { return message.reply('Lo siento, no tienes permisos para usar este comando!'); } // Split message into arguments to extract user and reason const args = message.content.slice('!ban'.length).trim().split(/ +/); const targetUser = message.mentions.users.first(); // Use all text after the mention as reason; default if none is provided const banReason = args.slice(1).join(' ') || 'Sin razón especificada'; // Validate if a user was mentioned if (!targetUser) { return message.reply("Pero hombre, mencioname al pobrecito que vas a banear"); } const targetMember = message.guild.member(targetUser); // Check if the user is actually in the guild if (!targetMember) { return message.reply("El jugador no está en el Guild!"); } // Attempt to ban the member (pass reason to audit logs) targetMember.ban({ reason: banReason }) .then(() => { message.reply(`Has baneado a: ${targetUser.tag} | Razón: ${banReason}`); // Optional: Send a DM to the banned user (note: this might fail if they blocked the bot) targetUser.send(`Has sido baneado de ${message.guild.name} por: ${banReason}`) .catch(err => console.log("No se pudo enviar el DM al usuario baneado")); }) .catch(err => { message.reply('No he podido banear al usuario. Probablemente tiene permisos más altos que yo!'); console.error(err); }); } });
How It Works
Permission Check:
- We use
message.member.hasPermission('KICK_MEMBERS')andmessage.member.hasPermission('BAN_MEMBERS')to verify the command user has the right server permissions. If you prefer to restrict to a specific role instead, you can use this snippet:// Example: Check for a "Moderador" role const hasModeratorRole = message.member.roles.cache.some(role => role.name.toLowerCase() === 'moderador'); if (!hasModeratorRole) { return message.reply('Solo los moderadores pueden usar este comando!'); }
- We use
Custom Reason:
- We split the message content into parts, take everything after the mentioned user, and join it back into a reason string. If no reason is provided, it defaults to
Sin razón especificada.
- We split the message content into parts, take everything after the mentioned user, and join it back into a reason string. If no reason is provided, it defaults to
Error Handling:
- Updated error messages to give clearer context (like if the target has higher permissions than the bot)
- Added a fallback for banned user DMs (since bots can't message users who've blocked them)
Usage Examples
- Kick with a reason:
!kick @Usuario#1234 Por spamear en el canal general - Ban without a reason:
!ban @Usuario#1234
内容的提问来源于stack exchange,提问作者SaM85




