我有一个不协调的.py斜杠命令,它包含两个参数。我想为这些论点提供选择,但我不知道怎么做。
到目前为止,这就是我所拥有的,但它不起作用。
import discord
from discord import app_commands
from discord.ext import commands
@bot.tree.command(name="schedule")
@app_commands.Argument(name="name", required=True, choices=[])
@app_commands.Argument(name="day", required=True, choices=[], default="Today")
async def schedule(interaction: discord.Interaction, name: str, day: str):
await interaction.response.send_message(f"{name} and {day}")
@discord.app_commands.choices()
为命令用户提供了可供选择的选项。
@bot.tree.command(name="schedule")
@app_commands.choices(name=[
app_commands.Choice(name='Name 1', value=1),
app_commands.Choice(name='Name 2', value=2)
])
@app_commands.choices(day=[
app_commands.Choice(name='Monday', value=1),
app_commands.Choice(name='Tuesday', value=2)
])
async def schedule(interaction: discord.Interaction, name: app_commands.Choice[int], day: app_commands.Choice[int]):
await interaction.response.send_message(f"{name.name} and {day.name}")
在app_commands.Choice[int]
中引用的类型str
或int
指示选择值。就像使用day.name
获取选项名称一样,也可以获取值;day.value
。
这也不是向命令提供选择的唯一方法。
还有两种更符合人体工程学的方法。
第一个是使用类型。文字注释
from typing import Literal
@bot.tree.command(name="schedule")
async def schedule(interaction: discord.Interaction, name: str, day: Literal["Monday", "Tuesday", "Wednesday"]):
...
第二种方法是使用enum。枚举
class Days(enum.Enum):
monday = 1
tuesday = 2
wednesday = 3
@bot.tree.command(name="schedule")
async def schedule(interaction: discord.Interaction, name: str, day: Days):
...
参考:discord.app_commands.choices