
当开发者尝试使用@app_commands.required(param=false)来标记一个斜杠命令参数为可选时,会遇到attributeerror: module 'discord.app_commands' has no attribute 'required'。这是因为discord.app_commands模块中并不存在这样一个装饰器来控制参数的必需性。discord.py处理可选参数的方式更符合python的惯例,即通过类型提示或默认值来表达。
这是定义可选参数的推荐方法之一,它清晰地表明了参数可以接受指定类型的值,也可以接受None。
核心概念:typing.Optional[T]实际上是Union[T, None]的简写,表示该参数可以是类型T,也可以是None。当Discord客户端看到这种类型提示时,它会自动将该参数标记为可选。
示例代码:
import discord
from discord import app_commands
import typing
# 假设 client 是你的 discord.Client 或 commands.Bot 实例
# client = discord.Client(intents=discord.Intents.default())
# tree = app_commands.CommandTree(client)
@app_commands.describe(
choice1="你的第一个选择?",
choice2="你的第二个选择?",
choice3="你的第三个选择? (可选)",
choice4="你的第四个选择?",
choice5="你的第五个选择? (可选)"
)
@app_commands.command(name='decide_optional_type', description='Bing将帮助你做出决定')
async def decide_optional_type(
interaction: discord.Interaction,
choice1: str,
choice2: str,
choice3: typing.Optional[str], # 使用 typing.Optional 标记为可选
choice4: str,
choice5: typing.Optional[str] # 再次使用 typing.Optional
):
print(f"选择1: {choice1}, 选择2: {choice2}, 选择3: {choice3}, 选择4: {choice4}, 选择5: {choice5}")
await interaction.response.send_message(
f"你的选择是:{choice1}, {choice2}, {choice3 if choice3 else '未提供'}, {choice4}, {choice5 if choice5 else '未提供'}"
)
# 注册命令(如果使用 commands.Bot,则不需要手动添加)
# tree.add_command(decide_optional_type)
# 在机器人启动后同步命令
# @client.event
# async def on_ready():
# print(f'Logged in as {client.user}')
# await tree.sync()注意事项:
这是Python中定义可选参数的另一种标准方式,同样适用于Discord.py的斜杠命令。
核心概念: 当一个函数参数被赋予了默认值(例如param: str = None),Python会自动将其视为可选参数。Discord客户端在解析命令时,也会识别出这种模式并将其标记为可选。
示例代码:
import discord
from discord import app_commands
# 假设 client 是你的 discord.Client 或 commands.Bot 实例
# client = discord.Client(intents=discord.Intents.default())
# tree = app_commands.CommandTree(client)
@app_commands.describe(
choice1="你的第一个选择?",
choice2="你的第二个选择?",
choice3="你的第三个选择? (可选)",
choice4="你的第四个选择?",
choice5="你的第五个选择? (可选)"
)
@app_commands.command(name='decide_default_none', description='Bing将帮助你做出决定')
async def decide_default_none(
interaction: discord.Interaction,
choice1: str,
choice2: str,
choice4: str, # 注意:所有必填参数必须在可选参数之前
choice5: str = None, # 设置默认值为 None 标记为可选
choice3: str = None # 设置默认值为 None 标记为可选
):
print(f"选择1: {choice1}, 选择2: {choice2}, 选择3: {choice3}, 选择4: {choice4}, 选择5: {choice5}")
await interaction.response.send_message(
f"你的选择是:{choice1}, {choice2}, {choice3 if choice3 else '未提供'}, {choice4}, {choice5 if choice5 else '未提供'}"
)
# 注册命令
# tree.add_command(decide_default_none)注意事项:
在Discord.py中,定义斜杠命令的可选参数并非通过@app_commands.required装饰器,而是遵循Python本身的参数定义规则:
两种方法都能让Discord客户端正确识别并显示为可选参数,并避免AttributeError。开发者可以根据个人偏好和团队规范选择其中一种。务必在处理这些可选参数时,考虑到它们可能为None的情况,以确保代码的健壮性。
以上就是Discord.py app_commands可选参数的正确定义方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号