discord.py开发白名单机器人时如何判断调用命令用户是否持有指定角色
问题核心原因
你代码里传递给discord.utils.get的角色ID是字符串类型,但discord.py中所有ID(角色、用户、服务器、频道等)均为整数类型,因此discord.utils.get永远无法匹配到正确的角色,返回值为None,判断条件自然永远不成立。
其他需排查的常见问题
- 确保你开启了必要的Intents:代码中初始化Bot时需要开启
guilds和members权限,同时需要在Discord开发者后台的Bot设置页打开对应权限开关 - 确认你复制的角色ID正确,没有多输/漏输数字
- 确认机器人的角色等级高于你要校验的白名单管理角色等级,否则机器人无法读取该角色的归属信息
修正后代码示例
@bot.command() async def idk(ctx): # 注意ID去掉引号,改为整数类型 role = discord.utils.get(ctx.guild.roles, id=892437125293813790) # 增加角色存在性判断,避免服务器删除该角色后代码报错 if not role: await ctx.send("未找到对应管理角色") return if role in ctx.author.roles: print('y') await ctx.send("权限校验通过") else: print(ctx.author.roles) print('n') await ctx.send("你没有白名单管理权限")
如果你不需要自定义复杂的权限判断逻辑,也可以直接用discord.py内置的权限校验装饰器,代码更简洁:
from discord.ext import commands @bot.command() # 直接传入整数类型的角色ID即可,也可传入角色名称字符串 @commands.has_role(892437125293813790) async def idk(ctx): print('y') await ctx.send("权限校验通过") # 无权限时的错误处理 @idk.error async def idk_error(ctx, error): if isinstance(error, commands.MissingRole): print('n') await ctx.send("你没有白名单管理权限")
内容的提问来源于stack exchange,提问作者user15430859
相关产品推荐
相关产品推荐

