当消息不是int时,如何使它只接受int?

2024-04-19 04:57:37 发布

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

这是我写的代码:

if  msg.startswith ("!gamble"):
    
    await message.channel.send(f"""{message.author.name} how much would you like to gamble (Max 10)""")
elif  not  (message.content) in commands and int(message.content) in (idpoints) :
        await message.channel.send(f"""{message.author.name} gambled {int(idpoints[int(message.content)])} and {gamblestate}!""")
elif  not  (message.content) in commands and (idpoints[int(message.content) > 10]) : #> int(message.content) 
    await message.channel.send(f"""{message.author.name} can't gamble {message.content} cause he is too poor """)
elif not (message.content) in commands and (idpoints[int(message.content) > 10]): 
    return None

每当有人写一个单词而不是一个数字时,我都会回复这样的信息:“答案必须是一个完整的数字!”


Tags: andnameinsendmessagechannelnotcontent
1条回答
网友
1楼 · 发布于 2024-04-19 04:57:37

如果强键入命令args,则可以稍后处理异常并向用户显示错误消息

@bot.command()
async def your_command(ctx, foo: str, bar: int):
    # do stuff with your code
    pass

当用户这样做时 !your_command spam egg,discord将抛出BadArgument错误,因为它预期的是int,但得到的是str

然后,您可以使用以下方法处理错误:

@your_command.error
async def your_command_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("Answer has to be an integer!")

请务必阅读discord.py documents,尽管它可能看起来很吓人。这是非常好的记录

相关问题 更多 >