discord.py如何检测message.author持有指定角色 避免AttributeError报错
你当前代码报错的原因是discord.utils.get()在目标用户没有找到对应名称的角色时会返回None,直接访问None的name属性就会触发AttributeError,你原代码中判断name == "Admin"属于冗余逻辑,因为get方法已经通过name参数过滤过角色了。
discord.py有原生的角色权限校验能力,根据你的开发场景可以选择以下两种实现方案:
方案1:使用commands框架原生装饰器(推荐)
如果你用discord.ext.commands框架开发指令,直接用官方原生提供的角色校验装饰器即可,不需要手动写判断逻辑:
from discord.ext import commands # 单角色校验:仅持有Admin角色的用户可调用 @bot.command() @commands.has_role("Admin") async def test_command(ctx): # 业务逻辑写在这里 await ctx.send("命令执行成功") # 多角色校验:持有Admin/Mod任意一个角色即可调用 @bot.command() @commands.has_any_role("Admin", "Mod") async def test_command2(ctx): await ctx.send("命令执行成功")
如果用户没有对应角色,会触发commands.MissingRole/commands.MissingAnyRole异常,你可以通过全局异常监听统一处理无权限提示,不需要每个命令单独捕获。
方案2:手动处理on_message事件的校验逻辑
如果你没有用commands框架,而是在on_message事件里手动处理指令,直接调整判断逻辑,避免访问None的属性即可:
# 单角色校验 admin_role = discord.utils.get(message.author.roles, name="Admin") if admin_role: # 业务逻辑写在这里 # 多角色校验 allowed_roles = ["Admin", "Mod"] has_perm = any(discord.utils.get(message.author.roles, name=role) for role in allowed_roles) if has_perm: # 业务逻辑写在这里
内容的提问来源于stack exchange,提问作者Xantium
相关产品推荐
相关产品推荐

