Spaces:
Runtime error
Runtime error
Download app.py from Homam1997/inspector_CZ2: direct link, hf CLI and curl.
- Browser
- Download file 9.31 kB
-
https://huggingface.co/spaces/Homam1997/inspector_CZ2/resolve/main/app.py
- Command line
-
hf download hf://spaces/Homam1997/inspector_CZ2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Homam1997/inspector_CZ2/resolve/main/app.py
9.31 kB
| import os | |
| import re | |
| import logging | |
| import traceback | |
| import html | |
| import asyncio | |
| from typing import Optional | |
| from dotenv import load_dotenv | |
| # الحزم الأساسية | |
| import motor.motor_asyncio | |
| import google.generativeai as genai | |
| from telegram import Update, User, Sticker, ReplyKeyboardMarkup | |
| from telegram.ext import ( | |
| ApplicationBuilder, | |
| CommandHandler, | |
| MessageHandler, | |
| ContextTypes, | |
| filters, | |
| ) | |
| # --- الإعدادات الأولية --- | |
| load_dotenv() | |
| logging.basicConfig( | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| level=logging.INFO, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # --- إعداد الذكاء الاصطناعي --- | |
| GEMINI_KEY = os.getenv("GEMINI_API_KEY") | |
| if GEMINI_KEY: | |
| genai.configure(api_key=GEMINI_KEY) | |
| # استخدام الإصدار الأحدث المستقر | |
| model = genai.GenerativeModel('gemini-1.5-flash') | |
| else: | |
| logger.warning("GEMINI_API_KEY missing. AI features will be disabled.") | |
| model = None | |
| # --- إعداد قاعدة البيانات --- | |
| MONGO_URI = os.getenv("MONGO_URI") | |
| client = motor.motor_asyncio.AsyncIOMotorClient( | |
| MONGO_URI, | |
| serverSelectionTimeoutMS=5000, | |
| maxPoolSize=10 | |
| ) | |
| db = client["CyberZone_DB"] | |
| users_col = db["users"] | |
| stickers_col = db["stickers"] | |
| # --- الثوابت --- | |
| BOT_DISPLAY_NAME = "CyberZone ID Inspector" | |
| ID_REGEX = re.compile(r"\b(\d{8,12})\b") | |
| # ============================ | |
| # HELPERS (المساعدات) | |
| # ============================ | |
| def clean_markdown(text: str) -> str: | |
| """تنظيف الرموز التي تكسر تنسيق Markdown في تلغرام""" | |
| if not text: return "N/A" | |
| escape_chars = r'_*[]()~`>#+-=|{}.!' | |
| return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', str(text)) | |
| def format_size(size_bytes: Optional[int]) -> str: | |
| if not size_bytes: return "Unknown" | |
| for unit in ['B', 'KB', 'MB', 'GB']: | |
| if size_bytes < 1024.0: return f"{size_bytes:.2f} {unit}" | |
| size_bytes /= 1024.0 | |
| return f"{size_bytes:.2f} TB" | |
| # ============================ | |
| # ERROR HANDLER (صائد الأخطاء) | |
| # ============================ | |
| async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: | |
| logger.error("Exception while handling update:", exc_info=context.error) | |
| # استخراج الخطأ | |
| tb_list = traceback.format_exception(None, context.error, context.error.__traceback__) | |
| tb_string = "".join(tb_list) | |
| ai_explanation = "AI Analysis is disabled." | |
| if model: | |
| try: | |
| prompt = f"Explain this Python Telegram Bot error in Arabic briefly:\n{tb_string[-1000:]}" | |
| response = await asyncio.to_thread(model.generate_content, prompt) | |
| ai_explanation = response.text | |
| except Exception as e: | |
| ai_explanation = f"AI failed: {e}" | |
| admin_id = os.getenv("ADMIN_ID") | |
| if admin_id: | |
| error_msg = ( | |
| f"🚨 <b>Smart Error Report</b>\n\n" | |
| f"❌ <b>Error:</b> <code>{html.escape(str(context.error))}</code>\n\n" | |
| f"🤖 <b>AI Analysis:</b>\n{ai_explanation}" | |
| ) | |
| # تقسيم الرسالة إذا كانت طويلة جداً | |
| await context.bot.send_message(chat_id=int(admin_id), text=error_msg[:4000], parse_mode="HTML") | |
| # ============================ | |
| # DB LOGIC (التعامل مع البيانات) | |
| # ============================ | |
| async def store_user(user: Optional[User]): | |
| if not user: return | |
| await users_col.update_one( | |
| {"_id": user.id}, | |
| {"$set": { | |
| "username": user.username, | |
| "first_name": user.first_name, | |
| "last_name": user.last_name, | |
| "premium": getattr(user, "is_premium", False), | |
| }}, | |
| upsert=True | |
| ) | |
| async def store_sticker(sticker: Optional[Sticker]): | |
| if not sticker: return | |
| st_type = "animated" if sticker.is_animated else "video" if sticker.is_video else "static" | |
| await stickers_col.update_one( | |
| {"_id": sticker.file_unique_id}, | |
| {"$set": { | |
| "file_id": sticker.file_id, | |
| "emoji": sticker.emoji, | |
| "set_name": sticker.set_name, | |
| "type": st_type, | |
| }}, | |
| upsert=True | |
| ) | |
| # ============================ | |
| # HANDLERS (الأوامر والمعالجة) | |
| # ============================ | |
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await store_user(update.effective_user) | |
| buttons = [["🔍 Inspector"], ["❓ Help", "👨💻 Contact Developer"]] | |
| await update.message.reply_text( | |
| f"Welcome to **{BOT_DISPLAY_NAME}**", | |
| parse_mode="Markdown", | |
| reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True) | |
| ) | |
| async def inspector_message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| msg = update.effective_message | |
| uid = update.effective_user.id | |
| if not msg or not context.bot_data.get("inspector_mode", {}).get(uid): | |
| return | |
| await store_user(update.effective_user) | |
| # رسالة المعالجة التلقائية للملفات الكبيرة | |
| status_msg = None | |
| if any([msg.photo, msg.video, msg.document, msg.sticker, msg.location]): | |
| status_msg = await msg.reply_text("⏳ **Processing Metadata...**", parse_mode="Markdown") | |
| try: | |
| if msg.forward_origin: | |
| await handle_forward(msg) | |
| elif msg.sticker: | |
| await store_sticker(msg.sticker) | |
| await msg.reply_text(f"🙂 **Sticker**\n**Set:** `{msg.sticker.set_name}`\n**ID:** `{msg.sticker.file_id}`", parse_mode="Markdown") | |
| elif msg.photo: | |
| p = msg.photo[-1] | |
| await msg.reply_text(f"📷 **Photo**\n**Res:** {p.width}x{p.height}\n**Size:** {format_size(p.file_size)}", parse_mode="Markdown") | |
| elif msg.video: | |
| v = msg.video | |
| await msg.reply_text(f"🎬 **Video**\n**Duration:** {v.duration}s\n**Size:** {format_size(v.file_size)}", parse_mode="Markdown") | |
| elif msg.text: | |
| await handle_text_lookup(msg) | |
| finally: | |
| if status_msg: await status_msg.delete() | |
| async def handle_forward(msg): | |
| fwd = msg.forward_origin | |
| info = "❌ Unable to detect source." | |
| if hasattr(fwd, 'sender_user') and fwd.sender_user: | |
| u = fwd.sender_user | |
| await store_user(u) | |
| info = f"👤 **User**\n**ID:** `{u.id}`\n**Name:** {clean_markdown(u.full_name)}\n**User:** @{clean_markdown(u.username)}" | |
| elif hasattr(fwd, 'sender_user_name'): | |
| info = f"🕵️ **Hidden User**\n**Name:** `{clean_markdown(fwd.sender_user_name)}`" | |
| elif hasattr(fwd, 'chat') and fwd.chat: | |
| c = fwd.chat | |
| info = f"📢 **Channel/Chat**\n**ID:** `{c.id}`\n**Title:** {clean_markdown(c.title)}\n**Link:** @{clean_markdown(c.username)}" | |
| await msg.reply_text(info, parse_mode="Markdown") | |
| async def handle_text_lookup(msg): | |
| if msg.text.startswith("@"): | |
| username = msg.text[1:].split()[0] | |
| data = await users_col.find_one({"username": username}) | |
| else: | |
| match = ID_REGEX.search(msg.text) | |
| data = await users_col.find_one({"_id": int(match.group(1))}) if match else None | |
| if data: | |
| name = clean_markdown(f"{data.get('first_name', '')} {data.get('last_name', '')}") | |
| res = f"🆔 **Result**\n**ID:** `{data['_id']}`\n**Name:** {name}\n**User:** @{data.get('username', 'N/A')}" | |
| else: | |
| res = "❌ No record found in CyberZone Cloud DB." | |
| await msg.reply_text(res, parse_mode="Markdown") | |
| async def keyboard_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| text = update.message.text | |
| uid = update.effective_user.id | |
| context.bot_data.setdefault("inspector_mode", {}) | |
| if text == "🔍 Inspector": | |
| context.bot_data["inspector_mode"][uid] = True | |
| await update.message.reply_text("🔍 **Mode: ON**\nSend anything to inspect.", | |
| reply_markup=ReplyKeyboardMarkup([["🔙 Back"]], resize_keyboard=True)) | |
| elif text == "🔙 Back": | |
| context.bot_data["inspector_mode"][uid] = False | |
| await update.message.reply_text("✅ **Mode: OFF**", reply_markup=main_menu_keyboard()) | |
| elif text == "❓ Help": | |
| await update.message.reply_text("🕵️ **How to use:**\n1. Enable Inspector.\n2. Forward any message or send media.\n3. Get hidden IDs and Metadata.") | |
| elif text == "👨💻 Contact Developer": | |
| await update.message.reply_text("🤖 **Dev:** @CyberZone_Admin\n*Powered by Gemini AI*") | |
| # ============================ | |
| # RUN (التشغيل) | |
| # ============================ | |
| def main(): | |
| token = os.getenv("BOT_TOKEN") | |
| if not token: raise ValueError("BOT_TOKEN not found!") | |
| app = ApplicationBuilder().token(token).build() | |
| # التسجيل | |
| app.add_error_handler(error_handler) | |
| app.add_handler(CommandHandler("start", start)) | |
| app.add_handler(MessageHandler(filters.TEXT & filters.Regex(r"^(🔍 Inspector|🔙 Back|❓ Help|👨💻 Contact Developer)$"), keyboard_handler)) | |
| app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, inspector_message_handler)) | |
| print(f"🚀 {BOT_DISPLAY_NAME} is active...") | |
| app.run_polling(drop_pending_updates=True) | |
| if __name__ == "__main__": | |
| main() | |