[英]Try/Except handling in discord.py doesn't work
So, I decided to have multiple embeds to be sent for an errors in my number generator.因此,我决定在我的数字生成器中发送多个嵌入的错误。 It works ok, but it doesn't matter whether I set try/except block or not.
它工作正常,但我是否设置 try/except 块并不重要。 The error is only printed in the console
该错误仅打印在控制台中
@bot.command()
async def random(ctx, number1, number2):
num1 = int(number1)
num2 = int(number2)
random_num=randint(num1, num2)
randsuc=embed(
title = "Random bumber",
description = f"{random_num}",
color=discord.Colour.blue())
randsuc.set_footer(text = f'LelushBot | {datetime.utcnow().strftime("%d.%m.%Y | %H:%M:%S")}')
randfail1=embed(
title="Random number",
description=f"An error has occured! {num1} и {num2} are not the numbers",
color=discord.Colour.red())
randfail1.set_footer(text = f'LelushBot | {datetime.utcnow().strftime("%d.%m.%Y | %H:%M:%S")}')
randfail2=embed(
title="Random number",
description=f"An error has occured! Insufficient arguments",
color=discord.Colour.red())
randfail2.set_footer(text = f'LelushBot | {datetime.utcnow().strftime("%d.%m.%Y | %H:%M:%S")}')
try:
await ctx.message.reply(embed=randsuc)
except ValueError:
await ctx.message.reply(embed=randfail1)
else:
await ctx.message.reply(embed=randfail2)
What can I do in this case?在这种情况下我能做什么? Thanks in advance
提前致谢
You're trying to do num1 = int(number1)
which can cause errors if you aren't given correctly formatted input.您正在尝试执行
num1 = int(number1)
,如果没有提供正确格式的输入,这可能会导致错误。 Instead, you should use converters .相反,您应该使用转换器。
@client.command()
async def random_number(ctx, num1: int, num2: int):
random_num = random.randint(num1, num2)
rand_embed = discord.Embed(
title="random_number",
description=f"{random_num}",
color=discord.Colour.blue()
)
rand_embed.set_footer(text='LelushBot')
rand_embed.timestamp = datetime.datetime.utcfromtimestamp(time.time()) # sidenote: this shows the timestamp properly and can be viewed by other people in different timezones
await ctx.send(embed=rand_embed)
You can then do error handling with something like this:然后你可以用这样的东西做错误处理:
async def on_command_error(ctx, err):
if err.__class__ is commands.MissingRequiredArgument:
await ctx.send(f'Error: {err}')
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.