如何基于nextcord(Python)实现词过滤功能?
嘿,我来帮你搞定Nextcord里的词过滤功能!其实这个功能实现起来并不复杂,分几个核心步骤就能落地,我给你一步步拆解清楚:
核心思路概述
简单来说,词过滤的核心逻辑就是:监听服务器内的所有消息 → 检查消息内容是否包含敏感词 → 对违规消息进行处理(删除、警告、记录日志等)。Nextcord提供了消息事件的监听接口,刚好能完美适配这个逻辑。
具体实现步骤
1. 准备敏感词库
首先你需要定义要过滤的敏感词,推荐用集合来存储(因为集合的in操作比列表快很多,敏感词多的时候优势明显):
bad_words = {"垃圾", "傻逼", "脏话示例1", "脏话示例2"}
如果不想硬编码在代码里,也可以从外部文件读取(比如bad_words.txt,每行一个敏感词),这样更新词库不用改代码:
with open("bad_words.txt", "r", encoding="utf-8") as f: bad_words = set(line.strip() for line in f if line.strip())
2. 开启消息内容权限
要读取消息内容,必须在Discord开发者后台开启Message Content Intent,同时在代码里声明这个权限:
intents = nextcord.Intents.default() intents.message_content = True # 这行必须加,不然读不到消息内容 bot = commands.Bot(command_prefix="!", intents=intents)
3. 监听消息事件并检查敏感词
用on_message事件监听所有消息,然后加入过滤逻辑。这里要注意几个细节:
- 忽略机器人自己的消息,避免循环处理
- 忽略管理员的消息,避免误拦操作指令
- 可以用正则表达式实现精确匹配,避免误判(比如不想把“小笨蛋”当成“笨蛋”违规)
完整的基础示例代码:
import nextcord from nextcord.ext import commands import re intents = nextcord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) # 初始化敏感词和正则匹配规则 bad_words = {"垃圾", "傻逼", "脏话示例"} # 编译正则,用\b匹配单词边界,忽略大小写 pattern = re.compile(r'\b(' + '|'.join(re.escape(word) for word in bad_words) + r')\b', re.IGNORECASE) @bot.event async def on_ready(): print(f"机器人已登录:{bot.user}") @bot.event async def on_message(message): # 跳过机器人消息 if message.author.bot: return # 跳过管理员消息 if message.author.guild_permissions.administrator: await bot.process_commands(message) # 别忘了处理命令,不然机器人的命令会失效 return # 检查是否包含敏感词 if pattern.search(message.content): # 删除违规消息 await message.delete() # 发送临时警告(5秒后自动删除) await message.channel.send(f"{message.author.mention} 请不要发送违规内容哦!", delete_after=5) # 可选:记录违规日志到指定频道 log_channel = bot.get_channel(1234567890) # 替换成你的日志频道ID if log_channel: await log_channel.send(f"⚠️ 违规提醒:{message.author.mention} ({message.author.id}) 在 {message.channel.mention} 发送了敏感内容:\n{message.content}") # 必须调用这行,否则机器人的命令无法被处理 await bot.process_commands(message) bot.run("你的机器人令牌")
进阶优化建议
如果想让功能更完善,可以考虑这些点:
- 支持多词库:比如区分脏话、广告、政治敏感词等不同类别,分别处理
- 模糊匹配:如果需要匹配变体(比如“傻B”“sB”这种同音字/大小写变体),可以用正则的字符集或者替换规则
- 用户惩罚机制:比如累计违规次数后自动禁言,需要配合数据库记录用户违规次数
- 白名单设置:允许某些频道或用户不受过滤规则限制
用Cog模块化实现(推荐)
如果你的机器人功能较多,建议把词过滤做成单独的Cog,方便维护:
import nextcord from nextcord.ext import commands import re class WordFilter(commands.Cog): def __init__(self, bot): self.bot = bot self.bad_words = {"垃圾", "傻逼", "脏话示例"} self.pattern = re.compile(r'\b(' + '|'.join(re.escape(word) for word in self.bad_words) + r')\b', re.IGNORECASE) self.log_channel_id = 1234567890 # 日志频道ID @commands.Cog.listener() async def on_message(self, message): if message.author.bot or message.author.guild_permissions.administrator: return if self.pattern.search(message.content): await message.delete() await message.channel.send(f"{message.author.mention} 请不要发送违规内容!", delete_after=5) log_channel = self.bot.get_channel(self.log_channel_id) if log_channel: await log_channel.send(f"⚠️ {message.author.mention} ({message.author.id}) 在 {message.channel.mention} 发送了敏感内容:\n{message.content}") def setup(bot): bot.add_cog(WordFilter(bot))
内容的提问来源于stack exchange,提问作者Reflex
相关产品推荐
相关产品推荐

