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

如何为Discord.py的字符串参数设置最小与最大长度?

如何为discord.py的app_command参数设置长度限制?

我编写了如下代码:

@app_commands.Argument(
  username={
    "min_length": 3,
    "max_length": 22
  }
)
async def inv(interaction:discord.Interaction, username:str):
  # code

运行时出现错误:

Traceback (most recent call last):
  File "main.py", line 69, in <module>
    @app_commands.Argument(
TypeError: __init__() got an unexpected keyword argument 'username'

解决方案

你错误使用了@app_commands.Argument的传参方式,以下是两种正确实现参数长度限制的方法:

方法1:为单个参数单独绑定装饰器

@app_commands.command()
@app_commands.Argument("username", min_length=3, max_length=22)
async def inv(interaction: discord.Interaction, username: str):
    # 你的业务代码
    await interaction.response.send_message(f"处理用户:{username}")

注意:@app_commands.Argument的第一个参数是目标参数的名称,后续直接传入min_length、max_length这类约束参数即可,不需要嵌套字典。

方法2:使用Annotated类型提示(官方推荐)

从discord.py 2.0版本开始,更推荐通过Annotated将参数约束直接嵌入类型标注,代码更简洁直观:

from typing import Annotated

@app_commands.command()
async def inv(
    interaction: discord.Interaction,
    username: Annotated[str, app_commands.Argument(min_length=3, max_length=22)]
):
    # 你的业务代码
    await interaction.response.send_message(f"处理用户:{username}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:30:59