You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在基于Node.js的Discord机器人现有代码中添加!ban、!kick、!clear moderation命令并完成配置与测试

Adding Moderation Commands (!ban, !kick, !clear) to Your Discord.js Bot

Hey there! Let's get those moderation commands set up for your bot. First, I'll help you clean up your existing code (since having multiple message event listeners can cause unexpected issues) and then walk you through adding each command, plus answer all your questions.

First: Clean Up Your Existing Code

Right now, you have separate bot.on('message') blocks for every command. This isn't efficient—Discord.js will trigger all of them every time a message is sent. Let's combine everything into a single listener using else if statements to keep things organized:

require('dotenv').config();
const Discord = require('discord.js');
const bot = new Discord.Client();
const TOKEN = process.env.TOKEN;

bot.login(TOKEN); // Fixed this: you were using the string 'TOKEN' instead of your .env variable!

bot.on('ready', () => {
  console.info(`Logged in as ${bot.user.tag}!`);
});

// Combined all message commands into one listener
bot.on('message', message => {
  // Ignore bot messages to prevent infinite loops
  if (message.author.bot) return;

  // Existing commands
  if (message.content === '!ping') {
    message.channel.send('Pong.');
  } else if (message.content === '!getpizza') {
    message.channel.send('Welcome to Lynks Pizza!!! Heres your pizza and have a nice day!!!');
  } else if (message.content === '!shutup') {
    message.channel.send('Okay, I am sorry.');
  } else if (message.content === '!playdead') {
    message.channel.send(':dizzy_face:');
  } else if (message.content === '!user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
  } else if (message.content === '!server-info') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
  }
  // We'll add moderation commands here next!
});

Adding the Moderation Commands

Now let's build out !kick, !ban, and !clear. Each command includes permission checks (so only authorized users can run them) and error handling (to avoid crashes and give clear feedback).

1. !kick Command

Lets admins kick a user from the server:

else if (message.content.startsWith('!kick')) {
  // Check if the user has permission to kick members
  if (!message.member.hasPermission('KICK_MEMBERS')) {
    return message.channel.send("You don't have permission to kick members!");
  }

  // Get the user to kick (first mention in the message)
  const user = message.mentions.users.first();
  if (!user) {
    return message.channel.send("Please mention a user to kick!");
  }

  // Get the server member object for the user
  const member = message.guild.member(user);
  if (member) {
    // Kick the member with a reason
    member.kick('Kicked via moderation command')
      .then(() => message.channel.send(`Successfully kicked ${user.tag}!`))
      .catch(err => {
        message.channel.send("I couldn't kick that user—they might have a higher role than me!");
        console.error(err);
      });
  } else {
    message.channel.send("That user isn't in this server!");
  }
}

2. !ban Command

Permanently bans a user from the server:

else if (message.content.startsWith('!ban')) {
  if (!message.member.hasPermission('BAN_MEMBERS')) {
    return message.channel.send("You don't have permission to ban members!");
  }

  const user = message.mentions.users.first();
  if (!user) {
    return message.channel.send("Please mention a user to ban!");
  }

  const member = message.guild.member(user);
  if (member) {
    member.ban({ reason: 'Banned via moderation command' })
      .then(() => message.channel.send(`Successfully banned ${user.tag}!`))
      .catch(err => {
        message.channel.send("I couldn't ban that user—they might have a higher role than me!");
        console.error(err);
      });
  } else {
    message.channel.send("That user isn't in this server!");
  }
}

3. !clear Command

Deletes a specified number of messages from the channel:

else if (message.content.startsWith('!clear')) {
  if (!message.member.hasPermission('MANAGE_MESSAGES')) {
    return message.channel.send("You don't have permission to manage messages!");
  }

  // Split the command into parts to get the number of messages
  const args = message.content.split(' ');
  const amount = parseInt(args[1]);

  // Validate the number is between 1-100 (Discord's bulk delete limit)
  if (isNaN(amount) || amount < 1 || amount > 100) {
    return message.channel.send("Please provide a valid number between 1 and 100!");
  }

  // Bulk delete messages (+1 to remove the !clear command itself)
  message.channel.bulkDelete(amount + 1)
    .then(deletedMessages => {
      message.channel.send(`Deleted ${deletedMessages.size - 1} messages!`).then(msg => {
        // Delete the confirmation message after 3 seconds
        setTimeout(() => msg.delete(), 3000);
      });
    })
    .catch(err => {
      message.channel.send("I couldn't delete those messages—they might be older than 14 days!");
      console.error(err);
    });
}

Answering Your Specific Questions

1. How to embed the new command code into your current code?

Copy each of the three command blocks (the else if (...) sections) and paste them inside your single bot.on('message') listener, right after your existing commands. Look for the comment // We'll add moderation commands here next! in the cleaned-up code—paste them there.

