Discord.py开发可手动配置的anti-toxicity过滤器功能实现求助
实现Discord机器人可配置反不良信息功能的方案
核心实现思路
- 用JSON文件持久化存储每个服务器的独立配置,避免重启机器人后配置丢失
- 新增服务器配置校验逻辑,未配置、未开启过滤的服务器默认不触发拦截
- 新增管理员专属指令,支持手动开关功能、增删违禁词
具体代码实现
1. 配置文件读写逻辑
首先创建JSON配置文件的读写工具,用来存储各服务器的过滤开关、自定义违禁词列表:
import json import os # 配置文件存储路径 CONFIG_PATH = "guild_config.json" # 初始化配置文件,不存在则自动创建 if not os.path.exists(CONFIG_PATH): with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump({}, f, indent=2, ensure_ascii=False) # 读取配置 def load_config(): with open(CONFIG_PATH, "r", encoding="utf-8") as f: return json.load(f) # 保存配置 def save_config(config): with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False)
JSON配置文件的存储结构示例:
{ "1234567890": { "filter_enabled": true, "cuss_words": ["违禁词1", "违禁词2"] }, "0987654321": { "filter_enabled": false, "cuss_words": [] } }
键为对应服务器的ID,每个服务器独立存储配置,互不影响
2. 修改消息拦截逻辑
替换原有的全局违禁词检测逻辑,新增配置校验规则:
@client.event async def on_message(message): # 忽略机器人自身消息、私信消息 if message.author.bot or not message.guild: await client.process_commands(message) return guild_id = str(message.guild.id) config = load_config() # 服务器未配置、未开启过滤时直接跳过检测 if guild_id not in config or not config[guild_id]["filter_enabled"]: await client.process_commands(message) return # 仅匹配当前服务器配置的违禁词 for word in config[guild_id]["cuss_words"]: if word in message.content: await message.delete() await message.channel.send("Please don't be toxic!", delete_after=10) break await client.process_commands(message)
3. 实现配置操作指令
新增管理员专属指令,用来操作过滤功能配置:
# 开启过滤功能 @client.command() @commands.has_permissions(administrator=True) async def enable_filter(ctx): config = load_config() guild_id = str(ctx.guild.id) if guild_id not in config: config[guild_id] = {"filter_enabled": True, "cuss_words": []} else: config[guild_id]["filter_enabled"] = True save_config(config) await ctx.send("✅ 反不良信息过滤已开启", delete_after=5) # 关闭过滤功能 @client.command() @commands.has_permissions(administrator=True) async def disable_filter(ctx): config = load_config() guild_id = str(ctx.guild.id) if guild_id in config: config[guild_id]["filter_enabled"] = False save_config(config) await ctx.send("❌ 反不良信息过滤已关闭", delete_after=5) # 添加违禁词 @client.command() @commands.has_permissions(administrator=True) async def add_cuss(ctx, *, word): config = load_config() guild_id = str(ctx.guild.id) if guild_id not in config: config[guild_id] = {"filter_enabled": False, "cuss_words": []} if word not in config[guild_id]["cuss_words"]: config[guild_id]["cuss_words"].append(word) save_config(config) await ctx.send(f"✅ 已添加违禁词:{word}", delete_after=5) else: await ctx.send(f"⚠️ 该违禁词已存在", delete_after=5)
优化建议
- 大流量服务器可以把配置加载到内存缓存,不用每次触发消息都读盘,降低IO损耗
- 可以把违禁词匹配改成正则全词匹配,避免误杀包含违禁词的正常内容
- 可按需新增删除违禁词、查看当前服务器违禁词列表的配套指令
内容的提问来源于stack exchange,提问作者Pr0methium
相关产品推荐
相关产品推荐

