Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,63 +1,142 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import asyncio
|
| 3 |
import threading
|
| 4 |
import logging
|
|
|
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# 1. إعداد الت
|
| 10 |
-
|
|
|
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
|
| 19 |
-
)
|
| 20 |
|
| 21 |
-
async def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
text = update.message.text
|
|
|
|
|
|
|
| 23 |
if text == "🔍 Inspector":
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
def run_telegram_bot():
|
| 31 |
token = os.getenv("BOT_TOKEN")
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
# تشغيل واجهة الويب (إلزامي في Hugging Face Gradio)
|
| 62 |
-
demo = web_interface()
|
| 63 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import re
|
| 3 |
import asyncio
|
| 4 |
import threading
|
| 5 |
import logging
|
| 6 |
+
import traceback
|
| 7 |
+
import html
|
| 8 |
import gradio as gr
|
| 9 |
+
import motor.motor_asyncio
|
| 10 |
+
import google.generativeai as genai
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
from telegram import Update, User, Sticker, ReplyKeyboardMarkup
|
| 14 |
+
from telegram.ext import (
|
| 15 |
+
ApplicationBuilder,
|
| 16 |
+
CommandHandler,
|
| 17 |
+
MessageHandler,
|
| 18 |
+
ContextTypes,
|
| 19 |
+
filters,
|
| 20 |
+
)
|
| 21 |
|
| 22 |
+
# 1. الإعدادات والتحميل
|
| 23 |
+
load_dotenv()
|
| 24 |
+
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
|
| 25 |
logger = logging.getLogger(__name__)
|
| 26 |
|
| 27 |
+
# إعداد Gemini
|
| 28 |
+
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 29 |
+
gemini_model = genai.GenerativeModel('gemini-1.5-flash-latest')
|
| 30 |
+
|
| 31 |
+
# إعداد MongoDB
|
| 32 |
+
MONGO_URI = os.getenv("MONGO_URI")
|
| 33 |
+
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URI)
|
| 34 |
+
db = client["CyberZone_DB"]
|
| 35 |
+
users_col = db["users"]
|
| 36 |
+
stickers_col = db["stickers"]
|
| 37 |
+
|
| 38 |
+
BOT_DISPLAY_NAME = "CyberZone ID Inspector"
|
| 39 |
+
ID_REGEX = re.compile(r"\b(\d{8,12})\b")
|
| 40 |
+
|
| 41 |
+
# --- 2. دوال المساعدة وفلترة النصوص ---
|
| 42 |
+
def clean_md(text):
|
| 43 |
+
if not text: return "N/A"
|
| 44 |
+
return str(text).replace("_", "\\_").replace("*", "\\*").replace("`", "\\`")
|
| 45 |
+
|
| 46 |
+
def format_size(size_in_bytes: Optional[int]) -> str:
|
| 47 |
+
if size_in_bytes is None: return "Unknown"
|
| 48 |
+
for unit in ['B', 'KB', 'MB', 'GB']:
|
| 49 |
+
if size_in_bytes < 1024.0: return f"{size_in_bytes:.2f} {unit}"
|
| 50 |
+
size_in_bytes /= 1024.0
|
| 51 |
+
return f"{size_in_bytes:.2f} TB"
|
| 52 |
+
|
| 53 |
+
# --- 3. منطق قاعدة البيانات ---
|
| 54 |
+
async def store_user(user: Optional[User]):
|
| 55 |
+
if not user: return
|
| 56 |
+
user_data = {
|
| 57 |
+
"username": user.username,
|
| 58 |
+
"first_name": user.first_name,
|
| 59 |
+
"last_name": user.last_name,
|
| 60 |
+
"premium": getattr(user, "is_premium", False),
|
| 61 |
+
}
|
| 62 |
+
await users_col.update_one({"_id": user.id}, {"$set": user_data}, upsert=True)
|
| 63 |
+
|
| 64 |
+
# --- 4. معالجات الرسائل والبوت ---
|
| 65 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 66 |
+
await store_user(update.effective_user)
|
| 67 |
+
keyboard = ReplyKeyboardMarkup([["🔍 Inspector"], ["❓ Help", "👨💻 Contact Developer"]], resize_keyboard=True)
|
| 68 |
+
await update.message.reply_text(f"Welcome to **{BOT_DISPLAY_NAME}**", parse_mode="Markdown", reply_markup=keyboard)
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
| 71 |
+
logger.error("Error occurred:", exc_info=context.error)
|
| 72 |
+
tb_string = "".join(traceback.format_exception(None, context.error, context.error.__traceback__))
|
| 73 |
+
try:
|
| 74 |
+
response = gemini_model.generate_content(f"Explain this Telegram Bot error in Arabic:\n{tb_string[-1500:]}")
|
| 75 |
+
ai_explanation = response.text
|
| 76 |
+
except:
|
| 77 |
+
ai_explanation = "فشل Gemini في تحليل الخطأ."
|
| 78 |
+
|
| 79 |
+
admin_id = os.getenv("ADMIN_ID")
|
| 80 |
+
if admin_id:
|
| 81 |
+
error_msg = f"🚨 <b>تقرير خطأ ذكي</b>\n\n❌ <b>الخطأ:</b> <code>{html.escape(str(context.error))}</code>\n\n🤖 <b>التحليل:</b>\n{ai_explanation}"
|
| 82 |
+
await context.bot.send_message(chat_id=int(admin_id), text=error_msg, parse_mode="HTML")
|
| 83 |
+
|
| 84 |
+
async def inspector_message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 85 |
+
msg = update.effective_message
|
| 86 |
+
uid = update.effective_user.id
|
| 87 |
+
if not msg or not context.bot_data.get("inspector_mode", {}).get(uid): return
|
| 88 |
+
|
| 89 |
+
# Forward Logic
|
| 90 |
+
if msg.forward_origin:
|
| 91 |
+
fwd = msg.forward_origin
|
| 92 |
+
if hasattr(fwd, 'sender_user') and fwd.sender_user:
|
| 93 |
+
user = fwd.sender_user
|
| 94 |
+
await msg.reply_text(f"👤 **User ID:** `{user.id}`\n**Name:** {clean_md(user.full_name)}\n**User:** @{clean_md(user.username)}", parse_mode="Markdown")
|
| 95 |
+
elif hasattr(fwd, 'chat') and fwd.chat:
|
| 96 |
+
chat = fwd.chat
|
| 97 |
+
await msg.reply_text(f"📢 **Channel ID:** `{chat.id}`\n**Title:** {clean_md(chat.title)}", parse_mode="Markdown")
|
| 98 |
+
|
| 99 |
+
# ID Detection in text
|
| 100 |
+
elif msg.text and ID_REGEX.search(msg.text):
|
| 101 |
+
target_id = ID_REGEX.search(msg.text).group(1)
|
| 102 |
+
await msg.reply_text(f"🆔 **Detected ID:** `{target_id}`", parse_mode="Markdown")
|
| 103 |
+
|
| 104 |
+
async def keyboard_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 105 |
text = update.message.text
|
| 106 |
+
uid = update.effective_user.id
|
| 107 |
+
context.bot_data.setdefault("inspector_mode", {})
|
| 108 |
if text == "🔍 Inspector":
|
| 109 |
+
context.bot_data["inspector_mode"][uid] = True
|
| 110 |
+
await update.message.reply_text("🔍 **Inspector Mode: ON**", reply_markup=ReplyKeyboardMarkup([["🔙 Back"]], resize_keyboard=True))
|
| 111 |
+
elif text == "🔙 Back":
|
| 112 |
+
context.bot_data["inspector_mode"][uid] = False
|
| 113 |
+
await update.message.reply_text("✅ **Mode: OFF**", reply_markup=ReplyKeyboardMarkup([["🔍 Inspector"], ["❓ Help"]], resize_keyboard=True))
|
| 114 |
|
| 115 |
+
# --- 5. تشغيل البوت (المعدل لـ Hugging Face) ---
|
| 116 |
def run_telegram_bot():
|
| 117 |
token = os.getenv("BOT_TOKEN")
|
| 118 |
+
loop = asyncio.new_event_loop()
|
| 119 |
+
asyncio.set_event_loop(loop)
|
| 120 |
+
|
| 121 |
+
app = ApplicationBuilder().token(token).build()
|
| 122 |
+
app.add_error_handler(error_handler)
|
| 123 |
+
app.add_handler(CommandHandler("start", start))
|
| 124 |
+
app.add_handler(MessageHandler(filters.TEXT & filters.Regex(r"^(🔍 Inspector|🔙 Back|❓ Help|👨💻 Contact Developer)$"), keyboard_handler))
|
| 125 |
+
app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, inspector_message_handler))
|
| 126 |
+
|
| 127 |
+
print("🚀 Bot is starting on background thread...")
|
| 128 |
+
app.run_polling(stop_signals=None)
|
| 129 |
+
|
| 130 |
+
# --- 6. واجهة Gradio ---
|
| 131 |
+
def web_ui():
|
| 132 |
+
with gr.Blocks() as demo:
|
| 133 |
+
gr.Markdown(f"# 🤖 {BOT_DISPLAY_NAME} Status")
|
| 134 |
+
gr.Markdown("### 🟢 Server is Running (Gradio Mode)")
|
| 135 |
+
gr.Markdown("This interface keeps the bot alive on Hugging Face.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
return demo
|
| 137 |
|
| 138 |
if __name__ == "__main__":
|
| 139 |
+
# تشغيل البوت في خيط منفصل
|
| 140 |
+
threading.Thread(target=run_telegram_bot, daemon=True).start()
|
| 141 |
+
# تشغيل الواجهة
|
| 142 |
+
web_ui().launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|