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

Discord.py中/marry命令ctx参数异常及报错问题求助

问题解决:Discord机器人slash命令中ctx为Interaction对象的问题

原因分析

你遇到的是正常的设计差异:

  • 使用client.tree.command()定义的是Slash命令(应用命令),这类命令的回调函数接收的参数是discord.Interaction对象,而非传统前缀命令(@client.command()定义)使用的commands.Context。
  • contextlib=True是前缀命令装饰器的专属参数,用于自动注入上下文,但Slash命令的装饰器CommandTree.command()并不支持该参数,因此会抛出TypeError。

解决方案

方案1:直接使用Interaction对象

Interaction对象包含了你需要的绝大多数上下文信息(用户、服务器、频道等),可以直接访问:

@client.tree.command(name="marry", description="结婚命令")
async def marry(interaction: discord.Interaction, partner: discord.User):
    # 直接调用interaction的属性
    await interaction.response.send_message(f"{interaction.user.mention} 和 {partner.mention} 结婚啦!")
    # 获取服务器信息示例
    if interaction.guild:
        print(f"命令在服务器 {interaction.guild.name} 执行")

方案2:转换为commands.Context(若必须使用)

如果你确实需要commands.Context对象,可以通过client.get_context()方法将Interaction转换为Context:

@client.tree.command(name="marry", description="结婚命令")
async def marry(interaction: discord.Interaction, partner: discord.User):
    # 转换为Context对象
    ctx = await client.get_context(interaction)
    # 注意:需先回应交互避免超时
    await interaction.response.defer()
    # 现在可以使用ctx的方法
    await ctx.send(f"{ctx.author.mention} 和 {partner.mention} 结婚啦!")

提示:转换后的Context无法完全支持前缀命令的所有特性,比如ctx.prefix会是空字符串(因为Slash命令没有前缀)。

额外说明

discord.py中前缀命令和Slash命令是两套独立系统:

  • 前缀命令用@client.command()定义,接收commands.Context
  • Slash命令用@client.tree.command()定义,接收discord.Interaction
    可根据需求选择对应的命令类型。

内容的提问来源于stack exchange,提问作者RayanUtka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 06:31:10