Homam1997 commited on
Commit
3919a7d
ยท
verified ยท
1 Parent(s): 867f9a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -80
app.py CHANGED
@@ -1,15 +1,15 @@
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,
@@ -19,124 +19,227 @@ from telegram.ext import (
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)
 
1
  import os
2
  import re
 
 
3
  import logging
4
  import traceback
5
  import html
6
+ import asyncio
 
 
7
  from typing import Optional
8
  from dotenv import load_dotenv
9
+
10
+ # ุงู„ุญุฒู… ุงู„ุฃุณุงุณูŠุฉ
11
+ import motor.motor_asyncio
12
+ import google.generativeai as genai
13
  from telegram import Update, User, Sticker, ReplyKeyboardMarkup
14
  from telegram.ext import (
15
  ApplicationBuilder,
 
19
  filters,
20
  )
21
 
22
+ # --- ุงู„ุฅุนุฏุงุฏุงุช ุงู„ุฃูˆู„ูŠุฉ ---
23
  load_dotenv()
24
+ logging.basicConfig(
25
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
26
+ level=logging.INFO,
27
+ )
28
  logger = logging.getLogger(__name__)
29
 
30
+ # --- ุฅุนุฏุงุฏ ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ ---
31
+ GEMINI_KEY = os.getenv("GEMINI_API_KEY")
32
+ if GEMINI_KEY:
33
+ genai.configure(api_key=GEMINI_KEY)
34
+ # ุงุณุชุฎุฏุงู… ุงู„ุฅุตุฏุงุฑ ุงู„ุฃุญุฏุซ ุงู„ู…ุณุชู‚ุฑ
35
+ model = genai.GenerativeModel('gemini-1.5-flash')
36
+ else:
37
+ logger.warning("GEMINI_API_KEY missing. AI features will be disabled.")
38
+ model = None
39
 
40
+ # --- ุฅุนุฏุงุฏ ู‚ุงุนุฏุฉ ุงู„ุจูŠุงู†ุงุช ---
41
  MONGO_URI = os.getenv("MONGO_URI")
42
+ client = motor.motor_asyncio.AsyncIOMotorClient(
43
+ MONGO_URI,
44
+ serverSelectionTimeoutMS=5000,
45
+ maxPoolSize=10
46
+ )
47
  db = client["CyberZone_DB"]
48
  users_col = db["users"]
49
  stickers_col = db["stickers"]
50
 
51
+ # --- ุงู„ุซูˆุงุจุช ---
52
  BOT_DISPLAY_NAME = "CyberZone ID Inspector"
53
  ID_REGEX = re.compile(r"\b(\d{8,12})\b")
54
 
55
+ # ============================
56
+ # HELPERS (ุงู„ู…ุณุงุนุฏุงุช)
57
+ # ============================
58
+
59
+ def clean_markdown(text: str) -> str:
60
+ """ุชู†ุธูŠู ุงู„ุฑู…ูˆุฒ ุงู„ุชูŠ ุชูƒุณุฑ ุชู†ุณูŠู‚ Markdown ููŠ ุชู„ุบุฑุงู…"""
61
  if not text: return "N/A"
62
+ escape_chars = r'_*[]()~`>#+-=|{}.!'
63
+ return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', str(text))
64
 
65
+ def format_size(size_bytes: Optional[int]) -> str:
66
+ if not size_bytes: return "Unknown"
67
  for unit in ['B', 'KB', 'MB', 'GB']:
68
+ if size_bytes < 1024.0: return f"{size_bytes:.2f} {unit}"
69
+ size_bytes /= 1024.0
70
+ return f"{size_bytes:.2f} TB"
71
 
72
+ # ============================
73
+ # ERROR HANDLER (ุตุงุฆุฏ ุงู„ุฃุฎุทุงุก)
74
+ # ============================
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
77
+ logger.error("Exception while handling update:", exc_info=context.error)
 
 
 
 
 
 
78
 
79
+ # ุงุณุชุฎุฑุงุฌ ุงู„ุฎุทุฃ
80
+ tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
81
+ tb_string = "".join(tb_list)
82
+
83
+ ai_explanation = "AI Analysis is disabled."
84
+ if model:
85
+ try:
86
+ prompt = f"Explain this Python Telegram Bot error in Arabic briefly:\n{tb_string[-1000:]}"
87
+ response = await asyncio.to_thread(model.generate_content, prompt)
88
+ ai_explanation = response.text
89
+ except Exception as e:
90
+ ai_explanation = f"AI failed: {e}"
91
+
92
  admin_id = os.getenv("ADMIN_ID")
