| |
|
|
| 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_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) |
| ) |
|
|
| |
| client = AsyncOpenAI( |
| base_url="https://router.huggingface.co/v1", |
| api_key=os.environ["HF_TOKEN"], |
| http_client=http_client |
| ) |
|
|
| |
| 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 = {} |
|
|
| |
| 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") |
| |
| |
| if HAS_SMART_CONTEXT: |
| smart_context = _get_or_create_smart_context(user_id) |
| |
| |
| await smart_context.process_message("user", user_message) |
| |
| |
| retrieved_context = await smart_context.retrieve_context(user_message, max_tokens=1024) |
| |
| |
| 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}) |
| |
| |
| 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') |
|
|
| |
|
|
| 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 |
|
|
| |
| if user_id in user_tasks: |
| try: |
| |
| if not user_tasks[user_id].done(): |
| |
| 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}") |
|
|
| |
| 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: |
| |
| 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)) |
| |
| |
| 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) |
|
|
| |
| port = int(os.environ.get("PORT", 8443)) |
| webhook_url = os.environ.get("RENDER_EXTERNAL_URL", "") |
| |
| if webhook_url: |
| |
| 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: |
| |
| application.run_polling(drop_pending_updates=True) |
| logger.info("Bot running in polling mode") |
|
|
| if __name__ == "__main__": |
| main() |