CoolFace
Datasetpublic

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)

sourceHugging Faceapache-2.0updated 4mo agoView on Hugging Face
3likes1.6kdownloads
main.py168 linesDownload Raw Back to render-main
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        response = await client.chat.completions.create(75            model="mlabonne/gemma-3-27b-it-abliterated:featherless-ai",76            messages=[{"role": "user", "content": user_message}],77            temperature=0.7,78            top_p=0.95,79            stream=False,80        )81        82        end_time = time.time()83        response_time = end_time - start_time84        data_manager.update_response_stats(response_time)85        86        await update.message.reply_text(response.choices[0].message.content)87        data_manager.update_user_stats(user_id, update.effective_user)88 89    except httpx.TimeoutException:90        logger.warning(f"Request timed out for user {user_id}.")91        await update.message.reply_text("⏱️ ارتباط با سرور هوش مصنوعی طولانی شد. لطفاً دوباره تلاش کنید.")92    except Exception as e:93        logger.error(f"Error while processing message for user {user_id}: {e}")94        await update.message.reply_text("❌ متاسفانه در پردازش درخواست شما مشکلی پیش آمد. لطفاً دوباره تلاش کنید.")95 96# --- هندلرهای اصلی ربات ---97async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:98    user = update.effective_user99    user_id = user.id100    101    data_manager.update_user_stats(user_id, user)102    103    welcome_msg = data_manager.DATA.get('welcome_message', "سلام {user_mention}! 🤖\n\nمن یک ربات هوشمند هستم. هر سوالی دارید بپرسید.")104    await update.message.reply_html(105        welcome_msg.format(user_mention=user.mention_html()),106        disable_web_page_preview=True107    )108 109async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:110    user_id = update.effective_user.id111    112    # بررسی مسدود بودن کاربر113    if data_manager.is_user_banned(user_id):114        logger.info(f"Banned user {user_id} tried to send a message.")115        return116    117    # بررسی حالت نگهداری (فقط برای کاربران عادی)118    if data_manager.DATA.get('maintenance_mode', False) and user_id not in admin_panel.ADMIN_IDS:119        await update.message.reply_text("🔧 ربات در حال حاضر در حالت نگهداری قرار دارد. لطفاً بعداً تلاش کنید.")120        return121 122    # بررسی کلمات مسدود شده123    if data_manager.contains_blocked_words(update.message.text):124        logger.info(f"User {user_id} sent a message with a blocked word.")125        # می‌توانید به کاربر اطلاع دهید یا پیام را نادیده بگیرید126        # await update.message.reply_text("⚠️ پیام شما حاوی کلمات نامناسب است و ارسال نشد.")127        return128 129    if user_id in user_tasks and not user_tasks[user_id].done():130        user_tasks[user_id].cancel()131        logger.info(f"Cancelled previous task for user {user_id} to start a new one.")132 133    task = asyncio.create_task(_process_user_request(update, context))134    user_tasks[user_id] = task135    task.add_done_callback(lambda t: _cleanup_task(t, user_id))136 137def main() -> None:138    token = os.environ.get("BOT_TOKEN")139    if not token:140        logger.error("BOT_TOKEN not set in environment variables!")141        return142 143    application = (144        Application.builder()145        .token(token)146        .concurrent_updates(True)147        .build()148    )149 150    application.add_handler(CommandHandler("start", start))151    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))152    153    # راه‌اندازی و ثبت هندلرهای پنل ادمین154    admin_panel.setup_admin_handlers(application)155 156    port = int(os.environ.get("PORT", 8443))157    webhook_url = os.environ.get("RENDER_EXTERNAL_URL") + "/webhook"158    159    application.run_webhook(160        listen="0.0.0.0",161        port=port,162        webhook_url=webhook_url,163        url_path="webhook"164    )165 166if __name__ == "__main__":167    main()168