File size: 19,012 Bytes
db37698 |
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# main.py
import os
import logging
import asyncio
import httpx
import time
from datetime import datetime
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
from openai import AsyncOpenAI
from keep_alive import start_keep_alive
# وارد کردن مدیر دادهها و پنل ادمین
import data_manager
import admin_panel
# شروع سرویس نگه داشتن ربات فعال
start_keep_alive()
# --- بهبود لاگینگ ---
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO,
filename=data_manager.LOG_FILE,
filemode='a'
)
logger = logging.getLogger(__name__)
try:
with open(data_manager.LOG_FILE, 'a') as f:
f.write("")
except Exception as e:
print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---
http_client = httpx.AsyncClient(
http2=True,
limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),
timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)
)
# کلاینت OpenAI (HuggingFace)
client = AsyncOpenAI(
base_url="https://router.huggingface.co/v1",
api_key=os.environ["HF_TOKEN"],
http_client=http_client
)
# --- سیستم Context هوشمند ---
try:
from smart_context import IntelligentContextManager
HAS_SMART_CONTEXT = True
logger.info("Smart context module loaded successfully")
except ImportError as e:
HAS_SMART_CONTEXT = False
logger.warning(f"Smart context module not available: {e}. Using basic context.")
# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---
user_tasks = {}
# --- دیکشنری برای مدیران Context هوشمند ---
smart_context_managers = {}
# --- توابع کمکی برای مدیریت وظایف ---
def _cleanup_task(task: asyncio.Task, user_id: int):
if user_id in user_tasks and user_tasks[user_id] == task:
del user_tasks[user_id]
logger.info(f"Cleaned up finished task for user {user_id}.")
try:
exception = task.exception()
if exception:
logger.error(f"Background task for user {user_id} failed: {exception}")
except asyncio.CancelledError:
logger.info(f"Task for user {user_id} was cancelled.")
def _get_or_create_smart_context(user_id: int) -> IntelligentContextManager:
"""دریافت یا ایجاد مدیر Context هوشمند برای کاربر"""
if user_id not in smart_context_managers:
smart_context_managers[user_id] = IntelligentContextManager(user_id)
return smart_context_managers[user_id]
async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
user_message = update.message.text
user_id = update.effective_user.id
start_time = time.time()
try:
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
# استفاده از Context هوشمند اگر فعال باشد
if HAS_SMART_CONTEXT:
smart_context = _get_or_create_smart_context(user_id)
# پردازش پیام کاربر با سیستم هوشمند
await smart_context.process_message("user", user_message)
# بازیابی context مرتبط
retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024)
# آمادهسازی پیامها برای API
messages = await smart_context.get_context_for_api(user_message)
logger.info(f"Smart context: {len(messages)} messages retrieved for user {user_id}")
else:
# استفاده از سیستم قدیمی
user_context = data_manager.get_context_for_api(user_id)
data_manager.add_to_user_context(user_id, "user", user_message)
messages = user_context.copy()
messages.append({"role": "user", "content": user_message})
# ارسال به API
response = await client.chat.completions.create(
model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",
messages=messages,
temperature=0.7,
top_p=0.95,
stream=False,
)
end_time = time.time()
response_time = end_time - start_time
data_manager.update_response_stats(response_time)
ai_response = response.choices[0].message.content
# ذخیره پاسخ در سیستم مناسب
if HAS_SMART_CONTEXT:
await smart_context.process_message("assistant", ai_response)
else:
data_manager.add_to_user_context(user_id, "assistant", ai_response)
await update.message.reply_text(ai_response)
data_manager.update_user_stats(user_id, update.effective_user)
except httpx.TimeoutException:
logger.warning(f"Request timed out for user {user_id}.")
await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")
except Exception as e:
logger.error(f"Error while processing message for user {user_id}: {e}")
await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")
# --- هندلرهای اصلی ربات ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
user_id = user.id
data_manager.update_user_stats(user_id, user)
welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")
await update.message.reply_html(
welcome_msg.format(user_mention=user.mention_html()),
disable_web_page_preview=True
)
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""پاک کردن تاریخچه چت برای کاربر"""
user_id = update.effective_user.id
if HAS_SMART_CONTEXT:
if user_id in smart_context_managers:
smart_context_managers[user_id].clear_context()
else:
data_manager.clear_user_context(user_id)
await update.message.reply_text(
"🧹 تاریخچه مکالمه شما پاک شد.\n"
"از این لحظه مکالمه جدیدی شروع خواهد شد."
)
async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""نمایش اطلاعات context کاربر"""
user_id = update.effective_user.id
if HAS_SMART_CONTEXT:
if user_id in smart_context_managers:
summary = smart_context_managers[user_id].get_summary()
info_text = (
"🧠 **وضعیت حافظه هوشمند شما:**\n\n"
f"📊 **آمار کلی:**\n"
f"• کل پیامها: {summary['total_messages']}\n"
f"• حافظه فعال: {summary['working_memory']} پیام\n"
f"• حافظه بلندمدت: {summary['long_term_memory']} پیام\n"
f"• حافظه هسته: {summary['core_memory']} پیام\n\n"
f"🎯 **علاقهمندیها:**\n"
)
interests = summary.get('profile_interests', [])
if interests:
info_text += "• " + "\n• ".join(interests[:5])
if len(interests) > 5:
info_text += f"\n• و {len(interests) - 5} مورد دیگر..."
else:
info_text += "هنوز علاقهمندیای ثبت نشده است."
info_text += f"\n\n📈 **کارایی:**\n"
info_text += f"• میانگین اهمیت: {summary['average_importance']:.2%}\n"
info_text += f"• نرخ فشردهسازی: {summary['compression_ratio']:.2%}\n"
info_text += f"• کارایی بازیابی: {summary['retrieval_efficiency']:.2%}"
else:
info_text = "هنوز context هوشمندی ایجاد نشده است."
else:
context_summary = data_manager.get_context_summary(user_id)
info_text = (
f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"
f"{context_summary}\n\n"
f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."
)
await update.message.reply_text(info_text, parse_mode='Markdown')
async def smart_context_status(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""نمایش وضعیت سیستم Context هوشمند"""
if not HAS_SMART_CONTEXT:
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
return
user_id = update.effective_user.id
smart_context = _get_or_create_smart_context(user_id)
# دریافت اطلاعات دقیق
debug_info = smart_context.export_debug_info()
status_text = (
"🤖 **وضعیت سیستم Context هوشمند:**\n\n"
f"✅ **سیستم فعال:** بله\n"
f"👤 **کاربر:** {user_id}\n"
f"📊 **تعداد گرههای حافظه:** {debug_info['memory_graph_size']}\n"
f"🔗 **اتصالات حافظه:** {debug_info['memory_graph_connections']}\n"
f"🎯 **تعداد علاقهمندیها:** {debug_info['user_profile']['interests_count']}\n"
f"⚙️ **تنظیمات مکالمه:** {debug_info['user_profile']['conversation_style']}\n\n"
"📈 **حافظه لایهای:**\n"
)
for layer, size in debug_info['layer_sizes'].items():
status_text += f"• {layer}: {size} پیام\n"
await update.message.reply_text(status_text, parse_mode='Markdown')
async def optimize_memory(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""بهینهسازی دستی حافظه"""
if not HAS_SMART_CONTEXT:
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
return
user_id = update.effective_user.id
if user_id in smart_context_managers:
before_stats = smart_context_managers[user_id].export_debug_info()
# اجرای بهینهسازی
smart_context_managers[user_id]._optimize_memory()
after_stats = smart_context_managers[user_id].export_debug_info()
# محاسبه بهبود
improvements = []
for layer in before_stats['layer_sizes'].keys():
before = before_stats['layer_sizes'][layer]
after = after_stats['layer_sizes'][layer]
if before > after:
improvement = before - after
improvements.append(f"• {layer}: {improvement} پیام آزاد شد")
if improvements:
improvement_text = "\n".join(improvements)
message = (
"✅ **حافظه بهینهسازی شد!**\n\n"
"📊 **بهبودها:**\n"
f"{improvement_text}\n\n"
"🔧 حافظههای غیرضروری پاکسازی شدند و اطلاعات مهم اولویتبندی شدند."
)
else:
message = "✅ حافظه قبلاً بهینه بود. هیچ تغییری اعمال نشد."
else:
message = "⚠️ هنوز حافظهای برای بهینهسازی وجود ندارد."
await update.message.reply_text(message, parse_mode='Markdown')
async def export_context(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""صدور دادههای Context"""
if not HAS_SMART_CONTEXT:
await update.message.reply_text("❌ سیستم Context هوشمند فعال نیست.")
return
user_id = update.effective_user.id
if user_id not in smart_context_managers:
await update.message.reply_text("⚠️ هنوز context هوشمندی ایجاد نشده است.")
return
smart_context = smart_context_managers[user_id]
debug_info = smart_context.export_debug_info()
# ذخیره در فایل موقت
import tempfile
import json
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as f:
json.dump(debug_info, f, indent=4, ensure_ascii=False)
temp_file_path = f.name
await update.message.reply_document(
document=open(temp_file_path, 'rb'),
caption=f"📊 دادههای Context هوشمند کاربر {user_id}"
)
# پاک کردن فایل موقت
import os
os.unlink(temp_file_path)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""نمایش دستورات کمک"""
base_commands = (
"🤖 **دستورات اصلی ربات:**\n\n"
"🟢 `/start` - شروع کار با ربات\n"
"🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"
"🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"
"🟢 `/help` - نمایش این پیام راهنما\n\n"
)
smart_commands = ""
if HAS_SMART_CONTEXT:
smart_commands = (
"🧠 **دستورات Context هوشمند:**\n\n"
"🔷 `/smart_status` - نمایش وضعیت سیستم هوشمند\n"
"🔷 `/optimize` - بهینهسازی دستی حافظه\n"
"🔷 `/export_context` - صدور دادههای Context\n\n"
)
note = (
"📝 **نکته:** ربات تاریخچه مکالمه شما را هوشمندانه مدیریت میکند.\n"
"برای شروع مکالمه جدید از دستور /clear استفاده کنید."
)
await update.message.reply_text(base_commands + smart_commands + note, parse_mode='Markdown')
# main.py - اضافه کردن fallback handler
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_user.id
# بررسی مسدود بودن کاربر
if data_manager.is_user_banned(user_id):
logger.info(f"Banned user {user_id} tried to send a message.")
return
# بررسی حالت نگهداری (فقط برای کاربران عادی)
if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:
await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")
return
# بررسی کلمات مسدود شده
if data_manager.contains_blocked_words(update.message.text):
logger.info(f"User {user_id} sent a message with a blocked word.")
return
# مدیریت وظایف همزمان با timeout
if user_id in user_tasks:
try:
# بررسی اگر task قبلی هنوز در حال اجرا است
if not user_tasks[user_id].done():
# منتظر پایان task قبلی با timeout
try:
await asyncio.wait_for(user_tasks[user_id], timeout=5.0)
except asyncio.TimeoutError:
logger.warning(f"Previous task for user {user_id} timed out, cancelling...")
user_tasks[user_id].cancel()
except Exception as e:
logger.error(f"Error handling previous task for user {user_id}: {e}")
# ایجاد وظیفه جدید با timeout
task = asyncio.create_task(
_process_user_request_with_timeout(update, context)
)
user_tasks[user_id] = task
task.add_done_callback(lambda t: _cleanup_task(t, user_id))
async def _process_user_request_with_timeout(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""پردازش درخواست کاربر با timeout"""
try:
# اجرا با timeout 30 ثانیه
await asyncio.wait_for(
_process_user_request(update, context),
timeout=30.0
)
except asyncio.TimeoutError:
logger.error(f"Processing timed out for user {update.effective_user.id}")
await update.message.reply_text("⏱️ پردازش درخواست شما زمان زیادی برد. لطفاً دوباره تلاش کنید.")
except Exception as e:
logger.error(f"Unexpected error in task for user {update.effective_user.id}: {e}")
def main() -> None:
token = os.environ.get("BOT_TOKEN")
if not token:
logger.error("BOT_TOKEN not set in environment variables!")
return
application = (
Application.builder()
.token(token)
.concurrent_updates(True)
.build()
)
# هندلرهای کاربران
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("clear", clear_chat))
application.add_handler(CommandHandler("context", context_info))
application.add_handler(CommandHandler("help", help_command))
# هندلرهای Context هوشمند
if HAS_SMART_CONTEXT:
application.add_handler(CommandHandler("smart_status", smart_context_status))
application.add_handler(CommandHandler("optimize", optimize_memory))
application.add_handler(CommandHandler("export_context", export_context))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# راهاندازی و ثبت هندلرهای پنل ادمین
admin_panel.setup_admin_handlers(application)
# تنظیمات Webhook برای Render
port = int(os.environ.get("PORT", 8443))
webhook_url = os.environ.get("RENDER_EXTERNAL_URL", "")
if webhook_url:
# حالت Webhook (برای Render)
application.run_webhook(
listen="0.0.0.0",
port=port,
webhook_url=webhook_url + "/webhook",
url_path="webhook",
drop_pending_updates=True
)
logger.info(f"Bot running in webhook mode on port {port}")
else:
# حالت Polling (برای توسعه)
application.run_polling(drop_pending_updates=True)
logger.info("Bot running in polling mode")
if __name__ == "__main__":
main() |