import asyncio import socket import logging import aiohttp from telegram.error import NetworkError, RetryAfter from telegram.ext import Application from telegram import Update # Configure logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) async def initialize_with_retry(bot_token: str) -> Application: """Initialize the bot with retry logic""" # DNS Configuration socket.setdefaulttimeout(30) # Initialize application with retry logic max_retries = 5 retry_delay = 5 # seconds last_error = None for attempt in range(max_retries): try: # Initialize the application with custom connection settings application = Application.builder().token(bot_token).build() # Configure connection pool for Hugging Face environment application.bot._request._client._client.transport._pool._max_keepalive_connections = 1 application.bot._request._client._client.transport._pool._max_connections = 1 # Test connection await application.bot.get_me() logger.info("Bot successfully initialized!") return application except (NetworkError, RetryAfter, aiohttp.ClientError) as e: last_error = e if attempt < max_retries - 1: wait_time = retry_delay * (2 ** attempt) # Exponential backoff logger.warning(f"Connection attempt {attempt + 1}/{max_retries} failed: {str(e)}") logger.info(f"Retrying in {wait_time} seconds...") await asyncio.sleep(wait_time) else: logger.error(f"Failed to initialize bot after {max_retries} attempts: {str(last_error)}") raise except Exception as e: logger.error(f"Unexpected error during initialization: {str(e)}") raise async def run_bot(application: Application): """Run the bot with proper error handling""" try: # Start the bot await application.initialize() await application.start() await application.run_polling(allowed_updates=Update.ALL_TYPES) except Exception as e: logger.error(f"Error running bot: {str(e)}") raise finally: # Proper cleanup try: await application.stop() await application.shutdown() except Exception as e: logger.error(f"Error during shutdown: {str(e)}")