|
import asyncio |
|
import socket |
|
import logging |
|
import aiohttp |
|
from telegram.error import NetworkError, RetryAfter |
|
from telegram.ext import Application |
|
from telegram import Update |
|
|
|
|
|
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""" |
|
|
|
socket.setdefaulttimeout(30) |
|
|
|
|
|
max_retries = 5 |
|
retry_delay = 5 |
|
last_error = None |
|
|
|
for attempt in range(max_retries): |
|
try: |
|
|
|
application = Application.builder().token(bot_token).build() |
|
|
|
|
|
application.bot._request._client._client.transport._pool._max_keepalive_connections = 1 |
|
application.bot._request._client._client.transport._pool._max_connections = 1 |
|
|
|
|
|
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) |
|
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: |
|
|
|
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: |
|
|
|
try: |
|
await application.stop() |
|
await application.shutdown() |
|
except Exception as e: |
|
logger.error(f"Error during shutdown: {str(e)}") |