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

如何在discord.py斜杠命令中添加必填文本参数与附件字段?

解决discord.py斜杠命令添加文本参数与必填附件的问题

一、添加文本参数字段

直接在命令函数的参数列表中声明参数类型(如str),配合@app_commands.describe可以给参数添加描述,让用户在Discord中看到参数说明。示例如下:

@tree.command(name="test", description="this is a test command")
@app_commands.describe(name="要打招呼的用户名")
async def first_command(interaction: discord.Interaction, name: str):
    await interaction.response.send_message(f"hello {name}", ephemeral=True)

也可以直接在参数上通过description参数指定说明,写法更紧凑:

@tree.command(name="test", description="this is a test command")
async def first_command(interaction: discord.Interaction, name: str = app_commands.Parameter(description="要打招呼的用户名")):
    await interaction.response.send_message(f"hello {name}", ephemeral=True)

二、添加必填附件字段

使用discord.Attachment作为参数类型,通过app_commands.Parameter(required=True)标记为必填项,同时可添加描述。获取附件后,你可以直接在回复中引用它,或者读取附件内容。完整示例:

import discord
from discord import app_commands

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(name="test", description="带文本参数和必填附件的测试命令")
@app_commands.describe(
    name="要打招呼的用户名",
    attachment="需要上传的必填附件"
)
async def first_command(
    interaction: discord.Interaction,
    name: str,
    attachment: discord.Attachment = app_commands.Parameter(required=True)
):
    # 示例:回复时带上用户名和附件
    await interaction.response.send_message(
        f"hello {name}, 你上传的附件:",
        files=[await attachment.to_file()],
        ephemeral=True
    )

@client.event
async def on_ready():
    await tree.sync()  # 同步命令到Discord服务器
    print(f"Logged in as {client.user}")

client.run("你的机器人令牌")

关键说明

  1. 必须确保在机器人启动时调用await tree.sync(),否则新添加的参数不会同步到Discord,导致命令无法正常显示参数。
  2. attachment.to_file()会将Discord上的附件转换为可发送的discord.File对象,方便在回复中复用。
  3. 如果参数标记为required=True,用户在执行命令时必须上传附件,否则无法发送命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:01:37