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

discord.py中command.before_invoke无法获取命令参数值问题

解决discord.py hybrid_command中@before_invoke无法获取命令参数的问题

问题现象

使用commands.hybrid_command定义setcash命令,通过前缀调用!setcash 10时:

  • 原命令函数内print(amount)输出实际传入的10
  • 但通过@_set_cash.before_invoke装饰的前置函数中,print(amount)只能输出默认值0;若不设置默认值则直接提示参数缺失

原命令代码:

@commands.hybrid_command(name='setcash', with_app_command=True)
@commands.cooldown(2, 5, commands.BucketType.user)
@track_speed
async def _set_cash(self, ctx, amount: int = 0):
    print(amount)
# 调用!setcash 10时输出:10

前置函数错误写法:

@_set_cash.before_invoke
async def _before_invoke_set_cash(self, ctx, amount:int=0):
    print(amount)
# 调用!setcash 10时输出:0

问题原因

discord.py的before_invoke装饰器函数不会自动接收命令参数,它的参数列表仅支持self和ctx(类命令场景)。额外定义的参数不会被框架自动填充,只能使用你设置的默认值,无默认值则触发参数缺失错误。

解决方案

要获取命令参数,需从ctx对象的args或kwargs属性中提取:

方法1:通过ctx.args获取位置参数

适用于前缀调用的位置参数场景,类命令中ctx.args前两个元素为self和ctx,后续为命令实际参数:

@_set_cash.before_invoke
async def _before_invoke_set_cash(self, ctx):
    # 对应_set_cash的amount参数位置
    amount = ctx.args[2]
    print(amount)
# 调用!setcash 10时输出:10

方法2:通过ctx.kwargs获取命名参数

通用型写法,同时支持前缀调用和应用命令(Slash Command)调用,推荐使用:

@_set_cash.before_invoke
async def _before_invoke_set_cash(self, ctx):
    # 通过参数名直接获取,可设置默认值避免异常
    amount = ctx.kwargs.get('amount', 0)
    print(amount)
# 调用!setcash 10或通过Slash Command传入10时,均输出:10

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:14