Pycord框架下Discord机器人斜杠命令获取图片生成Prompt问题
Pycord斜杠命令获取用户输入参数的问题
用户使用Pycord开发Discord机器人时,编写了generate斜杠命令用于生成图片,但无法正确获取用户输入的imageprompt参数内容,尝试message.content、message.summary等方法均无效。已有实现好的generate_image函数,需解决如何在斜杠命令中获取prompt并调用生成图片的问题,原代码如下:
@bot.slash_command(name = 'generate', description='Generate any image') async def generate(message, imageprompt: Option(str, description="The prompt to generate", required = True)): await message.channel.trigger_typing() #shows that the bot is typing prompt = message.summary(imageprompt) image_url = await generate_image(prompt) try: await message.respond(image_url) #responds to the slash command (bot must respond within 3 seconds) except: await message.send(image_url) #sends as a regular message, if it cannot send as a slash command
解决方案
在Pycord的斜杠命令函数中,你定义的参数会直接接收用户输入的内容,不需要通过message对象提取。直接使用函数形参imageprompt即可获取用户输入的prompt文本,修改第4行后,完整代码如下:
@bot.slash_command(name = 'generate', description='Generate any image') async def generate(message, imageprompt: Option(str, description="The prompt to generate", required = True)): await message.channel.trigger_typing() #shows that the bot is typing prompt = imageprompt # 直接使用函数参数获取用户输入的prompt image_url = await generate_image(prompt) try: await message.respond(image_url) #responds to the slash command (bot must respond within 3 seconds) except: await message.send(image_url) #sends as a regular message, if it cannot send as a slash command
也可以省去中间变量,直接将imageprompt传入生成函数:
@bot.slash_command(name = 'generate', description='Generate any image') async def generate(message, imageprompt: Option(str, description="The prompt to generate", required = True)): await message.channel.trigger_typing() #shows that the bot is typing image_url = await generate_image(imageprompt) try: await message.respond(image_url) #responds to the slash command (bot must respond within 3 seconds) except: await message.send(image_url) #sends as a regular message, if it cannot send as a slash command
原因是Pycord处理斜杠命令时,会自动将用户输入的参数值传递给函数对应的形参,无需从message对象中额外提取参数内容。
内容的提问来源于stack exchange,提问作者ThatMysticalDude
相关产品推荐
相关产品推荐

