File size: 2,589 Bytes
4b226cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
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)}") |