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

如何为discord.py斜杠命令的选项添加描述?

给Discord.py斜杠命令的选项添加描述

我通过python3 -m pip install -U git+https://github.com/Rapptz/discord.py安装了discord.py,现有main.py代码如下(/test斜杠命令可正常运行,但希望给其中的text选项添加描述“Text to repeat”):

guild_id = 964345157480747029

import discord
from discord import app_commands

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents = discord.Intents.default())
        self.synced = False # 避免Bot重复同步命令

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced: # 检查斜杠命令是否已同步
            await tree.sync(guild = discord.Object(id=guild_id)) # 服务器级同步,留空则为全局(全局同步需1-24小时生效)
            self.synced = True
        print(f"We have logged in as {self.user}.")

client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(guild = discord.Object(id=guild_id), name = 'test', description='A test slash command') # 服务器专属斜杠命令
async def slash2(interaction: discord.Interaction, text: str):
    await interaction.response.send_message(f'You said "{text}"!')

client.run('token')

解决方法

给斜杠命令的参数添加描述有两种常用方式:

方式一:使用@app_commands.describe装饰器

在命令函数上方添加该装饰器,直接指定参数对应的描述:

@tree.command(guild = discord.Object(id=guild_id), name = 'test', description='A test slash command')
@app_commands.describe(text="Text to repeat")  # 为text参数添加描述
async def slash2(interaction: discord.Interaction, text: str):
    await interaction.response.send_message(f'You said "{text}"!')

方式二:使用app_commands.Parameter注解参数

直接在参数的类型注解中嵌入描述信息:

@tree.command(guild = discord.Object(id=guild_id), name = 'test', description='A test slash command')
async def slash2(interaction: discord.Interaction, text: str = app_commands.Parameter(description="Text to repeat")):
    await interaction.response.send_message(f'You said "{text}"!')

修改完成后重启Bot,服务器级命令同步后几秒内即可生效,此时使用/test命令时,text选项就会显示你设置的描述内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:15:42