From e193bf1989b84ca7685d3529fc4babb7d09f6c54 Mon Sep 17 00:00:00 2001 From: pluja Date: Thu, 20 Apr 2023 10:10:56 +0200 Subject: [PATCH] add error handling for pyttsx3 file writing --- main.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index e5d9699..874af28 100644 --- a/main.py +++ b/main.py @@ -85,8 +85,9 @@ def generate_settings_markup(chat_id: str) -> InlineKeyboardMarkup: async def text_to_voice(text: str) -> BytesIO: with tempfile.NamedTemporaryFile(mode='wb', suffix='.ogg', delete=False) as ogg_file: temp_filename = ogg_file.name - voice_done = False + + # If Google TTS is enabled, try to use it first if ENABLE_GOOGLE_TTS: try: tts = gTTS(text) @@ -95,6 +96,7 @@ async def text_to_voice(text: str) -> BytesIO: except Exception as e: print("Google TTS failed, falling back to pyttsx3: --> ", e) + # If Google TTS is disabled or failed, use pyttsx3 if not voice_done: engine = pyttsx3.init() engine.setProperty('rate', 140) @@ -103,7 +105,18 @@ async def text_to_voice(text: str) -> BytesIO: await asyncio.sleep(0.5) # Add a small delay before reading the file with open(temp_filename, "rb") as audio_file: - voice_data = BytesIO(audio_file.read()) + try: # Try to read the file + voice_data = BytesIO(audio_file.read()) + except Exception as e: + print(e) + # If reading the file fails, wait 0.6 seconds and try again + await asyncio.sleep(0.6) # Add a small delay before reading the file + try: + voice_data = BytesIO(audio_file.read()) + except Exception: + # If reading the file fails again, return None + os.remove(temp_filename) + return os.remove(temp_filename) voice_data.seek(0)