
本文详解如何使用 `commands.cog.listener()` 正确检测用户消息中是否包含服务器配置的禁用词汇,并精准触发删除与提醒,避免误删、漏检及性能瓶颈。
在 Discord 机器人开发中,通过 @commands.Cog.listener() 监听 on_message 事件实现敏感词过滤是常见需求。但许多开发者会陷入逻辑误区——例如将禁用词列表错误地转为字符串再逐字符遍历(如原代码中 ' '.join(x for x in xxx2)),导致语义完全错乱:本意是匹配完整单词,结果却变成了单字符模糊匹配(如 "noob" 被拆成 'n','o','o','b',只要禁用词列表含任意单字母就误触发)。
✅ 正确做法:基于单词级精确匹配
假设 GetWF(guild_id) 返回的是形如 ['cat', 'dog', 'mouse'] 的字符串列表(即 list[str]),应直接利用 Python 的成员判断能力,结合消息内容分词处理:
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
bwl = GetWF(message.guild.id) # ✅ 应确保此函数返回 list[str] 或 None
if not bwl: # 更简洁的空值判断
print("No banned words found for this guild")
await self.bot.process_commands(message)
return
# ? 核心:检查消息中是否有任意一个单词(全词、区分大小写)存在于禁用词列表
words_in_msg = message.content.split()
if any(word in bwl for word in words_in_msg):
try:
await message.delete()
await message.channel.send(f"`HEY {message.author.name}!\nThat word is banned!`")
except discord.Forbidden:
print(f"Missing permissions to delete message in #{message.channel}")
except Exception as e:
print(f"Unexpected error during message handling: {e}")
await self.bot.process_commands(message) # ✅ 注意:此处应为 self.bot,非全局 client⚠️ 关键修正点:绝不将 bwl 转为字符串再 split() —— 这会破坏原始语义;使用 message.content.split() 获取单词列表,再用 any(word in bwl ...) 做 O(1) 平均查找(若 bwl 改为 set,性能更优);移除冗余的 return 和 else 分支,避免短路中断正常流程。
? 进阶优化建议
1. 提升匹配鲁棒性(推荐)
# 预处理:统一转小写 + 去除标点(基础版)
clean_bwl = {word.strip('.,!?;:"()[]{}').lower() for word in bwl}
clean_content = [w.strip('.,!?;:"()[]{}').lower() for w in message.content.split()]
if any(word in clean_bwl for word in clean_content):
# ...2. 避免高频重复查询(性能关键!)
GetWF(guild_id) 若涉及数据库/HTTP 请求,绝不可在每次 on_message 中调用。应在 Cog 初始化时缓存,或使用 LRU 缓存:
from functools import lru_cache
@lru_cache(maxsize=128)
def GetWF_cached(guild_id: int) -> list[str]:
return GetWF(guild_id)
# 在 listener 中调用:
bwl = GetWF_cached(message.guild.id)或更推荐:在 __init__ 中加载全部服务器配置到内存字典中,实现 O(1) 查询。
3. 权限与异常处理
- 检查机器人是否拥有 Manage Messages 权限;
- 对 message.delete() 和 send() 单独捕获 discord.Forbidden,便于调试;
- 切勿静默吞掉所有异常(如原代码 except Exception: return),这会使问题难以定位。
✅ 总结
要实现“仅当消息中出现完整禁用词时才删除”,核心是:
✅ 将禁用词保持为 list 或 set;
✅ 将消息按空格分词后逐项比对;
✅ 避免字符串拼接、字符级遍历等语义失真操作;
✅ 预加载配置、合理缓存、精准异常处理。
遵循以上原则,即可构建稳定、高效、可维护的敏感词过滤系统。










