discord.py auto moderator违禁词过滤代码无法运行修复求助
问题修复方案
现有代码错误点
- 语法错误:
if word in message.content.lower()行末尾缺少英文冒号:,会直接触发语法报错无法启动 - 缺少必要依赖导入:代码中使用了
datetime模块但未导入,同时discord.py v2.x+需要显式声明消息内容意图,否则无法读取用户消息内容 - 未过滤机器人自身消息:会导致机器人发送的内容触发规则后出现无限循环执行的问题
- 缺少命令处理调用:未添加
await client.process_commands(message)会导致其余自定义指令完全失效 - 潜在异常未处理:若日志频道不存在、Muted角色不存在、机器人无对应操作权限时会直接抛出异常终止运行
修复前准备
先安装所需依赖:pip install discord.py
修复后完整代码
import discord import datetime from discord.ext import commands # 显式声明需要的意图,消息内容意图必须在Discord开发者后台机器人设置页手动开启 intents = discord.Intents.default() intents.message_content = True intents.members = True # 初始化客户端 client = commands.Bot(command_prefix='!', intents=intents) filtered_words = ["bad", "words", "here"] # 替换为你自己的过滤词列表 filtered_words_counter = {} LOG_CHANNEL_ID = 123456789 # 替换为你的日志频道数字ID MUTED_ROLE_NAME = "Muted" # 和服务器内的静音角色名保持一致 @client.event async def on_ready(): print(f'登录成功,当前身份为 {client.user}') @client.event async def on_message(message): # 跳过机器人自身发送的消息 if message.author.bot: return # 可选:跳过管理员消息,根据需求调整 if message.author.guild_permissions.administrator: await client.process_commands(message) return for word in filtered_words: if word in message.content.lower(): await message.delete() # 构造日志嵌入 embed = discord.Embed(color=0xff0000) embed.set_author(name="违规词触发") embed.add_field(name="用户名:", value=f"{message.author.mention}", inline=False) embed.add_field(name="触发违规词:", value=f"{word}", inline=False) embed.add_field(name="原消息内容:", value=f"{message.content}", inline=False) embed.set_footer(text=f'用户ID: {message.author.id}') embed.timestamp = datetime.datetime.utcnow() # 发送日志 log_channel = client.get_channel(LOG_CHANNEL_ID) if log_channel: await log_channel.send(embed=embed) # 更新违规计数 if not filtered_words_counter.get(message.author.id): filtered_words_counter[message.author.id] = 1 else: filtered_words_counter[message.author.id] += 1 # 触发静音逻辑 if filtered_words_counter[message.author.id] >= 3: muted_role = discord.utils.get(message.guild.roles, name=MUTED_ROLE_NAME) if muted_role: try: await message.author.add_roles(muted_role) await message.channel.send(f'{message.author.mention} 因多次触发违规词已被静音') filtered_words_counter[message.author.id] = 0 except discord.Forbidden: if log_channel: await log_channel.send(f'权限不足,无法为用户 {message.author.mention} 添加静音角色') # 必须保留该行,否则其余自定义指令会失效 await client.process_commands(message) # 启动机器人,替换为你自己的机器人Token,不要泄露给第三方 client.run("你的机器人Token")
额外注意事项
- 确保机器人在服务器内拥有
删除消息、发送消息、嵌入链接、管理角色权限,且机器人角色的排序高于Muted角色,否则无法正常添加静音角色 - 不要将包含Token的代码上传到公开代码仓库,建议使用环境变量存储敏感信息
内容的提问来源于stack exchange,提问作者Celavi
相关产品推荐
相关产品推荐

