如何检查discord.py中是否缺少必需的参数

2024-10-03 19:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的discord机器人添加coinflip功能。此命令有3个参数,即!硬币翻转,硬币上你想要的一面和你想要赌博的金额。此功能工作正常。但是,如果用户将这些参数写错,或者缺少参数,则不会发生任何事情,并且我的控制台中会出现错误。当用户错误地编写命令时,如何让bot发送一条消息来解释如何编写命令

以下是代码的必要部分:

@bot.command()
async def coinflip(ctx, outcome, amount:int):
    coin = random.choice(["heads", "tails"])
    if outcome == coin:
        coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
        await ctx.send(embed=coinflipEmbed)
    elif outcome != coin:
        coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
        await ctx.send(embed=coinflipEmbed)

Tags: 用户命令功能参数bot错误硬币embed
2条回答

你可以:

  • 捕获*args中的所有参数
  • 验证其长度
  • 然后分别验证每个参数

看起来是这样的:

@bot.command()
async def coinflip(ctx, *args):
    # All args are here?
    if len(args) != 2:
        await ctx.send("Error message saying you want coin and amount")
        return
    # Are they valid?
    outcome = args[0]
    amount = args[1]
    if not outcome_is_valid(outcome):
        await ctx.send("Tell him its invalid and why")
        return
    if not amount_is_valid(outcome):
        await ctx.send("Tell him its invalid and why")
        return
    # All good, proceed
    coin = random.choice(["heads", "tails"])
    if outcome == coin:
        coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you won **{amount}** money!", color=0x00FF00)
        await ctx.send(embed=coinflipEmbed)
    elif outcome != coin:
        coinflipEmbed = discord.Embed(title="Coinflip", description=f"The coin landed on **{coin}**, and you lost **{amount}** money!", color=0xFF0000)
        await ctx.send(embed=coinflipEmbed)

您可能希望在coin_flip()命令下面创建一个错误命令

下面的代码只接受MissingRequiredArgument错误。 尽管您可以通过删除代码块来轻松地改变这一点。再次运行代码,键入不正确的内容并查找主要错误。然后用commands.your_error替换这个commands.MissingRequiredArgument

@coinflip.error
async def flip_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Inccorrect arguments entered | **!command_name - outcome:str - amount:int'**)

相关问题 更多 >