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('')
@flask_app.route('/')
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"🚨 Smart Error Report\n\n❌ Error: {html.escape(str(context.error))}\n\n🤖 AI Analysis:\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()