ysn-rfd/text-dataset-tiny-code-script-py-format
USED of tahamajs/medicine_ds_persian for .parquet file USED of Alijafarixcs2/persian-it-llama2-2k for .parquet file USED of Abirate/english_quotes for .jsonl file NEW FILES (05/12/2025) NEW FILES (12/26/2025) NEW FILES (02/15/2026)
31.6k
1# main.py2 3import os4import logging5import asyncio6import httpx7import time8from telegram import Update9from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes10from openai import AsyncOpenAI11from keep_alive import start_keep_alive12 13# وارد کردن مدیر دادهها و پنل ادمین14import data_manager15import admin_panel16 17# شروع سرویس نگه داشتن ربات فعال18start_keep_alive()19 20# --- بهبود لاگینگ ---21logging.basicConfig(22 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", 23 level=logging.INFO,24 filename=data_manager.LOG_FILE, 25 filemode='a'26)27logger = logging.getLogger(__name__)28 29try:30 with open(data_manager.LOG_FILE, 'a') as f:31 f.write("")32except Exception as e:33 print(f"FATAL: Could not write to log file at {data_manager.LOG_FILE}. Error: {e}")34 logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")35 36# --- ایجاد یک کلاینت HTTP بهینهسازیشده ---37http_client = httpx.AsyncClient(38 http2=True,39 limits=httpx.Limits(max_keepalive_connections=20, max_connections=100, keepalive_expiry=30.0),40 timeout=httpx.Timeout(timeout=60.0, connect=10.0, read=45.0, write=10.0)41)42 43# کلاینت OpenAI (HuggingFace)44client = AsyncOpenAI(45 base_url="https://router.huggingface.co/v1",46 api_key=os.environ["HF_TOKEN"],47 http_client=http_client48)49 50# --- دیکشنری برای مدیریت وظایف پسزمینه هر کاربر ---51user_tasks = {}52 53# --- توابع کمکی برای مدیریت وظایف ---54def _cleanup_task(task: asyncio.Task, user_id: int):55 if user_id in user_tasks and user_tasks[user_id] == task:56 del user_tasks[user_id]57 logger.info(f"Cleaned up finished task for user {user_id}.")58 try:59 exception = task.exception()60 if exception:61 logger.error(f"Background task for user {user_id} failed: {exception}")62 except asyncio.CancelledError:63 logger.info(f"Task for user {user_id} was cancelled.")64 65async def _process_user_request(update: Update, context: ContextTypes.DEFAULT_TYPE):66 chat_id = update.effective_chat.id67 user_message = update.message.text68 user_id = update.effective_user.id69 70 start_time = time.time()71 72 try:73 await context.bot.send_chat_action(chat_id=chat_id, action="typing")74 75 # دریافت context کاربر (شامل instruction سیستم)76 user_context = data_manager.get_context_for_api(user_id)77 78 # اضافه کردن پیام کاربر به context79 data_manager.add_to_user_context(user_id, "user", user_message)80 81 # ایجاد لیست پیامها برای API (instruction سیستم در ابتدا قرار دارد)82 messages = user_context83 84 logger.info(f"User {user_id} sending {len(messages)} messages to AI (incl. system instruction)")85 86 response = await client.chat.completions.create(87 model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",88 messages=messages,89 temperature=0.7,90 top_p=0.95,91 stream=False,92 )93 94 end_time = time.time()95 response_time = end_time - start_time96 data_manager.update_response_stats(response_time)97 98 ai_response = response.choices[0].message.content99 100 # اضافه کردن پاسخ هوش مصنوعی به context101 data_manager.add_to_user_context(user_id, "assistant", ai_response)102 103 await update.message.reply_text(ai_response)104 data_manager.update_user_stats(user_id, update.effective_user)105 106 except httpx.TimeoutException:107 logger.warning(f"Request timed out for user {user_id}.")108 await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")109 except Exception as e:110 logger.error(f"Error while processing message for user {user_id}: {e}")111 await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")112 113# --- هندلرهای اصلی ربات ---114async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:115 user = update.effective_user116 user_id = user.id117 118 data_manager.update_user_stats(user_id, user)119 120 welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")121 await update.message.reply_html(122 welcome_msg.format(user_mention=user.mention_html()),123 disable_web_page_preview=True124 )125 126async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:127 """پاک کردن تاریخچه چت برای کاربر"""128 user_id = update.effective_user.id129 data_manager.clear_user_context(user_id)130 131 await update.message.reply_text(132 "🧹 تاریخچه مکالمه شما پاک شد.\n"133 "از این لحظه مکالمه جدیدی شروع خواهد شد."134 )135 136async def context_info(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:137 """نمایش اطلاعات context کاربر"""138 user_id = update.effective_user.id139 context_summary = data_manager.get_context_summary(user_id)140 141 await update.message.reply_text(142 f"📊 **اطلاعات تاریخچه مکالمه شما:**\n\n"143 f"{context_summary}\n\n"144 f"برای پاک کردن تاریخچه از دستور /clear استفاده کنید."145 )146 147async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:148 """نمایش دستورات کمک"""149 help_text = (150 "🤖 **دستورات ربات:**\n\n"151 "🟢 `/start` - شروع کار با ربات\n"152 "🟢 `/clear` - پاک کردن تاریخچه مکالمه\n"153 "🟢 `/context` - نمایش اطلاعات تاریخچه مکالمه\n"154 "🟢 `/help` - نمایش این پیام راهنما\n\n"155 "📝 **نکته:** ربات تاریخچه مکالمه شما را تا ۵۱۲ توکن ذخیره میکند. "156 "برای شروع مکالمه جدید از دستور /clear استفاده کنید."157 )158 await update.message.reply_text(help_text, parse_mode='Markdown')159 160async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:161 user_id = update.effective_user.id162 163 # بررسی مسدود بودن کاربر164 if data_manager.is_user_banned(user_id):165 logger.info(f"Banned user {user_id} tried to send a message.")166 return167 168 # بررسی حالت نگهداری (فقط برای کاربران عادی)169 if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:170 await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")171 return172 173 # بررسی کلمات مسدود شده174 if data_manager.contains_blocked_words(update.message.text):175 logger.info(f"User {user_id} sent a message with a blocked word.")176 # میتوانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید177 # await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")178 return179 180 if user_id in user_tasks and not user_tasks[user_id].done():181 user_tasks[user_id].cancel()182 logger.info(f"Cancelled previous task for user {user_id} to start a new one.")183 184 task = asyncio.create_task(_process_user_request(update, context))185 user_tasks[user_id] = task186 task.add_done_callback(lambda t: _cleanup_task(t, user_id))187 188def main() -> None:189 token = os.environ.get("BOT_TOKEN")190 if not token:191 logger.error("BOT_TOKEN not set in environment variables!")192 return193 194 application = (195 Application.builder()196 .token(token)197 .concurrent_updates(True)198 .build()199 )200 201 # هندلرهای کاربران202 application.add_handler(CommandHandler("start", start))203 application.add_handler(CommandHandler("clear", clear_chat))204 application.add_handler(CommandHandler("context", context_info))205 application.add_handler(CommandHandler("help", help_command))206 application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))207 208 # راهاندازی و ثبت هندلرهای پنل ادمین209 admin_panel.setup_admin_handlers(application)210 211 port = int(os.environ.get("PORT", 8443))212 webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"213 214 application.run_webhook(215 listen="0.0.0.0",216 port=port,217 webhook_url=webhook_url,218 url_path="webhook"219 )220 221if __name__ == "__main__":222 main()