Download bot.py from felix-fx/fx-1: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/felix-fx/fx-1/resolve/main/bot.py
- Command line
-
hf download hf://felix-fx/fx-1/bot.py
-
curl -L -o bot.py https://huggingface.co/felix-fx/fx-1/resolve/main/bot.py
14.1 kB
| """ | |
| Felix Bot v5.1 — بوت التليجرام الرسمي لـ Minecraft FX | |
| إصلاح Webhook + تحسينات الأمان + Anti-Spam | |
| """ | |
| import logging | |
| import requests | |
| import json | |
| import asyncio | |
| import os | |
| import re | |
| import time | |
| from datetime import datetime, timedelta | |
| from collections import defaultdict | |
| from telegram import ( | |
| Update, InlineKeyboardButton, InlineKeyboardMarkup, | |
| BotCommand | |
| ) | |
| from telegram.ext import ( | |
| ApplicationBuilder, CommandHandler, MessageHandler, | |
| CallbackQueryHandler, filters, ContextTypes | |
| ) | |
| from telegram.constants import ParseMode, ChatAction | |
| # ===== إعدادات البوت — يُفضَّل قراءتها من متغيرات البيئة ===== | |
| TELEGRAM_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "8659892648:AAFRJmk4JaIo0Tf3RowKODGyoJmVyc66-jk") | |
| SITE_URL = os.getenv("SITE_URL", "https://fx-craft.vercel.app") | |
| WEBHOOK_URL = os.getenv("WEBHOOK_URL", "") # اضبطه عند النشر: https://yourdomain.com/webhook | |
| AI_API_URL = os.getenv("AI_API_URL", "https://pmmzocyndrkqygbflzfx.supabase.co/functions/v1/ai-mod-assistant") | |
| MODERATE_API_URL = os.getenv("MODERATE_API_URL", "https://pmmzocyndrkqygbflzfx.supabase.co/functions/v1/moderate-content") | |
| SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY", "sb_publishable__O9Og5I3bHaViMEyYkYliA_E9JMU07x") | |
| # ===== إعداد السجلات ===== | |
| logging.basicConfig( | |
| format="%(asctime)s | %(name)s | %(levelname)s | %(message)s", | |
| level=logging.INFO, | |
| handlers=[ | |
| logging.StreamHandler(), | |
| logging.FileHandler("felix_bot.log", encoding="utf-8") if os.path.exists(".") else logging.NullHandler(), | |
| ] | |
| ) | |
| logger = logging.getLogger("FelixBot") | |
| # ===== ذاكرة المحادثات ===== | |
| user_memories: dict[int, list] = defaultdict(list) | |
| # ===== نظام منع السبام (Rate Limiting) ===== | |
| user_request_times: dict[int, list] = defaultdict(list) | |
| user_warn_count: dict[int, int] = defaultdict(int) | |
| user_block_until: dict[int, float] = {} | |
| RATE_LIMIT_MAX = 5 # طلبات | |
| RATE_LIMIT_WINDOW = 60 # ثانية | |
| MAX_WARNS = 3 # تحذيرات قبل الحظر | |
| BLOCK_DURATION = 300 # 5 دقائق | |
| def check_rate_limit(user_id: int) -> tuple[bool, str]: | |
| """التحقق من حد الطلبات — يُعيد (مسموح، سبب الرفض)""" | |
| now = time.time() | |
| # فحص الحظر الزمني | |
| if user_id in user_block_until: | |
| if now < user_block_until[user_id]: | |
| remaining = int(user_block_until[user_id] - now) | |
| return False, f"أنت محظور مؤقتاً. حاول بعد {remaining} ثانية." | |
| else: | |
| del user_block_until[user_id] | |
| user_warn_count[user_id] = 0 | |
| # تنظيف الطلبات القديمة | |
| times = [t for t in user_request_times[user_id] if now - t < RATE_LIMIT_WINDOW] | |
| user_request_times[user_id] = times | |
| if len(times) >= RATE_LIMIT_MAX: | |
| user_warn_count[user_id] += 1 | |
| warns = user_warn_count[user_id] | |
| if warns >= MAX_WARNS: | |
| user_block_until[user_id] = now + BLOCK_DURATION | |
| user_warn_count[user_id] = 0 | |
| logger.warning(f"[BLOCK] User {user_id} blocked for {BLOCK_DURATION}s (spam)") | |
| return False, f"⛔ تم حظرك بسبب السبام. سيُرفع الحظر بعد {BLOCK_DURATION // 60} دقائق." | |
| return False, f"⚠️ أرسلت كثيراً من الطلبات. انتظر قليلاً. (تحذير {warns}/{MAX_WARNS})" | |
| times.append(now) | |
| return True, "" | |
| # ===== XSS / Injection Protection ===== | |
| def sanitize_text(text: str) -> str: | |
| """تنظيف النصوص من أكواد خطيرة""" | |
| if not isinstance(text, str): | |
| return "" | |
| # إزالة HTML tags | |
| text = re.sub(r'<[^>]+>', '', text) | |
| # إزالة Javascript protocols | |
| text = re.sub(r'javascript\s*:', '', text, flags=re.IGNORECASE) | |
| # إزالة SQL injection patterns | |
| text = re.sub(r"(\b(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC|UNION|SCRIPT)\b)", '', text, flags=re.IGNORECASE) | |
| # تحديد الطول | |
| return text[:2000].strip() | |
| # ===== الاتصال بـ AI الموقع ===== | |
| async def call_felix_ai(prompt: str, user_id: int, username: str, name: str) -> str: | |
| """إرسال رسالة لـ AI والحصول على رد""" | |
| safe_prompt = sanitize_text(prompt) | |
| history = user_memories.get(user_id, []) | |
| messages = [{"role": msg["role"], "content": msg["content"]} for msg in history[-10:]] | |
| messages.append({"role": "user", "content": safe_prompt}) | |
| payload = { | |
| "messages": messages, | |
| "userContext": { | |
| "username": username[:50] if username else "unknown", | |
| "displayName": name[:50] if name else "مستخدم", | |
| "platform": "telegram" | |
| } | |
| } | |
| headers = { | |
| "Authorization": f"Bearer {SUPABASE_ANON_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| try: | |
| r = requests.post(AI_API_URL, json=payload, headers=headers, timeout=30) | |
| if r.status_code == 200: | |
| data = r.json() | |
| reply = sanitize_text(data.get("reply", "عذراً، لم أتمكن من الحصول على رد.")) | |
| # تحديث الذاكرة | |
| history.append({"role": "user", "content": safe_prompt}) | |
| history.append({"role": "assistant", "content": reply}) | |
| user_memories[user_id] = history[-15:] | |
| return reply | |
| logger.warning(f"AI API returned {r.status_code}: {r.text[:200]}") | |
| return "⚠️ نظام AI الموقع غير متاح حالياً. حاول مجدداً." | |
| except requests.Timeout: | |
| logger.error("AI API timeout") | |
| return "⏱️ انتهت مهلة الاتصال. حاول مجدداً." | |
| except Exception as e: | |
| logger.error(f"AI API error: {e}") | |
| return "⚠️ حدث خطأ غير متوقع." | |
| # ===== فحص المحتوى عبر AI ===== | |
| async def moderate_content(title=None, content=None, image_url=None, content_type="general") -> tuple[bool, str]: | |
| """فحص المحتوى للتأكد من ملاءمته""" | |
| headers = { | |
| "Authorization": f"Bearer {SUPABASE_ANON_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| payload = { | |
| "title": sanitize_text(title) if title else None, | |
| "content": sanitize_text(content) if content else None, | |
| "image_url": image_url, | |
| "type": content_type | |
| } | |
| try: | |
| r = requests.post(MODERATE_API_URL, json=payload, headers=headers, timeout=30) | |
| if r.status_code == 200: | |
| data = r.json() | |
| approved = data.get("approved", True) | |
| reason = data.get("reason", "سبب غير معروف") | |
| return approved, reason | |
| # في حال فشل API المراقبة نمرر الطلب (fail open) | |
| logger.warning(f"Moderation API returned {r.status_code}") | |
| return True, "تعذر الفحص" | |
| except Exception as e: | |
| logger.error(f"Moderation error: {e}") | |
| return True, "خطأ في الفحص" | |
| # ===== أوامر البوت ===== | |
| async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| user_memories[user.id] = [] # إعادة تعيين الذاكرة | |
| text = ( | |
| f"🛡️ *مرحباً بك في Felix AI v5.1*\n\n" | |
| f"أنا المساعد الذكي الرسمي لمنصة *Minecraft FX*.\n\n" | |
| f"✅ *ما الذي يمكنني فعله؟*\n" | |
| f"• البحث عن إضافات Bedrock والـ Mods\n" | |
| f"• الإجابة على أسئلة ماينكرافت\n" | |
| f"• فحص الصور لمنع المحتوى غير اللائق\n" | |
| f"• مساعدة المطورين بالتقنيات\n\n" | |
| f"اسألني أي سؤال! 🎮" | |
| ) | |
| await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN) | |
| async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| text = ( | |
| "📚 *قائمة الأوامر:*\n\n" | |
| "/start — إعادة تشغيل البوت\n" | |
| "/help — عرض هذه القائمة\n" | |
| "/clear — مسح ذاكرة المحادثة\n" | |
| "/mods — جلب أحدث الإضافات\n" | |
| "/bedrock — إضافات بيدروك\n\n" | |
| f"🌐 الموقع: {SITE_URL}" | |
| ) | |
| await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN) | |
| async def cmd_clear(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| user_memories[user.id] = [] | |
| await update.message.reply_text("✅ تم مسح ذاكرة المحادثة. يمكنك البدء من جديد!") | |
| async def cmd_mods(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text(f"🎮 استعرض أحدث الإضافات على الموقع:\n{SITE_URL}/browse") | |
| async def cmd_bedrock(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text(f"📦 استعرض إضافات Bedrock:\n{SITE_URL}/bedrock-addons") | |
| # ===== معالجة الصور ===== | |
| async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| allowed, reason = check_rate_limit(user.id) | |
| if not allowed: | |
| await update.message.reply_text(reason) | |
| return | |
| photo = update.message.photo[-1] | |
| file = await context.bot.get_file(photo.file_id) | |
| image_url = file.file_path | |
| caption = sanitize_text(update.message.caption or "صورة بدون وصف") | |
| await context.bot.send_chat_action(update.effective_chat.id, ChatAction.TYPING) | |
| # فحص الصورة | |
| is_approved, mod_reason = await moderate_content( | |
| title="فحص صورة تليجرام", | |
| content=caption, | |
| image_url=image_url, | |
| content_type="telegram_upload" | |
| ) | |
| if not is_approved: | |
| try: | |
| await update.message.delete() | |
| except Exception: | |
| pass # قد لا تكون للبوت صلاحية الحذف في كل الحالات | |
| await context.bot.send_message( | |
| chat_id=update.effective_chat.id, | |
| text=f"⚠️ *تم حجب الصورة!*\nالسبب: {mod_reason}", | |
| parse_mode=ParseMode.MARKDOWN | |
| ) | |
| logger.info(f"[MODERATION] Photo blocked for user {user.id}: {mod_reason}") | |
| return | |
| reply = await call_felix_ai(f"[صورة مرفقة مع وصف: {caption}]", user.id, user.username or "unknown", user.full_name) | |
| await update.message.reply_text(reply, parse_mode=ParseMode.MARKDOWN) | |
| # ===== معالجة الرسائل النصية ===== | |
| async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| user = update.effective_user | |
| raw_text = update.message.text or "" | |
| if not raw_text.strip(): | |
| return | |
| # فحص Rate Limit | |
| allowed, rate_reason = check_rate_limit(user.id) | |
| if not allowed: | |
| await update.message.reply_text(rate_reason) | |
| return | |
| text = sanitize_text(raw_text) | |
| await context.bot.send_chat_action(update.effective_chat.id, ChatAction.TYPING) | |
| # فحص المحتوى | |
| is_approved, mod_reason = await moderate_content(content=text, content_type="text_message") | |
| if not is_approved: | |
| try: | |
| await update.message.delete() | |
| except Exception: | |
| pass | |
| await context.bot.send_message( | |
| chat_id=user.id, | |
| text=f"⚠️ رسالتك تحتوي على محتوى مرفوض: {mod_reason}" | |
| ) | |
| logger.info(f"[MODERATION] Message blocked for user {user.id}: {mod_reason}") | |
| return | |
| reply = await call_felix_ai(text, user.id, user.username or "unknown", user.full_name) | |
| await update.message.reply_text(reply, parse_mode=ParseMode.MARKDOWN) | |
| # ===== إعداد Webhook ===== | |
| async def setup_webhook(app, webhook_url: str): | |
| """إعداد Webhook لبيئة الإنتاج""" | |
| try: | |
| await app.bot.set_webhook( | |
| url=webhook_url, | |
| allowed_updates=["message", "callback_query"], | |
| drop_pending_updates=True | |
| ) | |
| info = await app.bot.get_webhook_info() | |
| logger.info(f"Webhook set: {info.url} | Pending: {info.pending_update_count}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Failed to set webhook: {e}") | |
| return False | |
| async def remove_webhook(app): | |
| """إزالة Webhook والتحول لـ Polling""" | |
| try: | |
| await app.bot.delete_webhook(drop_pending_updates=True) | |
| logger.info("Webhook removed, using polling mode") | |
| except Exception as e: | |
| logger.error(f"Failed to remove webhook: {e}") | |
| # ===== نقطة الدخول الرئيسية ===== | |
| if __name__ == "__main__": | |
| logger.info("🚀 بدء تشغيل Felix Bot v5.1...") | |
| app = ( | |
| ApplicationBuilder() | |
| .token(TELEGRAM_TOKEN) | |
| .connect_timeout(10) | |
| .read_timeout(30) | |
| .write_timeout(30) | |
| .build() | |
| ) | |
| # تسجيل الأوامر | |
| app.add_handler(CommandHandler("start", cmd_start)) | |
| app.add_handler(CommandHandler("help", cmd_help)) | |
| app.add_handler(CommandHandler("clear", cmd_clear)) | |
| app.add_handler(CommandHandler("mods", cmd_mods)) | |
| app.add_handler(CommandHandler("bedrock", cmd_bedrock)) | |
| app.add_handler(MessageHandler(filters.PHOTO, handle_photo)) | |
| app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) | |
| if WEBHOOK_URL: | |
| # وضع الـ Webhook (للإنتاج) | |
| logger.info(f"تشغيل في وضع Webhook: {WEBHOOK_URL}") | |
| app.run_webhook( | |
| listen="0.0.0.0", | |
| port=int(os.getenv("PORT", 8080)), | |
| url_path=TELEGRAM_TOKEN, | |
| webhook_url=f"{WEBHOOK_URL}/{TELEGRAM_TOKEN}", | |
| drop_pending_updates=True, | |
| ) | |
| else: | |
| # وضع Polling (للتطوير) | |
| logger.info("تشغيل في وضع Polling (تطوير)...") | |
| app.run_polling(drop_pending_updates=True, allowed_updates=["message", "callback_query"]) | |