93
  if admin_id:
94
+ error_msg = (
95
+ f"๐Ÿšจ <b>Smart Error Report</b>\n\n"
96
+ f"โŒ <b>Error:</b> <code>{html.escape(str(context.error))}</code>\n\n"
97
+ f"๐Ÿค– <b>AI Analysis:</b>\n{ai_explanation}"
98
+ )
99
+ # ุชู‚ุณูŠู… ุงู„ุฑุณุงู„ุฉ ุฅุฐุง ูƒุงู†ุช ุทูˆูŠู„ุฉ ุฌุฏุงู‹
100
+ await context.bot.send_message(chat_id=int(admin_id), text=error_msg[:4000], parse_mode="HTML")
101
+
102
+ # ============================
103
+ # DB LOGIC (ุงู„ุชุนุงู…ู„ ู…ุน ุงู„ุจูŠุงู†ุงุช)
104
+ # ============================
105
+
106
+ async def store_user(user: Optional[User]):
107
+ if not user: return
108
+ await users_col.update_one(
109
+ {"_id": user.id},
110
+ {"$set": {
111
+ "username": user.username,
112
+ "first_name": user.first_name,
113
+ "last_name": user.last_name,
114
+ "premium": getattr(user, "is_premium", False),
115
+ }},
116
+ upsert=True
117
+ )
118
+
119
+ async def store_sticker(sticker: Optional[Sticker]):
120
+ if not sticker: return
121
+ st_type = "animated" if sticker.is_animated else "video" if sticker.is_video else "static"
122
+ await stickers_col.update_one(
123
+ {"_id": sticker.file_unique_id},
124
+ {"$set": {
125
+ "file_id": sticker.file_id,
126
+ "emoji": sticker.emoji,
127
+ "set_name": sticker.set_name,
128
+ "type": st_type,
129
+ }},
130
+ upsert=True
131
+ )
132
+
133
+ # ============================
134
+ # HANDLERS (ุงู„ุฃูˆุงู…ุฑ ูˆุงู„ู…ุนุงู„ุฌุฉ)
135
+ # ============================
136
+
137
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
138
+ await store_user(update.effective_user)
139
+ buttons = [["๐Ÿ” Inspector"], ["โ“ Help", "๐Ÿ‘จโ€๐Ÿ’ป Contact Developer"]]
140
+ await update.message.reply_text(
141
+ f"Welcome to **{BOT_DISPLAY_NAME}**",
142
+ parse_mode="Markdown",
143
+ reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
144
+ )
145
 
146
  async def inspector_message_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
147
  msg = update.effective_message
