首页 > 解决方案 > 在 discord.py 中将引号作为参数传递时出现错误

问题描述

当前,当有人在命令中使用引号时,我的 Discord 机器人出现错误,我收到以下错误:根据discord.ext.commands.errors.ExpectedClosingQuoteError: Expected closing ".错误报告以及. 这个问题有点烦人,我想知道目前是否有任何解决方法。到目前为止,这是我的代码:discord.pydiscord.py

@bot.command()
async def f(ctx, *args):
hearts = (':heart:', ':orange_heart:', ':yellow_heart:', ':green_heart:', ':blue_heart:', ':purple_heart:')

if not args:
    response = '**{0}** has paid their respects {1}'.format(ctx.author.name,
                                                            hearts[random.randint(0, len(hearts) - 1)])
else:
    response = '**{0}** has paid their respects {1} {2}'.format(ctx.author.name, ' '.join(args),
                                                                hearts[random.randint(0, len(hearts) - 1)])

当用户通过输入!f "The thingDiscord 调用此函数时,我会得到上面提到的命令。无论如何我可以解决这个问题吗?我认为这是不可能的,因为从将参数传递到函数的那一刻起,就会引发错误。我想我可以编辑discord.py来解决这个问题,但它可能会破坏我机器人的其他区域。当 iOS 用户使用键盘上的引号并键入类似!f Josh's face. 有没有办法让所有的引号都通过这个函数成功传递?

谢谢!

标签: pythondiscord.py

解决方案


它会将命令之后的所有内容都设为 asargs并将默认设置为 None 因此如果没有 args 就不会出现错误discord.ext.commands.errors.MissingRequiredArgument: args is a required argument that is missing.

我也将格式更改为使用f 字符串,我相信它更容易。并且在您的情况下使用random.choise()更好

来自文档的示例

@bot.command()
async def f(ctx, *, args=None):
    hearts = (':heart:', ':orange_heart:', ':yellow_heart:',
              ':green_heart:', ':blue_heart:', ':purple_heart:')

    if not args:
        response = f'**{ctx.author.name}** has paid their respects {random.choice(hearts)}'
    else:
        response = f'**{ctx.author.name}** has paid their respects {args} {random.choice(hearts)}'

    await ctx.send(response)

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述


推荐阅读