Spaces:
Runtime error
Runtime error
Download main.py from Homam1997/CyberZone_ID_Inspector: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/spaces/Homam1997/CyberZone_ID_Inspector/resolve/main/main.py
- Command line
-
hf download hf://spaces/Homam1997/CyberZone_ID_Inspector/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Homam1997/CyberZone_ID_Inspector/resolve/main/main.py
7.64 kB
| import os | |
| import re | |
| import logging | |
| import traceback | |
| import html | |
| import asyncio | |
| from typing import Optional | |
| from threading import Thread | |
| from flask import Flask | |
| 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, | |
| ) | |
| # --- 1. ุฅุนุฏุงุฏ Flask ูุถู ุงู ุงุณุชูุฑุงุฑ ุงูุงุณุชุถุงูุฉ --- | |
| flask_app = Flask('') | |
| def home(): | |
| return "CyberZone Bot is Online! ๐" | |
| def run_flask(): | |
| # Hugging Face ู Render ูุณุชุฎุฏู ูู ุงูู ููุฐ 7860 ุฃู PORT | |
| port = int(os.environ.get("PORT", 7860)) | |
| flask_app.run(host='0.0.0.0', port=port) | |
| def keep_alive(): | |
| t = Thread(target=run_flask) | |
| t.daemon = True | |
| t.start() | |
| # --- 2. ุงูุฅุนุฏุงุฏุงุช ูุงูุจูุฆุฉ --- | |
| load_dotenv() | |
| logging.basicConfig( | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| level=logging.INFO, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ุฅุนุฏุงุฏ Gemini | |
| 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 disabled.") | |
| model = None | |
| # ุฅุนุฏุงุฏ MongoDB | |
| MONGO_URI = os.getenv("MONGO_URI") | |
| client = motor.motor_asyncio.AsyncIOMotorClient( | |
| MONGO_URI, | |
| serverSelectionTimeoutMS=5000 | |
| ) | |
| 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") | |
| # --- 3. ุงูุฏูุงู ุงูู ุณุงุนุฏุฉ --- | |
| def clean_markdown(text: str) -> str: | |
| 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" | |
| # --- 4. ู ุนุงูุฌ ุงูุฃุฎุทุงุก ุงูุฐูู --- | |
| async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: | |
| logger.error("Exception:", exc_info=context.error) | |
| tb_string = "".join(traceback.format_exception(None, context.error, context.error.__traceback__)) | |
| ai_explanation = "AI Analysis is disabled." | |
| if model: | |
| try: | |
| prompt = f"Explain this 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โ <b>Error:</b> <code>{html.escape(str(context.error))}</code>\n\n๐ค <b>AI Analysis:</b>\n{ai_explanation}" | |
| await context.bot.send_message(chat_id=int(admin_id), text=error_msg[:4000], parse_mode="HTML") | |
| # --- 5. ู ูุทู ุงูุจูุงูุงุช --- | |
| 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 | |
| ) | |
| # --- 6. ู ุนุงูุฌุงุช ุงูุฑุณุงุฆู --- | |
| 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]): | |
| status_msg = await msg.reply_text("โณ **Processing Metadata...**", parse_mode="Markdown") | |
| try: | |
| if msg.forward_origin: | |
| fwd = msg.forward_origin | |
| 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, 'chat') and fwd.chat: | |
| c = fwd.chat | |
| info = f"๐ข **Channel**\n**ID:** `{c.id}`\n**Title:** {clean_markdown(c.title)}" | |
| else: | |
| info = "๐ต๏ธ **Hidden Source**" | |
| await msg.reply_text(info, 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.sticker: | |
| await msg.reply_text(f"๐ **Sticker**\n**Set:** `{msg.sticker.set_name}`\n**ID:** `{msg.sticker.file_id}`", parse_mode="Markdown") | |
| elif msg.text: | |
| match = ID_REGEX.search(msg.text) | |
| if match: | |
| target_id = int(match.group(1)) | |
| data = await users_col.find_one({"_id": target_id}) | |
| if data: | |
| res = f"๐ **DB Match**\n**ID:** `{target_id}`\n**Name:** {clean_markdown(data.get('first_name'))}" | |
| else: | |
| res = f"๐ **ID Detected:** `{target_id}`\n*(Not in DB)*" | |
| await msg.reply_text(res, parse_mode="Markdown") | |
| finally: | |
| if status_msg: await status_msg.delete() | |
| 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**", 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=ReplyKeyboardMarkup([["๐ Inspector"], ["โ Help", "๐จโ๐ป Contact Developer"]], resize_keyboard=True)) | |
| elif text == "๐จโ๐ป Contact Developer": | |
| await update.message.reply_text("๐ค **Dev:** @CyberZone_Admin") | |
| # --- 7. ุงูุชุดุบูู ุงูุฑุฆูุณู --- | |
| def main(): | |
| keep_alive() | |
| token = os.getenv("BOT_TOKEN") | |
| if not token: return | |
| 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("๐ Bot is running on Hugging Face...") | |
| app.run_polling(drop_pending_updates=True) | |
| if __name__ == "__main__": | |
| main() |