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

如何在discord.py的Cogs中为斜杠命令参数添加描述?

Cogs中用@app_commands.describe()报错?看这俩解决办法

为啥会报错?
在Cogs里用斜杠命令时,要么是装饰器顺序搞反了,要么是参数名没对应上,导致装饰器错误识别参数(比如把self当成命令参数处理),就会触发TypeError提示未知参数。

解决办法1:调整装饰器顺序

在Cogs里,必须把@app_commands.command()放在最上面,@app_commands.describe()紧贴函数定义,而且描述里的参数名要和函数里除了self、interaction之外的参数完全一致(大小写都不能错)。

示例代码:

import discord
from discord import app_commands
from discord.ext import commands

class TestCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    # 正确顺序:先command装饰器,再describe
    @app_commands.command(name="test_cmd", description="测试用的斜杠命令")
    @app_commands.describe(test_param="这是你要输入的测试参数")
    async def test_command(self, interaction: discord.Interaction, test_param: str):
        await interaction.response.send_message(f"你输入的参数是:{test_param}")

async def setup(bot: commands.Bot):
    await bot.add_cog(TestCog(bot))

解决办法2:直接给参数加描述

不想纠结装饰器顺序的话,直接在参数定义时用app_commands.Parameter()指定描述,这种方式更直观,也不容易出错。

示例代码:

import discord
from discord import app_commands
from discord.ext import commands

class TestCog(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @app_commands.command(name="test_cmd", description="测试用的斜杠命令")
    async def test_command(
        self, 
        interaction: discord.Interaction, 
        test_param: str = app_commands.Parameter(description="这是你要输入的测试参数")
    ):
        await interaction.response.send_message(f"你输入的参数是:{test_param}")

async def setup(bot: commands.Bot):
    await bot.add_cog(TestCog(bot))

额外注意点

  • 确保你的discord.py版本是v2.0及以上,旧版本对Cogs中斜杠命令的支持有问题
  • 描述里的参数名必须和函数参数名完全匹配,别打错字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:15:22