Discord Python Bot角色权限验证异常:无响应问题求助
Discord Bot 基于角色的命令无响应问题修复
问题场景
尝试让Discord Python Bot仅对拥有「Streamer」角色的用户响应特定命令,但Bot完全无响应,VS Code未检测到代码错误。预期效果:
- 拥有「Streamer」角色的用户发送
syd.hello时,Bot回复「Hello Syd!」 - 无该角色的用户发送该命令时,Bot回复「Hi」
原始代码:
import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): prefix = "syd." if message.content.startswith(prefix): command = message.content[len(prefix):] #get commands isAdmin = [role.name == "Streamer" for role in message.author.roles][0] if command == "hello" and isAdmin: await message.channel.send("Hello Syd!") else: discord.utils.get(discord.guild.roles, name='Streamer') await message.channel.send("Hi") intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('MTE0MDgwOTg2ODM1ODQ1MTMyMA.GcpAIl.a-b5uNVIce_o3ML2BP3Bgd9vNpUPLcviUZJoAo')
问题分析与修复
1. 角色判断逻辑错误
原始代码中[role.name == "Streamer" for role in message.author.roles][0]仅取用户第一个角色的判断结果,若「Streamer」不是用户的第一个角色,即使拥有该角色也会返回False,导致命令无法触发。
正确的判断方式是用any()检查用户角色列表中是否存在「Streamer」角色:
is_admin = any(role.name == "Streamer" for role in message.author.roles)
2. 未排除Bot自身消息
如果Bot自己发送了带前缀的消息,会触发on_message事件导致循环,需在函数开头添加判断跳过自身消息:
if message.author == self.user: return
3. 无效代码调用
else块中的discord.utils.get(discord.guild.roles, name='Streamer')毫无意义,discord.guild是类而非具体服务器对象,该调用无法获取角色,直接删除即可。
修正后的完整代码
import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as {self.user}!') async def on_message(self, message): # 跳过Bot自身发送的消息 if message.author == self.user: return prefix = "syd." if message.content.startswith(prefix): command = message.content[len(prefix):] # 正确检查用户是否拥有「Streamer」角色 is_admin = any(role.name == "Streamer" for role in message.author.roles) if command == "hello" and is_admin: await message.channel.send("Hello Syd!") else: await message.channel.send("Hi") intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('你的Bot令牌')
额外检查项
- 确保Bot已启用
message_content意图(代码中已设置,但需在Discord开发者后台的Bot页面开启该意图) - 确认Bot在服务器中有发送消息的权限
- 检查「Streamer」角色名称是否完全匹配(大小写、空格均需一致)
内容的提问来源于stack exchange,提问作者Syd
相关产品推荐
相关产品推荐

