Spaces:
Runtime error
Runtime error
File size: 9,313 Bytes
49ff754 867f9a3 52314a1 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 49ff754 3919a7d 867f9a3 3919a7d 49ff754 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 49ff754 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 867f9a3 52314a1 867f9a3 3919a7d 52314a1 867f9a3 3919a7d 867f9a3 3919a7d 9d98649 3919a7d 49ff754 3919a7d 867f9a3 3919a7d 867f9a3 3919a7d 49ff754 3919a7d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | 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()
|