Homam1997 commited on
Commit
867f9a3
·
verified ·
1 Parent(s): 24681fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -45
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
- 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)
 
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)