You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:57:05