Update bot.py
Browse files
bot.py
CHANGED
|
@@ -6,7 +6,7 @@ import threading
|
|
| 6 |
import aiosqlite
|
| 7 |
import gradio as gr
|
| 8 |
from hydrogram import Client, filters
|
| 9 |
-
from hydrogram.errors import FloodWait,
|
| 10 |
from hydrogram.types import (
|
| 11 |
InputMediaPhoto, InputMediaVideo, InputMediaDocument,
|
| 12 |
InputMediaAudio
|
|
@@ -14,6 +14,23 @@ from hydrogram.types import (
|
|
| 14 |
from fastapi import FastAPI
|
| 15 |
import uvicorn
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# ============ إعداد السجلات (Logging) ============
|
| 18 |
logging.basicConfig(
|
| 19 |
level=logging.INFO,
|
|
@@ -26,7 +43,6 @@ API_ID = int(os.environ.get("API_ID", 0))
|
|
| 26 |
API_HASH = os.environ.get("API_HASH", "")
|
| 27 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 28 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
| 29 |
-
# يمكنك وضع قنوات مفصولة بفواصل مثل: "@channel1, -100123456789, @channel2"
|
| 30 |
CHANNELS_TO_SCRAPE = os.environ.get("CHANNELS_TO_SCRAPE", "")
|
| 31 |
|
| 32 |
DATA_DIR = "/tmp/data" if not os.path.exists("/data") else "/data"
|
|
@@ -49,6 +65,8 @@ app = Client(
|
|
| 49 |
)
|
| 50 |
|
| 51 |
TARGET_CHAT = "me"
|
|
|
|
|
|
|
| 52 |
stats = {
|
| 53 |
"total_queued": 0,
|
| 54 |
"total_transferred": 0,
|
|
@@ -66,14 +84,12 @@ class RateLimiter:
|
|
| 66 |
|
| 67 |
async def wait(self):
|
| 68 |
async with self.lock:
|
| 69 |
-
# التحقق من وجود حظر FloodWait
|
| 70 |
now = time.time()
|
| 71 |
if self.flood_until > now:
|
| 72 |
wait_sec = self.flood_until - now
|
| 73 |
logger.warning(f"⏳ FloodWait فعال، انتظار {wait_sec:.1f} ثانية...")
|
| 74 |
await asyncio.sleep(wait_sec)
|
| 75 |
|
| 76 |
-
# التحقق من الفاصل الزمني العادي لتفادي الحظر
|
| 77 |
now = time.time()
|
| 78 |
elapsed = now - self.last_call
|
| 79 |
if elapsed < self.delay:
|
|
@@ -120,7 +136,6 @@ async def add_message_to_queue(message, album_info=None):
|
|
| 120 |
message_id = int(message.id)
|
| 121 |
media_group_id = str(message.media_group_id) if message.media_group_id else None
|
| 122 |
|
| 123 |
-
# تحديد نوع الميديا
|
| 124 |
media_type = "unknown"
|
| 125 |
if message.photo: media_type = "photo"
|
| 126 |
elif message.video: media_type = "video"
|
|
@@ -130,13 +145,10 @@ async def add_message_to_queue(message, album_info=None):
|
|
| 130 |
elif message.video_note: media_type = "video_note"
|
| 131 |
elif message.animation: media_type = "animation"
|
| 132 |
|
| 133 |
-
# اسم القناة أو المجموعة
|
| 134 |
chat = message.chat
|
| 135 |
source_name = chat.title or chat.first_name or chat.username or f"Chat_{chat_id}"
|
| 136 |
-
|
| 137 |
raw_caption = message.caption or ""
|
| 138 |
|
| 139 |
-
# تفاصيل الألبوم إن وجدت
|
| 140 |
album_total = 1
|
| 141 |
album_index = 1
|
| 142 |
if album_info:
|
|
@@ -183,7 +195,7 @@ async def process_single_job(job):
|
|
| 183 |
|
| 184 |
await rate_limiter.wait()
|
| 185 |
|
| 186 |
-
# 1. المحاولة الأولى: النسخ المباشر
|
| 187 |
try:
|
| 188 |
await app.copy_message(
|
| 189 |
chat_id=TARGET_CHAT,
|
|
@@ -194,17 +206,18 @@ async def process_single_job(job):
|
|
| 194 |
logger.info(f"⚡ تم النقل السريع بنجاح للرسالة {msg_id} من {source_name}")
|
| 195 |
return True
|
| 196 |
except (FloodWait, FloodPremiumWait) as e:
|
| 197 |
-
|
|
|
|
| 198 |
raise e
|
| 199 |
except ChatForwardsRestricted:
|
| 200 |
-
logger.warning(f"⚠️ القناة محمية المحتوى! ا
|
| 201 |
except MessageIdInvalid:
|
| 202 |
logger.error(f"❌ الرسالة {msg_id} محذوفة أو غير صالحة.")
|
| 203 |
return "DELETED"
|
| 204 |
except Exception as e:
|
| 205 |
logger.warning(f"⚠️ فشل النسخ المباشر للرسالة {msg_id} ({e})، جاري محاولة التحميل والرفع...")
|
| 206 |
|
| 207 |
-
# 2. المحاولة الثانية: التحميل والرفع
|
| 208 |
try:
|
| 209 |
msg = await app.get_messages(chat_id, msg_id)
|
| 210 |
if not msg or not msg.media:
|
|
@@ -216,7 +229,6 @@ async def process_single_job(job):
|
|
| 216 |
if not downloaded or not os.path.exists(downloaded):
|
| 217 |
raise Exception("فشل تنزيل الملف")
|
| 218 |
|
| 219 |
-
# إعادة الإرسال حسب النوع
|
| 220 |
mtype = job["media_type"]
|
| 221 |
if mtype == "photo":
|
| 222 |
await app.send_photo(TARGET_CHAT, photo=downloaded, caption=caption)
|
|
@@ -235,14 +247,14 @@ async def process_single_job(job):
|
|
| 235 |
else:
|
| 236 |
await app.send_document(TARGET_CHAT, document=downloaded, caption=caption)
|
| 237 |
|
| 238 |
-
# تنظيف الملف المؤقت فوراً لتوفير المساحة
|
| 239 |
if os.path.exists(downloaded):
|
| 240 |
os.remove(downloaded)
|
| 241 |
|
| 242 |
logger.info(f"📥 تم التحميل والرفع بنجاح للرسالة {msg_id}")
|
| 243 |
return True
|
| 244 |
except (FloodWait, FloodPremiumWait) as e:
|
| 245 |
-
|
|
|
|
| 246 |
raise e
|
| 247 |
except Exception as e:
|
| 248 |
logger.error(f"❌ فشل تام في معالجة الرسالة {msg_id}: {e}")
|
|
@@ -276,7 +288,6 @@ async def queue_worker():
|
|
| 276 |
await db.execute("UPDATE jobs SET status='processing' WHERE id=?", (job_id,))
|
| 277 |
await db.commit()
|
| 278 |
|
| 279 |
-
# المعالجة
|
| 280 |
result = await process_single_job(job)
|
| 281 |
|
| 282 |
async with aiosqlite.connect(DB_PATH) as db:
|
|
@@ -293,17 +304,15 @@ async def queue_worker():
|
|
| 293 |
await db.commit()
|
| 294 |
|
| 295 |
except (FloodWait, FloodPremiumWait) as e:
|
| 296 |
-
|
| 297 |
-
|
|
|
|
| 298 |
except Exception as e:
|
| 299 |
logger.error(f"خطأ غير متوقع في الـ Worker: {e}")
|
| 300 |
await asyncio.sleep(5)
|
| 301 |
|
| 302 |
# ============ ماسح الرسائل القديمة (History Scraper) ============
|
| 303 |
async def scrape_channel_history(chat_identifier, limit=0):
|
| 304 |
-
"""
|
| 305 |
-
يقوم بجلب كافة الرسائل القديمة من قناة أو مجموعة وترتيبها في الطابور
|
| 306 |
-
"""
|
| 307 |
try:
|
| 308 |
chat = await app.get_chat(chat_identifier)
|
| 309 |
chat_id = chat.id
|
|
@@ -313,10 +322,8 @@ async def scrape_channel_history(chat_identifier, limit=0):
|
|
| 313 |
count = 0
|
| 314 |
media_groups = {}
|
| 315 |
|
| 316 |
-
# قراءة الأرشيف من الأقدم للأحدث أو من الأحدث للأقدم
|
| 317 |
async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0):
|
| 318 |
if message.media:
|
| 319 |
-
# إذا كان ألبوم
|
| 320 |
if message.media_group_id:
|
| 321 |
mg_id = str(message.media_group_id)
|
| 322 |
media_groups.setdefault(mg_id, []).append(message)
|
|
@@ -328,9 +335,7 @@ async def scrape_channel_history(chat_identifier, limit=0):
|
|
| 328 |
logger.info(f"📦 تم جدولة {count} رسالة من {chat_title}...")
|
| 329 |
await asyncio.sleep(0.1)
|
| 330 |
|
| 331 |
-
# إضافة الألبومات مع حساب عدد المقاطع لكل ألبوم
|
| 332 |
for mg_id, msgs in media_groups.items():
|
| 333 |
-
# ترتيب رسائل الألبوم بالترتيب الزمني الصحيح
|
| 334 |
msgs.sort(key=lambda m: m.id)
|
| 335 |
total = len(msgs)
|
| 336 |
for idx, msg in enumerate(msgs, start=1):
|
|
@@ -347,12 +352,10 @@ async def scrape_channel_history(chat_identifier, limit=0):
|
|
| 347 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 348 |
async def realtime_media_handler(client, message):
|
| 349 |
try:
|
| 350 |
-
# تجنب رصد الرسائل التي ترسلها الوجهة
|
| 351 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 352 |
return
|
| 353 |
|
| 354 |
if message.media_group_id:
|
| 355 |
-
# إذا كان ألبوم، انتظر ثانية واحدة لتكتمل حزمة الألبوم ثم جدولها
|
| 356 |
await asyncio.sleep(1.5)
|
| 357 |
try:
|
| 358 |
group_messages = await client.get_media_group(message.chat.id, message.id)
|
|
@@ -361,7 +364,6 @@ async def realtime_media_handler(client, message):
|
|
| 361 |
for idx, msg in enumerate(group_messages, start=1):
|
| 362 |
await add_message_to_queue(msg, album_info={"total": total, "index": idx})
|
| 363 |
except Exception:
|
| 364 |
-
# إذا فشل جلب المجموعة كاملة، أضف الرسالة مفردة
|
| 365 |
await add_message_to_queue(message)
|
| 366 |
else:
|
| 367 |
await add_message_to_queue(message)
|
|
@@ -392,13 +394,13 @@ async def resolve_target():
|
|
| 392 |
logger.error(f"فشل التحقق من الوجهة ({raw}): {e}. تم التحويل للرسائل المحفوظة.")
|
| 393 |
TARGET_CHAT = "me"
|
| 394 |
|
| 395 |
-
# ============ واجهة
|
| 396 |
def create_ui():
|
| 397 |
with gr.Blocks(title="Telegram Archiver Pro") as demo:
|
| 398 |
gr.Markdown("## 🚀 محول وأرشيف تيليجرام الاحترافي (بدون ضياع ملفات)")
|
| 399 |
|
| 400 |
with gr.Row():
|
| 401 |
-
status_box = gr.Textbox(label="حالة النظام", value="
|
| 402 |
queued_box = gr.Number(label="الملفات في الطابور", value=0, interactive=False)
|
| 403 |
transferred_box = gr.Number(label="الملفات المنقولة بنجاح", value=0, interactive=False)
|
| 404 |
|
|
@@ -407,72 +409,28 @@ def create_ui():
|
|
| 407 |
with gr.Row():
|
| 408 |
channel_input = gr.Textbox(
|
| 409 |
label="معرف أو رابط القناة / الكروب",
|
| 410 |
-
placeholder="@my_channel أو -100123456789
|
| 411 |
)
|
| 412 |
limit_input = gr.Number(label="أقصى عدد رسائل (0 = الكل)", value=0)
|
| 413 |
scrape_btn = gr.Button("بدء السحب الآن 📥", variant="primary")
|
| 414 |
|
| 415 |
-
scrape_output = gr.Textbox(label="
|
| 416 |
|
| 417 |
def do_scrape(ch, lim):
|
| 418 |
if not ch:
|
| 419 |
return "يرجى كتابة معرف القناة أولاً"
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
scrape_btn.click(fn=do_scrape, inputs=[channel_input, limit_input], outputs=[scrape_output])
|
| 426 |
|
| 427 |
return demo
|
| 428 |
|
| 429 |
-
# ============ تشغيل
|
| 430 |
def run_web():
|
| 431 |
-
|
| 432 |
-
demo = create_ui()
|
| 433 |
-
gr.mount_gradio_app(fastapi_app, demo, path="/")
|
| 434 |
-
|
| 435 |
-
@fastapi_app.get("/ping")
|
| 436 |
-
async def ping():
|
| 437 |
-
return {"status": "alive", "stats": stats}
|
| 438 |
-
|
| 439 |
-
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
| 440 |
-
|
| 441 |
-
async def main():
|
| 442 |
-
logger.info("جاري تسجيل الدخول إلى تيليجرام...")
|
| 443 |
-
await app.start()
|
| 444 |
-
|
| 445 |
-
me = await app.get_me()
|
| 446 |
-
logger.info(f"✅ تم الدخول بحساب: {me.first_name} (@{me.username or me.id})")
|
| 447 |
-
|
| 448 |
-
await resolve_target()
|
| 449 |
-
await init_db()
|
| 450 |
-
|
| 451 |
-
# تشغيل العامل في الخلفية
|
| 452 |
-
asyncio.create_task(queue_worker())
|
| 453 |
-
|
| 454 |
-
# فحص القنوات المحددة في المتغيرات البيئية إن وجدت
|
| 455 |
-
if CHANNELS_TO_SCRAPE:
|
| 456 |
-
channels = [c.strip() for c in CHANNELS_TO_SCRAPE.split(",") if c.strip()]
|
| 457 |
-
for ch in channels:
|
| 458 |
-
asyncio.create_task(scrape_channel_history(ch))
|
| 459 |
-
|
| 460 |
-
stats["status"] = "يعمل بكفاءة ✅"
|
| 461 |
-
|
| 462 |
-
# الإبقاء قيد التشغيل
|
| 463 |
-
stop_event = asyncio.Event()
|
| 464 |
-
await stop_event.wait()
|
| 465 |
-
|
| 466 |
-
if __name__ == "__main__":
|
| 467 |
-
# تشغيل واجهة الويب في Thread مستقل لمنع تعليق البوت وتلبية متطلبات Hugging Face
|
| 468 |
-
web_thread = threading.Thread(target=run_web, daemon=True)
|
| 469 |
-
web_thread.start()
|
| 470 |
-
|
| 471 |
-
loop = asyncio.get_event_loop()
|
| 472 |
-
try:
|
| 473 |
-
loop.run_until_complete(main())
|
| 474 |
-
except KeyboardInterrupt:
|
| 475 |
-
pass
|
| 476 |
-
finally:
|
| 477 |
-
if app.is_connected:
|
| 478 |
-
loop.run_until_complete(app.stop())
|
|
|
|
| 6 |
import aiosqlite
|
| 7 |
import gradio as gr
|
| 8 |
from hydrogram import Client, filters
|
| 9 |
+
from hydrogram.errors import FloodWait, RPCError
|
| 10 |
from hydrogram.types import (
|
| 11 |
InputMediaPhoto, InputMediaVideo, InputMediaDocument,
|
| 12 |
InputMediaAudio
|
|
|
|
| 14 |
from fastapi import FastAPI
|
| 15 |
import uvicorn
|
| 16 |
|
| 17 |
+
# ============ حل مشكلة استيراد الأخطاء غير الموجودة بأمان ============
|
| 18 |
+
try:
|
| 19 |
+
from hydrogram.errors import FloodPremiumWait
|
| 20 |
+
except ImportError:
|
| 21 |
+
class FloodPremiumWait(FloodWait):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
from hydrogram.errors import ChatForwardsRestricted
|
| 26 |
+
except ImportError:
|
| 27 |
+
ChatForwardsRestricted = RPCError
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from hydrogram.errors import MessageIdInvalid
|
| 31 |
+
except ImportError:
|
| 32 |
+
MessageIdInvalid = RPCError
|
| 33 |
+
|
| 34 |
# ============ إعداد السجلات (Logging) ============
|
| 35 |
logging.basicConfig(
|
| 36 |
level=logging.INFO,
|
|
|
|
| 43 |
API_HASH = os.environ.get("API_HASH", "")
|
| 44 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 45 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
|
|
|
| 46 |
CHANNELS_TO_SCRAPE = os.environ.get("CHANNELS_TO_SCRAPE", "")
|
| 47 |
|
| 48 |
DATA_DIR = "/tmp/data" if not os.path.exists("/data") else "/data"
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
TARGET_CHAT = "me"
|
| 68 |
+
MAIN_LOOP = None
|
| 69 |
+
|
| 70 |
stats = {
|
| 71 |
"total_queued": 0,
|
| 72 |
"total_transferred": 0,
|
|
|
|
| 84 |
|
| 85 |
async def wait(self):
|
| 86 |
async with self.lock:
|
|
|
|
| 87 |
now = time.time()
|
| 88 |
if self.flood_until > now:
|
| 89 |
wait_sec = self.flood_until - now
|
| 90 |
logger.warning(f"⏳ FloodWait فعال، انتظار {wait_sec:.1f} ثانية...")
|
| 91 |
await asyncio.sleep(wait_sec)
|
| 92 |
|
|
|
|
| 93 |
now = time.time()
|
| 94 |
elapsed = now - self.last_call
|
| 95 |
if elapsed < self.delay:
|
|
|
|
| 136 |
message_id = int(message.id)
|
| 137 |
media_group_id = str(message.media_group_id) if message.media_group_id else None
|
| 138 |
|
|
|
|
| 139 |
media_type = "unknown"
|
| 140 |
if message.photo: media_type = "photo"
|
| 141 |
elif message.video: media_type = "video"
|
|
|
|
| 145 |
elif message.video_note: media_type = "video_note"
|
| 146 |
elif message.animation: media_type = "animation"
|
| 147 |
|
|
|
|
| 148 |
chat = message.chat
|
| 149 |
source_name = chat.title or chat.first_name or chat.username or f"Chat_{chat_id}"
|
|
|
|
| 150 |
raw_caption = message.caption or ""
|
| 151 |
|
|
|
|
| 152 |
album_total = 1
|
| 153 |
album_index = 1
|
| 154 |
if album_info:
|
|
|
|
| 195 |
|
| 196 |
await rate_limiter.wait()
|
| 197 |
|
| 198 |
+
# 1. المحاولة الأولى: النسخ المباشر السريع من السيرفر
|
| 199 |
try:
|
| 200 |
await app.copy_message(
|
| 201 |
chat_id=TARGET_CHAT,
|
|
|
|
| 206 |
logger.info(f"⚡ تم النقل السريع بنجاح للرسالة {msg_id} من {source_name}")
|
| 207 |
return True
|
| 208 |
except (FloodWait, FloodPremiumWait) as e:
|
| 209 |
+
wait_val = getattr(e, 'value', 30)
|
| 210 |
+
rate_limiter.set_flood(wait_val)
|
| 211 |
raise e
|
| 212 |
except ChatForwardsRestricted:
|
| 213 |
+
logger.warning(f"⚠️ القناة محمية المحتوى! جاري التحميل والرفع للرسالة {msg_id}...")
|
| 214 |
except MessageIdInvalid:
|
| 215 |
logger.error(f"❌ الرسالة {msg_id} محذوفة أو غير صالحة.")
|
| 216 |
return "DELETED"
|
| 217 |
except Exception as e:
|
| 218 |
logger.warning(f"⚠️ فشل النسخ المباشر للرسالة {msg_id} ({e})، جاري محاولة التحميل والرفع...")
|
| 219 |
|
| 220 |
+
# 2. المحاولة الثانية: التحميل والرفع
|
| 221 |
try:
|
| 222 |
msg = await app.get_messages(chat_id, msg_id)
|
| 223 |
if not msg or not msg.media:
|
|
|
|
| 229 |
if not downloaded or not os.path.exists(downloaded):
|
| 230 |
raise Exception("فشل تنزيل الملف")
|
| 231 |
|
|
|
|
| 232 |
mtype = job["media_type"]
|
| 233 |
if mtype == "photo":
|
| 234 |
await app.send_photo(TARGET_CHAT, photo=downloaded, caption=caption)
|
|
|
|
| 247 |
else:
|
| 248 |
await app.send_document(TARGET_CHAT, document=downloaded, caption=caption)
|
| 249 |
|
|
|
|
| 250 |
if os.path.exists(downloaded):
|
| 251 |
os.remove(downloaded)
|
| 252 |
|
| 253 |
logger.info(f"📥 تم التحميل والرفع بنجاح للرسالة {msg_id}")
|
| 254 |
return True
|
| 255 |
except (FloodWait, FloodPremiumWait) as e:
|
| 256 |
+
wait_val = getattr(e, 'value', 30)
|
| 257 |
+
rate_limiter.set_flood(wait_val)
|
| 258 |
raise e
|
| 259 |
except Exception as e:
|
| 260 |
logger.error(f"❌ فشل تام في معالجة الرسالة {msg_id}: {e}")
|
|
|
|
| 288 |
await db.execute("UPDATE jobs SET status='processing' WHERE id=?", (job_id,))
|
| 289 |
await db.commit()
|
| 290 |
|
|
|
|
| 291 |
result = await process_single_job(job)
|
| 292 |
|
| 293 |
async with aiosqlite.connect(DB_PATH) as db:
|
|
|
|
| 304 |
await db.commit()
|
| 305 |
|
| 306 |
except (FloodWait, FloodPremiumWait) as e:
|
| 307 |
+
wait_val = getattr(e, 'value', 30)
|
| 308 |
+
logger.warning(f"انتظار FloodWait: {wait_val}s")
|
| 309 |
+
await asyncio.sleep(wait_val + 1)
|
| 310 |
except Exception as e:
|
| 311 |
logger.error(f"خطأ غير متوقع في الـ Worker: {e}")
|
| 312 |
await asyncio.sleep(5)
|
| 313 |
|
| 314 |
# ============ ماسح الرسائل القديمة (History Scraper) ============
|
| 315 |
async def scrape_channel_history(chat_identifier, limit=0):
|
|
|
|
|
|
|
|
|
|
| 316 |
try:
|
| 317 |
chat = await app.get_chat(chat_identifier)
|
| 318 |
chat_id = chat.id
|
|
|
|
| 322 |
count = 0
|
| 323 |
media_groups = {}
|
| 324 |
|
|
|
|
| 325 |
async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0):
|
| 326 |
if message.media:
|
|
|
|
| 327 |
if message.media_group_id:
|
| 328 |
mg_id = str(message.media_group_id)
|
| 329 |
media_groups.setdefault(mg_id, []).append(message)
|
|
|
|
| 335 |
logger.info(f"📦 تم جدولة {count} رسالة من {chat_title}...")
|
| 336 |
await asyncio.sleep(0.1)
|
| 337 |
|
|
|
|
| 338 |
for mg_id, msgs in media_groups.items():
|
|
|
|
| 339 |
msgs.sort(key=lambda m: m.id)
|
| 340 |
total = len(msgs)
|
| 341 |
for idx, msg in enumerate(msgs, start=1):
|
|
|
|
| 352 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 353 |
async def realtime_media_handler(client, message):
|
| 354 |
try:
|
|
|
|
| 355 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 356 |
return
|
| 357 |
|
| 358 |
if message.media_group_id:
|
|
|
|
| 359 |
await asyncio.sleep(1.5)
|
| 360 |
try:
|
| 361 |
group_messages = await client.get_media_group(message.chat.id, message.id)
|
|
|
|
| 364 |
for idx, msg in enumerate(group_messages, start=1):
|
| 365 |
await add_message_to_queue(msg, album_info={"total": total, "index": idx})
|
| 366 |
except Exception:
|
|
|
|
| 367 |
await add_message_to_queue(message)
|
| 368 |
else:
|
| 369 |
await add_message_to_queue(message)
|
|
|
|
| 394 |
logger.error(f"فشل التحقق من الوجهة ({raw}): {e}. تم التحويل للرسائل المحفوظة.")
|
| 395 |
TARGET_CHAT = "me"
|
| 396 |
|
| 397 |
+
# ============ واجهة Gradio ============
|
| 398 |
def create_ui():
|
| 399 |
with gr.Blocks(title="Telegram Archiver Pro") as demo:
|
| 400 |
gr.Markdown("## 🚀 محول وأرشيف تيليجرام الاحترافي (بدون ضياع ملفات)")
|
| 401 |
|
| 402 |
with gr.Row():
|
| 403 |
+
status_box = gr.Textbox(label="حالة النظام", value="يعمل بنجاح ✅", interactive=False)
|
| 404 |
queued_box = gr.Number(label="الملفات في الطابور", value=0, interactive=False)
|
| 405 |
transferred_box = gr.Number(label="الملفات المنقولة بنجاح", value=0, interactive=False)
|
| 406 |
|
|
|
|
| 409 |
with gr.Row():
|
| 410 |
channel_input = gr.Textbox(
|
| 411 |
label="معرف أو رابط القناة / الكروب",
|
| 412 |
+
placeholder="@my_channel أو -100123456789"
|
| 413 |
)
|
| 414 |
limit_input = gr.Number(label="أقصى عدد رسائل (0 = الكل)", value=0)
|
| 415 |
scrape_btn = gr.Button("بدء السحب الآن 📥", variant="primary")
|
| 416 |
|
| 417 |
+
scrape_output = gr.Textbox(label="حالة الطلب", interactive=False)
|
| 418 |
|
| 419 |
def do_scrape(ch, lim):
|
| 420 |
if not ch:
|
| 421 |
return "يرجى كتابة معرف القناة أولاً"
|
| 422 |
+
if MAIN_LOOP and MAIN_LOOP.is_running():
|
| 423 |
+
asyncio.run_coroutine_threadsafe(
|
| 424 |
+
scrape_channel_history(ch.strip(), int(lim)),
|
| 425 |
+
MAIN_LOOP
|
| 426 |
+
)
|
| 427 |
+
return f"تم بدء جلب الأرشيف من {ch} في الخلفية بنجاح! راقب الطابور والسجلات."
|
| 428 |
+
return "حدث خطأ في تشغيل المهمة، تأكد من اتصال البوت."
|
| 429 |
|
| 430 |
scrape_btn.click(fn=do_scrape, inputs=[channel_input, limit_input], outputs=[scrape_output])
|
| 431 |
|
| 432 |
return demo
|
| 433 |
|
| 434 |
+
# ============ تشغيل الويب ============
|
| 435 |
def run_web():
|
| 436 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|