python error image download any solution?

Question:

I’m trying to download an image with a discord bot but I get the following error:

https://i.imgur.com/H8rgqjT.png

I would like it to throw an image error message in case the image cannot be downloaded within Discord: This is the code that gives an error:

Here would be the error:

Thank you very much!

Answers:

You need to make sure the request succeeded before you try to use the result.

@bot.command()
async def habbo(ctx):
    url = f"https://images.habbo.com/web_images/mypages/hhes/87548.png"
    r = request.get(url)
    if r.status_code == 200:
        imagen = Image.open(io.BytesIO(r.content))
        with io.BytesIO() as imagen_binary:
            imagen.save(imagen_binary, 'PNG')
            imagen_binary.seek(0)
    else:
        print("Failed to fetch image")    
Answered By: Tim Roberts
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.