Discord机器人反脏话系统在消息编辑后失效的修复方法
编辑消息脏话检测漏洞修复方案
问题根源
现有检测逻辑仅绑定on_message事件,该事件仅在用户首次发送消息时触发,完全无法捕获消息编辑后的内容变更,因此用户事后在原消息里追加脏话时,bot不会触发任何检测流程。
同时原代码存在两个附带逻辑bug:
- 违规检测分支内的
await client.process_commands(message)写在return语句之后,属于永远不会执行的无效代码 - 脏话检测、告警发送逻辑完全内嵌在事件函数中,重复代码冗余度极高
修复步骤
- 将核心的脏话检测、违规处理逻辑抽成独立的通用函数,供不同事件复用
- 新增
on_message_edit事件监听,捕获消息编辑操作,对编辑后的新内容执行完全一致的脏话检测 - 修正原代码的无效代码位置,保证正常消息的指令处理逻辑不会失效
修正后完整可运行代码
# 启动时提前加载违禁词列表为内存集合,避免每次检测都读取文件,提升运行效率 with open("badwords.txt", "r", encoding="utf-8") as f: BADWORDS = set(line.strip().lower() for line in f if line.strip()) async def check_and_handle_profanity(message): # 通用检测逻辑:传入待检测的消息对象,命中违禁词时返回True,否则返回False if message.author.bot: return False content = message.content.lower() matched_badword = None for badword in BADWORDS: if badword in content: matched_badword = badword break if not matched_badword: return False # 命中违禁词后执行删除、告警流程 await message.delete() warn_msg = f"Hey {message.author.mention}! Don't say that!" await message.channel.send(warn_msg, delete_after=5.0) print(f"{message.author.name} tried saying: {matched_badword}") log_channel = client.get_channel(836232733126426666) embed = discord.Embed(title="Someone tried to swear!", colour=0x2D2D2D) embed.add_field(name="Person who tried to swear:", value=f"{message.author.name}", inline=False) embed.add_field(name="What they tried to say:", value=f"{matched_badword}", inline=False) embed.add_field(name="Channel they tried to swear in:", value=f"<#{message.channel.id}>", inline=False) await log_channel.send(embed=embed) return True @client.event async def on_message(message): if message.author.bot: return # 优先执行脏话检测,命中违规直接返回,不需要处理后续逻辑 if await check_and_handle_profanity(message): return # 保留原有的自定义触发回复逻辑 if message.content.startswith('Jason derulo'): await message.channel.send('Wiggle wiggle wiggle') if message.content.startswith('fast'): await message.channel.send('She a runner she a track star') # 正常消息走完所有逻辑后,必须调用process_commands,否则所有前缀指令会失效 await client.process_commands(message) # 新增消息编辑监听事件,解决编辑后漏检问题 @client.event async def on_message_edit(before, after): # 直接对编辑后的新消息内容执行检测即可 await check_and_handle_profanity(after)
运行注意事项
- 如果需要追踪用户编辑前后的内容差异(比如原消息是正常内容,编辑后加了脏话),可以在
on_message_edit函数中把before.content和after.content的对比结果追加到告警embed里,方便后续审计 - 如果发现编辑消息事件没有触发,需要检查Discord开发者平台的机器人配置,是否开启了
Message Content Intent权限,否则bot无法获取消息内容相关的事件回调 - 目前的匹配逻辑是简单子串匹配,如果需要规避用户用拆字、形近字绕检的问题,可以后续在检测函数里补充正则规则或自定义匹配逻辑
内容的提问来源于stack exchange,提问作者Ender 2K89
相关产品推荐
相关产品推荐

