Discord Python Bot:按角色限制命令权限的代码异常问题
问题原因
你代码里的'Premium' in message.author.roles判断逻辑错误,因为message.author.roles返回的是Discord Role对象的列表,不是字符串列表。直接用字符串'Premium'和Role对象做存在性比较,永远会返回False,所以才会触发else分支。
修复方案
可以用以下几种方式修正角色判断逻辑:
方法1:遍历角色列表匹配名称
import os import discord intents = discord.Intents.all() client = discord.Client(command_prefix='.',intents=intents) @client.event async def on_message(message): if message.author == client.user: return # 检查用户是否拥有Premium角色 has_premium = any(role.name == 'Premium' for role in message.author.roles) if message.content.startswith('.start') and has_premium: await message.channel.send("Server Is Starting") else: await message.channel.send("You need a Premium role to use this command") client.run('my token')
方法2:通过角色ID判断(更可靠)
如果担心角色名称被修改导致判断失效,建议用角色ID来判断(角色ID是唯一且不会变的):
import os import discord intents = discord.Intents.all() client = discord.Client(command_prefix='.',intents=intents) # 替换成你服务器里Premium角色的实际ID PREMIUM_ROLE_ID = 123456789012345678 @client.event async def on_message(message): if message.author == client.user: return # 检查用户是否拥有指定ID的角色 has_premium = any(role.id == PREMIUM_ROLE_ID for role in message.author.roles) if message.content.startswith('.start') and has_premium: await message.channel.send("Server Is Starting") else: await message.channel.send("You need a Premium role to use this command") client.run('my token')
额外提示
你的else提示文案写错了,应该是提示需要Premium角色而不是MOD角色,记得修正。
内容的提问来源于stack exchange,提问作者MedCode
相关产品推荐
相关产品推荐

