discord.py的Automod邀请链接检测功能运行报错,寻求解决方案
问题排查与修复方案
核心报错原因
discord.py框架的on_message事件仅接收1个message参数,你额外定义了不需要的ctx参数,导致参数数量不匹配,触发你看到的missing 1 required positional argument: 'message'报错。
其他存在的逻辑错误
- 缩进错误:当前禁言、发送日志的逻辑没有放在邀请链接检测的if判断分支内,会导致所有发消息的用户无论是否违规都会被禁言
- 上下文引用错误:你错误使用了不存在的
ctx对象调用消息属性,后续直接用message参数即可 - 正则匹配逻辑缺陷:
match方法仅匹配字符串开头,若用户消息开头带其他内容就会绕过检测,替换为search更合理 - 边界情况缺失:没有过滤机器人自身发送的消息,也没有处理非服务器私信场景下无guild属性的异常
- 依赖缺失:使用
re模块前需要先导入 - 权限逻辑缺失:没有排除管理员/机器人自身的权限豁免,可能会误禁管理人员
- 旧版API使用:
avatar_url在新版discord.py中已经弃用,需要替换为display_avatar.url
修复后可运行代码
# 顶部先导入需要的模块 import re import discord from discord.ext import commands # 注意要开启消息内容意图,discord.py v2.x必须在开发者后台和代码中同时配置 intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix='!', intents=intents) red = discord.Color.red() # 你代码中用到的red变量需要提前定义 @bot.event async def on_message(message): # 先过滤机器人自身消息、私信消息 if message.author.bot or not message.guild: await bot.process_commands(message) return # 可选:添加管理员豁免规则,不需要可以删除 if message.author.guild_permissions.administrator: await bot.process_commands(message) return discordInviteFilter = re.compile(r"(...)?(?:https?://)?discord(?:(?:app)?\.com/invite|\.gg)/?[a-zA-Z0-9]+/?") guild = message.guild mutedRole = discord.utils.get(guild.roles, name="🔇 | Muted") log_channel = discord.utils.get(guild.channels, name="📝║logs") # 检测到邀请链接时才执行处罚逻辑 if discordInviteFilter.search(message.content): # 删除违规消息 await message.delete() # 发送公屏提示 await message.channel.send(f'{message.author.mention}, 本服务器不允许发送邀请链接,请重新阅读规则') # 赋予禁言角色 await message.author.add_roles(mutedRole) # 构造日志Embed embed1=discord.Embed(title="用户已被禁言", colour=red) embed1.set_thumbnail(url=message.author.display_avatar.url) embed1.add_field(name="违规原因", value="发送Discord邀请链接", inline=False) embed1.add_field(name="违规用户", value=f"{message.author.mention}(用户ID:{message.author.id})", inline=False) # 发送日志到指定频道 if log_channel: await log_channel.send(embed=embed1) # 保留正常命令处理逻辑 await bot.process_commands(message)
内容的提问来源于stack exchange,提问作者B1ueDev
相关产品推荐
相关产品推荐

