如何在Pycord/discord.py中通过ctx获取斜杠命令执行者的角色?
解决方案
在Pycord 2.4.1(兼容discord.py)中,斜杠命令的ApplicationContext(即代码里的ctx)自带member属性,该属性直接指向执行命令的服务器成员对象,无需额外调用user.Member或其他方法。你可以通过ctx.member.roles直接获取角色列表,再格式化为易读字符串即可。
修改后的完整代码如下:
from discord.commands import slash_command from discord.ext import commands class Cog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): print("Cog connected.") @slash_command(guild_ids=[12345], name='test') async def test(self, ctx): # 通过ctx.member直接获取角色列表,提取角色名称转为字符串 role_names = ', '.join([role.name for role in ctx.member.roles]) await ctx.respond(f"Your roles are {role_names}") def setup(bot): bot.add_cog(Cog(bot))
说明
ctx.member:斜杠命令上下文专属的成员对象,仅在服务器内执行命令时有效(你的代码已指定guild_ids,完全适配该场景)。ctx.member.roles返回包含所有角色的列表,通过列表推导式提取每个角色的name属性,再用join拼接成逗号分隔的字符串,便于输出展示。
内容的提问来源于stack exchange,提问作者syrok
相关产品推荐
相关产品推荐

