Search code examples
pythonpython-3.xdiscorddiscord.py

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. 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


Solution

  • You're trying to do num1 = int(number1) which can cause errors if you aren't given correctly formatted input. 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:

    enter image description here