diff --git a/src/session_notifier.py b/src/session_notifier.py index 951d3bf..f3e14cf 100644 --- a/src/session_notifier.py +++ b/src/session_notifier.py @@ -1,8 +1,10 @@ import smtplib import os import logging +import asyncio from email.message import EmailMessage from telegram import Bot +from telegram.error import TimedOut, NetworkError class SessionNotifier: @@ -75,17 +77,34 @@ class SessionNotifier: logging.error(f"Failed to send email: {str(e)}") raise - async def send_telegram_notification(self, message): + async def send_telegram_notification(self, message, max_retries=3): """ Send a Telegram notification with the given message. Args: message (str): The message content to be sent in the Telegram chat + max_retries (int): Maximum number of retry attempts (default: 3) """ # Create a Bot instance with the provided token bot = Bot(token=self.telegram_credentials["token"]) - # Send the message to the specified chat ID and await the result - await bot.send_message(chat_id=self.telegram_credentials["chat_id"], text=message) + + for attempt in range(max_retries): + try: + # Send the message to the specified chat ID and await the result + await bot.send_message(chat_id=self.telegram_credentials["chat_id"], text=message) + logging.debug("Telegram notification sent successfully") + return + except (TimedOut, NetworkError) as e: + if attempt < max_retries - 1: + wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s + logging.warning(f"Telegram notification failed (attempt {attempt + 1}/{max_retries}): {str(e)}. Retrying in {wait_time} seconds...") + await asyncio.sleep(wait_time) + else: + logging.error(f"Failed to send Telegram notification after {max_retries} attempts: {str(e)}") + raise + except Exception as e: + logging.error(f"Unexpected error sending Telegram notification: {str(e)}") + raise async def notify_session_booking(self, session_details): """