我在我的Pycord机器人上有一个斜杠指令。以下是代码:
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name):
await ctx.send('Hello ' + name + '!')如何使"name“成为可选参数?我试着设置name=None,但它不起作用。
发布于 2021-12-08 09:44:16
有几种方法可以做到这一点。第一种方法是最简单、最懒的方法,它只是将参数设置为默认值:
@bot.slash_command(name='greet', description='Greet someone!')
async def greet(ctx, name=''):
await ctx.respond(f'Hello {name}!')我所知道的第二种方法来自于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}!')编辑:
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}!")发布于 2022-01-15 06:38:10
您可以从pycord 命令中找到示例。
# example.py
import discord
import json
from discord.ext import commands
from discord.commands.context import ApplicationContext
from discord.commands import Option
from discord.file import File
import os
# example for getting image
def get_image_paths():
file_paths = []
for fn in os.listdir('./img'):
file_paths.append(os.path.join(os.getcwd(), 'img', fn))
return file_paths
async def images(ctx : ApplicationContext):
imgs = get_image_paths()
files = [File(path) for path in imgs]
await ctx.respond(files=files)
async def say_hello(ctx : ApplicationContext):
await ctx.respond(f"hello")
# guild_ids are optional, but for fast registration I recommand it
# name (optional) : if not provided, your command name will shown as function name; this case "my_command"
@commands.slash_command(
name = "my_command",
description= "This is sample command",
guild_ids = [ <your guild(server) id> ],
)
async def sample_command(
ctx : ApplicationContext,
opt: Option(str,
"reaction you want",
choices=["Hi", "image"],
required=True)
):
if opt == "Hi":
await say_hello(ctx)
if opt == "image":
await images(ctx)它将看起来像:



将此脚本导入为from example import library_command
别忘了添加命令
# at main.py
...
bot.add_application_command(library_command)
...
bot.run(<your token>)你必须以“回复”的方式发送,而不是“发送”,否则不和将被算作“未能回复”。
https://stackoverflow.com/questions/70259162
复制相似问题