-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathleapcell_config.py
More file actions
95 lines (78 loc) · 2.98 KB
/
Copy pathleapcell_config.py
File metadata and controls
95 lines (78 loc) · 2.98 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
import logging
from datetime import datetime
import sentry_sdk
from prometheus_client import Counter, Histogram
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from healthcheck import HealthCheck
import psutil
# Initialize Sentry for error tracking
sentry_sdk.init(
dsn=os.getenv("SENTRY_DSN", ""), # Add your Sentry DSN here
traces_sample_rate=1.0,
profiles_sample_rate=0.5,
)
# Prometheus metrics
REQUEST_COUNT = Counter('bot_requests_total', 'Total bot requests')
RESPONSE_TIME = Histogram('bot_response_time_seconds', 'Response time in seconds')
ERROR_COUNT = Counter('bot_errors_total', 'Total errors')
# Health check
health = HealthCheck()
def bot_health_check():
"""Check if bot is running and responsive"""
try:
# Check system resources
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
if memory.percent > 90: # Memory usage above 90%
return False, "High memory usage"
if disk.percent > 90: # Disk usage above 90%
return False, "Low disk space"
return True, "Bot is healthy"
except Exception as e:
return False, str(e)
health.add_check(bot_health_check)
# Scheduler for periodic tasks
scheduler = AsyncIOScheduler()
async def cleanup_old_records():
"""Cleanup old records from database"""
try:
thirty_days_ago = datetime.utcnow() - timedelta(days=30)
result = await users_collection.delete_many({
"last_active": {"$lt": thirty_days_ago}
})
logging.info(f"Cleaned up {result.deleted_count} old records")
except Exception as e:
logging.error(f"Error in cleanup: {e}")
sentry_sdk.capture_exception(e)
# Schedule cleanup job
scheduler.add_job(cleanup_old_records, 'cron', hour=0) # Run at midnight
# Cache configuration
from cachetools import TTLCache
user_cache = TTLCache(maxsize=100, ttl=3600) # Cache user data for 1 hour
# Retry configuration
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
async def send_message_with_retry(*args, **kwargs):
"""Send message with retry mechanism"""
return await bot.send_message(*args, **kwargs)
# System monitoring
def get_system_metrics():
"""Get system metrics"""
return {
'memory_usage': psutil.virtual_memory().percent,
'cpu_usage': psutil.cpu_percent(),
'disk_usage': psutil.disk_usage('/').percent,
'open_files': len(psutil.Process().open_files()),
'connections': len(psutil.Process().connections())
}
# Rate limiting
from cachetools import TTLCache
rate_limit_cache = TTLCache(maxsize=1000, ttl=60)
def check_rate_limit(user_id: int, limit: int = 10) -> bool:
"""Check if user has exceeded rate limit"""
current_count = rate_limit_cache.get(user_id, 0)
if current_count >= limit:
return False
rate_limit_cache[user_id] = current_count + 1
return True