Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,144 +1,63 @@
|
|
| 1 |
import os
|
| 2 |
-
import re
|
| 3 |
-
import logging
|
| 4 |
-
import traceback
|
| 5 |
-
import html
|
| 6 |
import asyncio
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
|
| 12 |
-
# الحزم الأساسية
|
| 13 |
-
import motor.motor_asyncio
|
| 14 |
-
import google.generativeai as genai
|
| 15 |
-
from telegram import Update, User, ReplyKeyboardMarkup
|
| 16 |
-
from telegram.ext import (
|
| 17 |
-
ApplicationBuilder,
|
| 18 |
-
CommandHandler,
|
| 19 |
-
MessageHandler,
|
| 20 |
-
ContextTypes,
|
| 21 |
-
filters,
|
| 22 |
-
)
|
| 23 |
-
|
| 24 |
-
# --- 1. إعداد Flask والـ Webhook ---
|
| 25 |
-
flask_app = Flask(__name__)
|
| 26 |
-
application = None # سنقوم بتعريفه في main
|
| 27 |
-
|
| 28 |
-
@flask_app.route('/')
|
| 29 |
-
def home():
|
| 30 |
-
return "CyberZone Bot is Online via Webhook! 🚀"
|
| 31 |
-
|
| 32 |
-
@flask_app.route('/webhook', methods=['POST'])
|
| 33 |
-
async def webhook():
|
| 34 |
-
if application:
|
| 35 |
-
update = Update.de_json(request.get_json(force=True), application.bot)
|
| 36 |
-
await application.process_update(update)
|
| 37 |
-
return 'OK', 200
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
logging.basicConfig(level=logging.INFO)
|
| 42 |
logger = logging.getLogger(__name__)
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
GEMINI_KEY = os.getenv("GEMINI_API_KEY")
|
| 46 |
-
if GEMINI_KEY:
|
| 47 |
-
genai.configure(api_key=GEMINI_KEY)
|
| 48 |
-
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 49 |
-
else:
|
| 50 |
-
model = None
|
| 51 |
-
|
| 52 |
-
# إعداد MongoDB
|
| 53 |
-
MONGO_URI = os.getenv("MONGO_URI")
|
| 54 |
-
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
|
| 55 |
-
db = client["CyberZone_DB"]
|
| 56 |
-
users_col = db["users"]
|
| 57 |
-
|
| 58 |
-
BOT_DISPLAY_NAME = "CyberZone ID Inspector"
|
| 59 |
-
ID_REGEX = re.compile(r"\b(\d{8,12})\b")
|
| 60 |
-
|
| 61 |
-
# --- 3. الدوال المساعدة ---
|
| 62 |
-
def clean_markdown(text: str) -> str:
|
| 63 |
-
if not text: return "N/A"
|
| 64 |
-
escape_chars = r'_*[]()~`>#+-=|{}.!'
|
| 65 |
-
return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', str(text))
|
| 66 |
-
|
| 67 |
-
async def store_user(user: Optional[User]):
|
| 68 |
-
if not user: return
|
| 69 |
-
await users_col.update_one(
|
| 70 |
-
{"_id": user.id},
|
| 71 |
-
{"$set": {
|
| 72 |
-
"username": user.username,
|
| 73 |
-
"first_name": user.first_name,
|
| 74 |
-
"premium": getattr(user, "is_premium", False),
|
| 75 |
-
}},
|
| 76 |
-
upsert=True
|
| 77 |
-
)
|
| 78 |
-
|
| 79 |
-
# --- 4. معالجات الرسائل ---
|
| 80 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 81 |
-
|
| 82 |
-
buttons = [["🔍 Inspector"], ["👨💻 Contact Developer"]]
|
| 83 |
await update.message.reply_text(
|
| 84 |
-
|
| 85 |
-
parse_mode="Markdown",
|
| 86 |
reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
|
| 87 |
)
|
| 88 |
|
| 89 |
-
async def
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
await msg.reply_text("🔍 **Inspector Mode: ON**\nForward any message here.")
|
| 97 |
-
return
|
| 98 |
-
|
| 99 |
-
# منطق الفحص
|
| 100 |
-
if context.bot_data.get("mode", {}).get(uid):
|
| 101 |
-
if msg.forward_origin:
|
| 102 |
-
# فحص الرسائل المحولة
|
| 103 |
-
fwd = msg.forward_origin
|
| 104 |
-
info = "🕵️ Source Detected"
|
| 105 |
-
if hasattr(fwd, 'sender_user') and fwd.sender_user:
|
| 106 |
-
info = f"👤 **User ID:** `{fwd.sender_user.id}`\n**Name:** {fwd.sender_user.full_name}"
|
| 107 |
-
await msg.reply_text(info, parse_mode="Markdown")
|
| 108 |
-
elif msg.text and ID_REGEX.search(msg.text):
|
| 109 |
-
target_id = ID_REGEX.search(msg.text).group(1)
|
| 110 |
-
await msg.reply_text(f"🆔 **Found ID:** `{target_id}`", parse_mode="Markdown")
|
| 111 |
-
|
| 112 |
-
# --- 5. معالج الأخطاء ---
|
| 113 |
-
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 114 |
-
logger.error(f"Update {update} caused error {context.error}")
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
def
|
| 118 |
-
global application
|
| 119 |
token = os.getenv("BOT_TOKEN")
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
|
|
|
|
|
|
|
| 122 |
application = ApplicationBuilder().token(token).build()
|
| 123 |
-
|
|
|
|
| 124 |
application.add_handler(CommandHandler("start", start))
|
| 125 |
-
application.add_handler(MessageHandler(filters.
|
| 126 |
-
application.add_error_handler(error_handler)
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
else:
|
| 140 |
-
print("⚠️ SPACE_URL missing! Using Polling (might fail)...")
|
| 141 |
-
application.run_polling()
|
| 142 |
|
| 143 |
if __name__ == "__main__":
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import asyncio
|
| 3 |
+
import threading
|
| 4 |
+
import logging
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from telegram import Update, ReplyKeyboardMarkup
|
| 7 |
+
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# 1. إعداد التسجيل (Logs) لمراقبة الأخطاء
|
| 10 |
+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
|
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
+
# 2. دوال البوت الأساسية
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 15 |
+
buttons = [["🔍 Inspector"], ["👨💻 Contact"]]
|
|
|
|
| 16 |
await update.message.reply_text(
|
| 17 |
+
"👋 أهلاً بك في بوت الفحص!\n\nالسيرفر يعمل الآن بنجاح على بيئة Gradio.",
|
|
|
|
| 18 |
reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
|
| 19 |
)
|
| 20 |
|
| 21 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 22 |
+
text = update.message.text
|
| 23 |
+
if text == "🔍 Inspector":
|
| 24 |
+
await update.message.reply_text("🔎 أرسل الآن أي رسالة أو معرف (ID) لفحصه.")
|
| 25 |
+
else:
|
| 26 |
+
# هنا نضع منطق الفحص البسيط كمثال
|
| 27 |
+
await update.message.reply_text(f"📝 استلمت رسالتك: {text}\nجاري تحليل البيانات...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# 3. تشغيل البوت في Thread منفصل
|
| 30 |
+
def run_telegram_bot():
|
|
|
|
| 31 |
token = os.getenv("BOT_TOKEN")
|
| 32 |
+
if not token:
|
| 33 |
+
print("❌ Error: BOT_TOKEN not found in Secrets!")
|
| 34 |
+
return
|
| 35 |
|
| 36 |
+
# بناء التطبيق
|
| 37 |
+
# ملاحظة: استخدمنا محرك هادئ لتجنب بعض مشاكل الـ DNS عند الإقلاع
|
| 38 |
application = ApplicationBuilder().token(token).build()
|
| 39 |
+
|
| 40 |
+
# إضافة المعالجات
|
| 41 |
application.add_handler(CommandHandler("start", start))
|
| 42 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
|
|
|
| 43 |
|
| 44 |
+
print("🚀 البوت يحاول التشغيل الآن...")
|
| 45 |
+
application.run_polling(drop_pending_updates=True)
|
| 46 |
+
|
| 47 |
+
# 4. إعداد واجهة Gradio (للحفاظ على السبيس حياً)
|
| 48 |
+
def web_interface():
|
| 49 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 50 |
+
gr.Markdown("# 🤖 CyberZone Bot Status")
|
| 51 |
+
gr.info("إذا كانت هذه الصفحة تظهر لك، فالسيرفر يعمل.")
|
| 52 |
+
status = gr.Textbox(label="حالة السيرفر", value="Online ✅")
|
| 53 |
+
gr.Button("تحديث الحالة")
|
| 54 |
+
return demo
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
if __name__ == "__main__":
|
| 57 |
+
# تشغيل خيط البوت
|
| 58 |
+
bot_thread = threading.Thread(target=run_telegram_bot, daemon=True)
|
| 59 |
+
bot_thread.start()
|
| 60 |
+
|
| 61 |
+
# تشغيل واجهة الويب (إلزامي في Hugging Face Gradio)
|
| 62 |
+
demo = web_interface()
|
| 63 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|