Create bot_init.py
Browse files- Mikobot/bot_init.py +71 -0
Mikobot/bot_init.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import socket
|
3 |
+
import logging
|
4 |
+
import aiohttp
|
5 |
+
from telegram.error import NetworkError, RetryAfter
|
6 |
+
from telegram.ext import Application
|
7 |
+
from telegram import Update
|
8 |
+
|
9 |
+
# Configure logging
|
10 |
+
logging.basicConfig(
|
11 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
12 |
+
level=logging.INFO
|
13 |
+
)
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
async def initialize_with_retry(bot_token: str) -> Application:
|
17 |
+
"""Initialize the bot with retry logic"""
|
18 |
+
# DNS Configuration
|
19 |
+
socket.setdefaulttimeout(30)
|
20 |
+
|
21 |
+
# Initialize application with retry logic
|
22 |
+
max_retries = 5
|
23 |
+
retry_delay = 5 # seconds
|
24 |
+
last_error = None
|
25 |
+
|
26 |
+
for attempt in range(max_retries):
|
27 |
+
try:
|
28 |
+
# Initialize the application with custom connection settings
|
29 |
+
application = Application.builder().token(bot_token).build()
|
30 |
+
|
31 |
+
# Configure connection pool for Hugging Face environment
|
32 |
+
application.bot._request._client._client.transport._pool._max_keepalive_connections = 1
|
33 |
+
application.bot._request._client._client.transport._pool._max_connections = 1
|
34 |
+
|
35 |
+
# Test connection
|
36 |
+
await application.bot.get_me()
|
37 |
+
logger.info("Bot successfully initialized!")
|
38 |
+
return application
|
39 |
+
|
40 |
+
except (NetworkError, RetryAfter, aiohttp.ClientError) as e:
|
41 |
+
last_error = e
|
42 |
+
if attempt < max_retries - 1:
|
43 |
+
wait_time = retry_delay * (2 ** attempt) # Exponential backoff
|
44 |
+
logger.warning(f"Connection attempt {attempt + 1}/{max_retries} failed: {str(e)}")
|
45 |
+
logger.info(f"Retrying in {wait_time} seconds...")
|
46 |
+
await asyncio.sleep(wait_time)
|
47 |
+
else:
|
48 |
+
logger.error(f"Failed to initialize bot after {max_retries} attempts: {str(last_error)}")
|
49 |
+
raise
|
50 |
+
|
51 |
+
except Exception as e:
|
52 |
+
logger.error(f"Unexpected error during initialization: {str(e)}")
|
53 |
+
raise
|
54 |
+
|
55 |
+
async def run_bot(application: Application):
|
56 |
+
"""Run the bot with proper error handling"""
|
57 |
+
try:
|
58 |
+
# Start the bot
|
59 |
+
await application.initialize()
|
60 |
+
await application.start()
|
61 |
+
await application.run_polling(allowed_updates=Update.ALL_TYPES)
|
62 |
+
except Exception as e:
|
63 |
+
logger.error(f"Error running bot: {str(e)}")
|
64 |
+
raise
|
65 |
+
finally:
|
66 |
+
# Proper cleanup
|
67 |
+
try:
|
68 |
+
await application.stop()
|
69 |
+
await application.shutdown()
|
70 |
+
except Exception as e:
|
71 |
+
logger.error(f"Error during shutdown: {str(e)}")
|