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

如何使用Discord.js实现封禁限制功能?

用Discord.js实现封禁限制功能的完整指南

当然可以!Discord.js完全支持实现封禁限制功能,下面我给你一套完整的实现方案,包括基础代码和关键功能解析,你可以直接参考调整。

一、前期准备

  • 确保你已经安装了Discord.js:npm install discord.js
  • 你的机器人拥有管理员权限(或者至少有BanMembers权限),否则无法执行封禁操作
  • 已经完成Discord机器人的创建,并成功邀请到目标服务器中

二、基础封禁限制器实现示例

这个示例包含两个核心功能:自动检测违规次数达到阈值后封禁用户,以及限制管理员手动封禁的频率防止滥用。

const { Client, GatewayIntentBits, PermissionsBitField } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers
  ] 
});

// 存储用户违规次数(重启机器人会清空,建议后续改用数据库持久化)
const userWarnings = new Map();
// 存储封禁操作冷却时间,防止频繁封禁
const banCooldowns = new Map();

// 机器人登录成功提示
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// 消息处理逻辑
client.on('messageCreate', async (message) => {
  // 忽略机器人自身发送的消息
  if (message.author.bot) return;

  // --- 自动违规检测与封禁逻辑 ---
  // 自定义违规关键词,你可以根据需求修改
  const forbiddenKeywords = ['违规词1', '违规词2'];
  const hasViolation = forbiddenKeywords.some(keyword => message.content.toLowerCase().includes(keyword));

  if (hasViolation) {
    const userId = message.author.id;
    // 更新违规次数,首次违规则初始化为1
    userWarnings.set(userId, (userWarnings.get(userId) || 0) + 1);
    const warningCount = userWarnings.get(userId);

    await message.reply(`你已违规 ${warningCount} 次!累计3次将被封禁。`);

    // 达到封禁阈值,执行封禁
    if (warningCount >= 3) {
      const botId = client.user.id;
      const now = Date.now();
      const cooldown = 5 * 60 * 1000; // 机器人自动封禁的5分钟冷却

      // 检查冷却时间
      if (banCooldowns.has(botId) && now < banCooldowns.get(botId) + cooldown) {
        const remaining = Math.ceil((banCooldowns.get(botId) + cooldown - now) / 1000);
        return message.reply(`封禁操作过于频繁,请等待 ${remaining} 秒后再试。`);
      }

      try {
        // 执行封禁,可设置临时封禁时长(deleteMessageSeconds:单位秒,比如86400=1天)
        await message.member.ban({ 
          reason: '累计3次违规',
          // deleteMessageSeconds: 86400
        });
        await message.channel.send(`${message.author.tag} 因多次违规已被封禁!`);
        // 重置该用户的违规记录
        userWarnings.delete(userId);
        // 更新机器人冷却时间
        banCooldowns.set(botId, now);
      } catch (err) {
        console.error('自动封禁失败:', err);
        message.reply('无法执行封禁,请检查机器人是否拥有足够权限。');
      }
    }
  }

  // --- 管理员手动封禁命令(带冷却限制) ---
  if (message.content.startsWith('!ban')) {
    // 检查发送命令的用户是否有封禁权限
    if (!message.member.permissions.has(PermissionsBitField.Flags.BanMembers)) {
      return message.reply('你没有权限执行封禁操作!');
    }

    const args = message.content.slice(4).trim().split(' ');
    const targetUser = message.mentions.members.first();
    const banReason = args.slice(1).join(' ') || '无理由';

    if (!targetUser) {
      return message.reply('请指定要封禁的用户!');
    }

    // 检查管理员的封禁冷却
    const adminId = message.author.id;
    const now = Date.now();
    const cooldown = 2 * 60 * 1000; // 管理员手动封禁的2分钟冷却

    if (banCooldowns.has(adminId) && now < banCooldowns.get(adminId) + cooldown) {
      const remaining = Math.ceil((banCooldowns.get(adminId) + cooldown - now) / 1000);
      return message.reply(`你封禁操作太频繁,请等待 ${remaining} 秒后再试。`);
    }

    try {
      await targetUser.ban({ reason: banReason });
      await message.channel.send(`${targetUser.user.tag} 已被 ${message.author.tag} 封禁,理由:${banReason}`);
      // 更新管理员冷却时间
      banCooldowns.set(adminId, now);
    } catch (err) {
      console.error('手动封禁失败:', err);
      message.reply('无法执行封禁,请检查目标用户的权限是否高于机器人。');
    }
  }
});

// 替换成你的机器人令牌
client.login('你的机器人令牌');

三、关键功能解析

  • 违规次数追踪:用Map对象userWarnings实时存储用户违规次数,存取效率高,适合临时存储(如果需要持久化,建议改用SQLite或MongoDB)
  • 冷却机制:banCooldowns记录每次封禁的时间戳,避免同一账号(机器人或管理员)短时间内频繁执行封禁操作
  • 权限校验:无论是自动封禁还是手动封禁,都会先检查权限,避免因权限不足导致操作失败
  • 错误捕获:通过try/catch捕获封禁过程中的异常,比如目标用户权限更高、机器人权限不足等情况,并给出友好提示

四、扩展建议

  • 将违规记录和冷却时间存储到数据库,重启机器人后不会丢失数据
  • 添加临时封禁的自定义时长设置,让管理员可以指定封禁天数/小时
  • 增加违规警告的阈值配置,允许管理员通过命令修改封禁触发的违规次数
  • 新增封禁日志频道,自动记录所有封禁操作的详细信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:16:09