2. How to configure the new command code?

  • Permissions: The commands use standard Discord permissions (KICK_MEMBERS, BAN_MEMBERS, MANAGE_MESSAGES). If you want to use custom roles instead, replace the permission check with something like:
    if (!message.member.roles.cache.some(role => role.name === 'Moderator')) {
      return message.channel.send("You need the Moderator role to use this command!");
    }
    
  • Command Triggers: Change the command name (e.g., !kick to !boot) by updating the string in message.content.startsWith('!kick').
  • Custom Reasons: Let users add their own reasons by modifying the code to capture extra arguments, like:
    const reason = args.slice(2).join(' ') || 'No reason provided';
    member.kick(reason);
    

3. Where to place the new code?

All new command code lives inside the single bot.on('message') listener we created. Keeping everything in one listener prevents unexpected behavior and makes your code easier to maintain.

4. How to test these commands?

  1. Set Bot Permissions: In your Discord server, go to Server Settings > Roles, find your bot's role, and enable Kick Members, Ban Members, and Manage Messages.
  2. Use an Admin Account: Test the commands with a user account that has Administrator permissions (or the required moderation role).
  3. Test Edge Cases:
    • Run the command without mentioning a user (should get an error message).
    • Run the command without permission (should get a "no permission" warning).
    • For !clear, try numbers outside 1-100 or non-numeric values (should get validation errors).
  4. Check the Console: If something breaks, the console will log errors to help you debug.

Full Modified Code

Here's the complete code with all your existing commands plus the new moderation tools:

require('dotenv').config();
const Discord = require('discord.js');
const bot = new Discord.Client();
const TOKEN = process.env.TOKEN;

bot.login(TOKEN);

bot.on('ready', () => {
  console.info(`Logged in as ${bot.user.tag}!`);
});

bot.on('message', message => {
  // Ignore bot messages to prevent loops
  if (message.author.bot) return;

  // Existing Commands
  if (message.content === '!ping') {
    message.channel.send('Pong.');
  } else if (message.content === '!getpizza') {
    message.channel.send('Welcome to Lynks Pizza!!! Heres your pizza and have a nice day!!!');
  } else if (message.content === '!shutup') {
    message.channel.send('Okay, I am sorry.');
  } else if (message.content === '!playdead') {
    message.channel.send(':dizzy_face:');
  } else if (message.content === '!user-info') {
    message.channel.send(`Your username: ${message.author.username}\nYour ID: ${message.author.id}`);
  } else if (message.content === '!server-info') {
    message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);

  // Moderation Commands
  } else if (message.content.startsWith('!kick')) {
    if (!message.member.hasPermission('KICK_MEMBERS')) {
      return message.channel.send("You don't have permission to kick members!");
    }

    const user = message.mentions.users.first();
    if (!user) {
      return message.channel.send("Please mention a user to kick!");
    }

    const member = message.guild.member(user);
    if (member) {
      member.kick('Kicked via moderation command')
        .then(() => message.channel.send(`Successfully kicked ${user.tag}!`))
        .catch(err => {
          message.channel.send("I couldn't kick that user—they might have a higher role than me!");
          console.error(err);
        });
    } else {
      message.channel.send("That user isn't in this server!");
    }

  } else if (message.content.startsWith('!ban')) {
    if (!message.member.hasPermission('BAN_MEMBERS')) {
      return message.channel.send("You don't have permission to ban members!");
    }

    const user = message.mentions.users.first();
    if (!user) {
      return message.channel.send("Please mention a user to ban!");
    }

    const member = message.guild.member(user);
    if (member) {
      member.ban({ reason: 'Banned via moderation command' })
        .then(() => message.channel.send(`Successfully banned ${user.tag}!`))
        .catch(err => {
          message.channel.send("I couldn't ban that user—they might have a higher role than me!");
          console.error(err);
        });
    } else {
      message.channel.send("That user isn't in this server!");
    }

  } else if (message.content.startsWith('!clear')) {
    if (!message.member.hasPermission('MANAGE_MESSAGES')) {
      return message.channel.send("You don't have permission to manage messages!");
    }

    const args = message.content.split(' ');
    const amount = parseInt(args[1]);

    if (isNaN(amount) || amount < 1 || amount > 100) {
      return message.channel.send("Please provide a valid number between 1 and 100!");
    }

    message.channel.bulkDelete(amount + 1)
      .then(deletedMessages => {
        message.channel.send(`Deleted ${deletedMessages.size - 1} messages!`).then(msg => {
          setTimeout(() => msg.delete(), 3000);
        });
      })
      .catch(err => {
        message.channel.send("I couldn't delete those messages—they might be older than 14 days!");
        console.error(err);
      });
  }
});

内容的提问来源于stack exchange,提问作者AriesTropixDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:52:45