148
  uid = update.effective_user.id
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ if not msg or not context.bot_data.get("inspector_mode", {}).get(uid):
151
+ return
152
+
153
+ await store_user(update.effective_user)
154
+
155
+ # ุฑุณุงู„ุฉ ุงู„ู…ุนุงู„ุฌุฉ ุงู„ุชู„ู‚ุงุฆูŠุฉ ู„ู„ู…ู„ูุงุช ุงู„ูƒุจูŠุฑุฉ
156
+ status_msg = None
157
+ if any([msg.photo, msg.video, msg.document, msg.sticker, msg.location]):
158
+ status_msg = await msg.reply_text("โณ **Processing Metadata...**", parse_mode="Markdown")
159
+
160
+ try:
161
+ if msg.forward_origin:
162
+ await handle_forward(msg)
163
+ elif msg.sticker:
164
+ await store_sticker(msg.sticker)
165
+ await msg.reply_text(f"๐Ÿ™‚ **Sticker**\n**Set:** `{msg.sticker.set_name}`\n**ID:** `{msg.sticker.file_id}`", parse_mode="Markdown")
166
+ elif msg.photo:
167
+ p = msg.photo[-1]
168
+ await msg.reply_text(f"๐Ÿ“ท **Photo**\n**Res:** {p.width}x{p.height}\n**Size:** {format_size(p.file_size)}", parse_mode="Markdown")
169
+ elif msg.video:
170
+ v = msg.video
171
+ await msg.reply_text(f"๐ŸŽฌ **Video**\n**Duration:** {v.duration}s\n**Size:** {format_size(v.file_size)}", parse_mode="Markdown")
172
+ elif msg.text:
173
+ await handle_text_lookup(msg)
174
+ finally:
175
+ if status_msg: await status_msg.delete()
176
+
177
+ async def handle_forward(msg):
178
+ fwd = msg.forward_origin
179
+ info = "โŒ Unable to detect source."
180
+
181
+ if hasattr(fwd, 'sender_user') and fwd.sender_user:
182
+ u = fwd.sender_user
183
+ await store_user(u)
184
+ info = f"๐Ÿ‘ค **User**\n**ID:** `{u.id}`\n**Name:** {clean_markdown(u.full_name)}\n**User:** @{clean_markdown(u.username)}"
185
+ elif hasattr(fwd, 'sender_user_name'):
186
+ info = f"๐Ÿ•ต๏ธ **Hidden User**\n**Name:** `{clean_markdown(fwd.sender_user_name)}`"
187
+ elif hasattr(fwd, 'chat') and fwd.chat:
188
+ c = fwd.chat
189
+ info = f"๐Ÿ“ข **Channel/Chat**\n**ID:** `{c.id}`\n**Title:** {clean_markdown(c.title)}\n**Link:** @{clean_markdown(c.username)}"
190
+
191
+ await msg.reply_text(info, parse_mode="Markdown")
192
+
193
+ async def handle_text_lookup(msg):
194
+ if msg.text.startswith("@"):
195
+ username = msg.text[1:].split()[0]
196
+ data = await users_col.find_one({"username": username})
197
+ else:
198
+ match = ID_REGEX.search(msg.text)
199
+ data = await users_col.find_one({"_id": int(match.group(1))}) if match else None
200
+
201
+ if data:
202
+ name = clean_markdown(f"{data.get('first_name', '')} {data.get('last_name', '')}")
203
+ res = f"๐Ÿ†” **Result**\n**ID:** `{data['_id']}`\n**Name:** {name}\n**User:** @{data.get('username', 'N/A')}"
204
+ else:
205
+ res = "โŒ No record found in CyberZone Cloud DB."
206
+ await msg.reply_text(res, parse_mode="Markdown")
207
 
208
  async def keyboard_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
209
  text = update.message.text
210
  uid = update.effective_user.id
211
  context.bot_data.setdefault("inspector_mode", {})
212
+
213
  if text == "๐Ÿ” Inspector":
214
  context.bot_data["inspector_mode"][uid] = True
215
+ await update.message.reply_text("๐Ÿ” **Mode: ON**\nSend anything to inspect.",
216
+ reply_markup=ReplyKeyboardMarkup([["๐Ÿ”™ Back"]], resize_keyboard=True))
217
  elif text == "๐Ÿ”™ Back":
218
  context.bot_data["inspector_mode"][uid] = False
219
+ await update.message.reply_text("โœ… **Mode: OFF**", reply_markup=main_menu_keyboard())
220
+ elif text == "โ“ Help":
221
+ await update.message.reply_text("๐Ÿ•ต๏ธ **How to use:**\n1. Enable Inspector.\n2. Forward any message or send media.\n3. Get hidden IDs and Metadata.")
222
+ elif text == "๐Ÿ‘จโ€๐Ÿ’ป Contact Developer":
223
+ await update.message.reply_text("๐Ÿค– **Dev:** @CyberZone_Admin\n*Powered by Gemini AI*")
224
+
225
+ # ============================
226
+ # RUN (ุงู„ุชุดุบูŠู„)
227
+ # ============================
228
 
229
+ def main():
 
230
  token = os.getenv("BOT_TOKEN")
231
+ if not token: raise ValueError("BOT_TOKEN not found!")
 
232
 
233
  app = ApplicationBuilder().token(token).build()
234
+
235
+ # ุงู„ุชุณุฌูŠู„
236
  app.add_error_handler(error_handler)
237
  app.add_handler(CommandHandler("start", start))
238
  app.add_handler(MessageHandler(filters.TEXT & filters.Regex(r"^(๐Ÿ” Inspector|๐Ÿ”™ Back|โ“ Help|๐Ÿ‘จโ€๐Ÿ’ป Contact Developer)$"), keyboard_handler))
239
  app.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, inspector_message_handler))
240
 
241
+ print(f"๐Ÿš€ {BOT_DISPLAY_NAME} is active...")
242
+ app.run_polling(drop_pending_updates=True)
 
 
 
 
 
 
 
 
243
 
244
  if __name__ == "__main__":
245
+ main()