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

如何在discord.js机器人中实现独立单词级别的违禁词检测?

解决违禁词独立单词检测问题

问题分析

当前用includes()方法检测违禁词会匹配子串,导致像"pineapple"包含"apple"这类非违禁内容被误拦截。加空格的方式无法覆盖违禁词在句首、句尾或标点前后的情况(比如"apple!"或"Apple")。

解决方案:使用正则表达式的单词边界

利用正则的\b元字符匹配单词边界,它能识别单词与非单词字符(空格、标点、字符串首尾)的分界,确保只匹配独立单词。同时处理以下情况:

  • 违禁词在句首/句尾
  • 违禁词前后带标点(如apple!、(apple))
  • 大小写不敏感(比如Apple也需要拦截)

实现步骤

  1. 为每个违禁词构建带单词边界的正则表达式,同时开启大小写不敏感模式
  2. 用RegExp.test()替代includes()进行检测
  3. 转义违禁词中的特殊正则字符(比如.或*),避免语法错误

修改后的代码

JavaScript 部分

const bannedWords = ["apple", "car", "test"];

const word2parse = document.getElementById("word2parse");
const output = document.getElementById("display");

function parse() {
  const isBanned = bannedWords.some(word => {
    // 转义特殊正则字符
    const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    // 创建正则:\b匹配单词边界,i开启大小写不敏感
    const regex = new RegExp(`\\b${escapedWord}\\b`, 'i');
    return regex.test(word2parse.value);
  });

  output.innerHTML = isBanned ? "这个词是违禁词" : "这个词没问题";
}

HTML 部分

<input type="text" id="word2parse">
<input type="button" onclick="parse()" value="检测">
<p id="display"></p>

在discord.js中实际应用

把检测逻辑移植到机器人的消息监听事件即可:

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

const bannedWords = ["apple", "car", "test"];

client.on('messageCreate', (message) => {
  // 忽略机器人自身消息
  if (message.author.bot) return;

  const isBanned = bannedWords.some(word => {
    const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const regex = new RegExp(`\\b${escapedWord}\\b`, 'i');
    return regex.test(message.content);
  });

  if (isBanned) {
    message.delete();
    message.reply('你的消息包含违禁词,请修改后发送!');
  }
});

client.login('你的机器人Token');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:03:21