From 90c97d3f54323c7ec4eb996dd332590f2df62d64 Mon Sep 17 00:00:00 2001 From: wirehack7 Date: Thu, 1 May 2025 19:25:48 +0200 Subject: [PATCH] better timeout handling --- src/main.py | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main.py b/src/main.py index ec7718d..31a993f 100644 --- a/src/main.py +++ b/src/main.py @@ -159,16 +159,20 @@ async def generate( } start_time = time.monotonic() - - async with aiohttp.ClientSession() as session: - async with session.post( - "https://image.novelai.net/ai/generate-image", - json=payload, - headers=headers, - timeout=aiohttp.ClientTimeout(total=120), - ) as response: - response_bytes = await response.read() - status_code = response.status + try: + async with aiohttp.ClientSession() as session: + async with session.post( + "https://image.novelai.net/ai/generate-image", + json=payload, + headers=headers, + timeout=aiohttp.ClientTimeout(total=120), + ) as response: + response_bytes = await response.read() + status_code = response.status + except aiohttp.TimeoutError: + await interaction.followup.send("Error: the request timed out.") + except aiohttp.ClientError as e: + await interaction.followup.send(f"Error: {e}") duration = time.monotonic() - start_time logger.info("Image creation took %.2f seconds", duration) @@ -214,9 +218,9 @@ async def generate( except Exception: # pylint: disable=W0718 error_data = "error message unreadable" - error_message = f"Error {status_code} at API-request.\n" f"Answer: {error_data}\n" + error_message = f"Error {status_code} at API-request.\n" f"Answer: {error_data}\n" - await interaction.followup.send(error_message) + await interaction.followup.send(error_message) bot.run(BOT_TOKEN)