Bla*_*f12 2 python discord pycord
我的 Pycord 机器人中有一个斜杠命令。这是代码:
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name):
await ctx.send('Hello ' + name + '!')
Run Code Online (Sandbox Code Playgroud)
我如何使“名称”成为可选参数?我尝试设置 name=None,但它不起作用。
有几种方法可以做到这一点。第一种方法是最简单也是最懒的方法,只需将参数设置为默认值,如下所示:
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name=''):
await ctx.respond(f'Hello {name}!')
Run Code Online (Sandbox Code Playgroud)
我知道的第二种方法是来自Pycord 存储库中的示例代码:
from discord.commands import Option
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name: Option(str, "Enter your friend's name", required = False, default = '')):
await ctx.respond(f'Hello {name}!')
Run Code Online (Sandbox Code Playgroud)
编辑:
await ctx.send(f'Hello {name}!')更改为await ctx.respond(f'Hello {name}!')因为不和谐需要斜线命令的响应,否则不和谐将显示一条丑陋的错误消息,指出没有响应。
更新:
自 2022 年 6 月起,您可以使用装饰器中表示的默认参数值编写斜杠命令:
@bot.slash_command(name='greet', description='Greet someone!')
@option(
"name",
description="Enter your friend's name",
required=False,
default=''
)
async def greet(
ctx: discord.ApplicationContext,
name: str
):
await ctx.respond(f"Hello {name}!")
Run Code Online (Sandbox Code Playgroud)