
在 Discord.py 中开发斜杠命令时,开发者可能希望某些参数是可选的,即用户在调用命令时可以选择不提供这些参数。然而,一些开发者可能会尝试使用类似 @app_commands.required(param_name=False) 这样的装饰器来标记参数为可选。这会导致一个 AttributeError,因为 discord.app_commands 模块并没有名为 required 的属性或装饰器。
例如,以下代码片段展示了导致错误的常见尝试:
import discord
from discord import app_commands
# 假设 bot 是你的 discord.ext.commands.Bot 或 discord.Client 实例
# bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())
# 或者
# bot = discord.Client(intents=discord.Intents.default())
# tree = app_commands.CommandTree(bot)
# 错误示例:试图使用不存在的 @app_commands.required
@bot.tree.command(name='decide', description='帮助你做出决定')
@app_commands.describe(choice1="你的第一个选择")
@app_commands.describe(choice2="你的第二个选择")
@app_commands.describe(choice3="你的第三个选择")
# @app_commands.required(choice3=False) # 这一行会导致 AttributeError
async def decide(interaction: discord.Interaction, choice1: str, choice2: str, choice3: str):
await interaction.response.send_message(f"你选择了:{choice1}, {choice2}, {choice3}")
# 当执行上述代码时,会抛出以下错误:
# AttributeError: module 'discord.app_commands' has no attribute 'required'Discord.py 的 app_commands 模块通过检查命令函数参数的类型提示来确定其可选性。如果你希望一个参数是可选的,最推荐且清晰的方法是使用 Python 的 typing 模块中的 Optional 类型提示。
typing.Optional[T] 本质上表示该参数的类型可以是 T 或 None。当 Discord.py 解析命令时,它会识别这种类型提示,并将该参数标记为可选。
示例代码:
import discord
from discord import app_commands
import typing # 导入 typing 模块
# 假设 bot 是你的 discord.ext.commands.Bot 或 discord.Client 实例
bot = discord.Client(intents=discord.Intents.default())
tree = app_commands.CommandTree(bot)
@tree.command(name='decide_optional_type', description='使用 typing.Optional 设置可选参数')
@app_commands.describe(choice1="你的第一个选择")
@app_commands.describe(choice2="你的第二个选择")
@app_commands.describe(choice3="你的第三个选择 (可选)") # 描述中可注明可选
async def decide_optional_type(interaction: discord.Interaction, choice1: str, choice2: str, choice3: typing.Optional[str]):
"""
一个使用 typing.Optional 定义可选参数的示例命令。
"""
if choice3:
response_message = f"你选择了: {choice1}, {choice2}, 和 {choice3}。"
else:
response_message = f"你选择了: {choice1}, {choice2},但未提供第三个选择。"
await interaction.response.send_message(response_message)
# 在机器人启动时同步命令
@bot.event
async def on_ready():
print(f'{bot.user} 已经上线!')
await tree.sync() # 同步斜杠命令
print("斜杠命令已同步。")
# bot.run("YOUR_BOT_TOKEN")另一种实现可选参数的方法是直接在函数签名中为参数提供一个默认值,通常是 None。Python 函数的默认参数行为与 Discord.py 的 app_commands 机制兼容。当一个参数有默认值时,它自然成为可选的。
示例代码:
import discord
from discord import app_commands
# 假设 bot 是你的 discord.ext.commands.Bot 或 discord.Client 实例
bot = discord.Client(intents=discord.Intents.default())
tree = app_commands.CommandTree(bot)
@tree.command(name='decide_default_value', description='使用默认参数值设置可选参数')
@app_commands.describe(choice1="你的第一个选择")
@app_commands.describe(choice2="你的第二个选择")
@app_commands.describe(choice3="你的第三个选择 (可选)") # 描述中可注明可选
async def decide_default_value(interaction: discord.Interaction, choice1: str, choice2: str, choice3: str = None):
"""
一个使用默认参数值定义可选参数的示例命令。
"""
if choice3:
response_message = f"你选择了: {choice1}, {choice2}, 和 {choice3}。"
else:
response_message = f"你选择了: {choice1}, {choice2},但未提供第三个选择。"
await interaction.response.send_message(response_message)
# 在机器人启动时同步命令
@bot.event
async def on_ready():
print(f'{bot.user} 已经上线!')
await tree.sync() # 同步斜杠命令
print("斜杠命令已同步。")
# bot.run("YOUR_BOT_TOKEN")参数顺序: 在 Python 函数中,所有带有默认值的参数(即可选参数)必须定义在所有不带默认值的参数(即必需参数)之后。例如,async def my_command(interaction, required_arg: str, optional_arg: str = None): 是正确的,而 async def my_command(interaction, optional_arg: str = None, required_arg: str): 会导致语法错误。 当使用 typing.Optional[str] 时,同样建议将其放在必需参数之后,以保持代码的可读性和一致性。Discord 客户端在显示命令参数时,通常会将所有可选参数排在必需参数之后。
None 值处理: 当一个可选参数未被提供时,它在命令函数内部的值将是 None。因此,在函数逻辑中,你需要检查这些可选参数是否为 None,并根据需要进行相应的处理。在上述示例中,我们使用了 if choice3: 来判断参数是否被提供。
app_commands.describe 的使用: 无论哪种方法,都应继续使用 @app_commands.describe() 装饰器为每个参数提供清晰的描述。这有助于用户在 Discord 客户端中更好地理解每个参数的用途,特别是对于可选参数,可以在描述中明确指出其可选性。
选择哪种方法?
两种方法在功能上是等效的,都会使参数在 Discord 客户端中显示为可选。
通过 typing.Optional[Type] 类型提示或为参数设置默认值(如 None),可以有效地为 Discord.py 的斜杠命令定义可选参数,避免 AttributeError。这两种方法都符合 Python 和 Discord.py 的最佳实践,使得命令更加灵活和用户友好。在实际开发中,建议优先使用 typing.Optional 以增强代码的类型安全和可读性。同时,务必注意参数顺序和 None 值的处理,以确保命令逻辑的健壮性。
以上就是Discord.py app_commands:正确设置斜杠命令可选参数的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号