Update bot.py
Browse files
bot.py
CHANGED
|
@@ -4,14 +4,14 @@ import logging
|
|
| 4 |
import time
|
| 5 |
import threading
|
| 6 |
import shutil
|
| 7 |
-
from typing import Optional, List, Dict, Any
|
| 8 |
import aiosqlite
|
| 9 |
import gradio as gr
|
| 10 |
from hydrogram import Client, filters
|
| 11 |
from hydrogram.errors import FloodWait, RPCError
|
| 12 |
from hydrogram.types import (
|
| 13 |
InputMediaPhoto, InputMediaVideo, InputMediaDocument,
|
| 14 |
-
InputMediaAudio, Message
|
| 15 |
)
|
| 16 |
from fastapi import FastAPI
|
| 17 |
import uvicorn
|
|
@@ -33,57 +33,64 @@ try:
|
|
| 33 |
except ImportError:
|
| 34 |
MessageIdInvalid = RPCError
|
| 35 |
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
logging.basicConfig(
|
| 38 |
level=logging.INFO,
|
| 39 |
format='%(asctime)s | %(levelname)-7s | %(message)s',
|
| 40 |
datefmt='%Y-%m-%d %H:%M:%S'
|
| 41 |
)
|
| 42 |
-
logger = logging.getLogger("
|
| 43 |
|
| 44 |
# ============ الإعدادات والمتغيرات ============
|
| 45 |
API_ID = int(os.environ.get("API_ID", 0))
|
| 46 |
API_HASH = os.environ.get("API_HASH", "")
|
| 47 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 48 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
| 49 |
-
|
| 50 |
|
| 51 |
-
# إعداد مسارات التخزين
|
| 52 |
DATA_DIR = "/data" if os.path.exists("/data") else "/tmp/data"
|
| 53 |
DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
|
| 54 |
-
DB_PATH = os.path.join(DATA_DIR, "
|
| 55 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 56 |
|
| 57 |
# ============ إنشاء العميل ============
|
| 58 |
app = Client(
|
| 59 |
-
"
|
| 60 |
api_id=API_ID,
|
| 61 |
api_hash=API_HASH,
|
| 62 |
session_string=SESSION_STRING,
|
| 63 |
in_memory=True,
|
| 64 |
workers=8,
|
| 65 |
max_concurrent_transmissions=4,
|
| 66 |
-
device_model="
|
| 67 |
system_version="Linux 64bit",
|
| 68 |
-
app_version="
|
| 69 |
lang_code="ar"
|
| 70 |
)
|
| 71 |
|
| 72 |
TARGET_CHAT = "me"
|
|
|
|
| 73 |
MAIN_LOOP: Optional[asyncio.AbstractEventLoop] = None
|
|
|
|
| 74 |
|
| 75 |
-
# إحصائيات
|
| 76 |
stats = {
|
| 77 |
"total_queued": 0,
|
| 78 |
"total_transferred": 0,
|
| 79 |
"total_failed": 0,
|
| 80 |
-
"
|
|
|
|
| 81 |
"status": "Starting..."
|
| 82 |
}
|
| 83 |
|
| 84 |
-
# ============ إدارة التحكم بالسرعة و
|
| 85 |
class SmartFloodManager:
|
| 86 |
-
def __init__(self, normal_delay: float = 1.
|
| 87 |
self.normal_delay = normal_delay
|
| 88 |
self.last_call = 0.0
|
| 89 |
self.lock = asyncio.Lock()
|
|
@@ -94,7 +101,7 @@ class SmartFloodManager:
|
|
| 94 |
now = time.time()
|
| 95 |
if self.flood_until > now:
|
| 96 |
sleep_time = self.flood_until - now
|
| 97 |
-
logger.warning(f"⏳ FloodWait
|
| 98 |
await asyncio.sleep(sleep_time)
|
| 99 |
|
| 100 |
now = time.time()
|
|
@@ -106,11 +113,11 @@ class SmartFloodManager:
|
|
| 106 |
def handle_flood(self, seconds: int):
|
| 107 |
wait_seconds = max(seconds, 5) + 2
|
| 108 |
self.flood_until = time.time() + wait_seconds
|
| 109 |
-
logger.warning(f"🚨
|
| 110 |
|
| 111 |
flood_manager = SmartFloodManager(normal_delay=1.8)
|
| 112 |
|
| 113 |
-
# ============ قاعدة البيانات ذاتية ال
|
| 114 |
def cleanup_corrupted_files():
|
| 115 |
for ext in ["", "-wal", "-shm", "-journal"]:
|
| 116 |
p = f"{DB_PATH}{ext}"
|
|
@@ -127,9 +134,9 @@ async def init_db():
|
|
| 127 |
cur = await db.execute("PRAGMA integrity_check;")
|
| 128 |
res = await cur.fetchone()
|
| 129 |
if not res or res[0] != "ok":
|
| 130 |
-
raise Exception("
|
| 131 |
except Exception as e:
|
| 132 |
-
logger.error(f"Database
|
| 133 |
cleanup_corrupted_files()
|
| 134 |
|
| 135 |
async with aiosqlite.connect(DB_PATH) as db:
|
|
@@ -137,7 +144,7 @@ async def init_db():
|
|
| 137 |
await db.execute("PRAGMA synchronous=NORMAL;")
|
| 138 |
await db.execute("PRAGMA busy_timeout=30000;")
|
| 139 |
|
| 140 |
-
# جدول ال
|
| 141 |
await db.execute("""
|
| 142 |
CREATE TABLE IF NOT EXISTS jobs (
|
| 143 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -160,21 +167,22 @@ async def init_db():
|
|
| 160 |
await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)")
|
| 161 |
await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)")
|
| 162 |
|
| 163 |
-
# جدول نقاط الحفظ للا
|
| 164 |
await db.execute("""
|
| 165 |
CREATE TABLE IF NOT EXISTS scrape_checkpoints (
|
| 166 |
chat_id INTEGER PRIMARY KEY,
|
| 167 |
-
|
|
|
|
| 168 |
last_scraped_id INTEGER DEFAULT 0,
|
| 169 |
total_queued INTEGER DEFAULT 0,
|
| 170 |
-
status TEXT DEFAULT '
|
| 171 |
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 172 |
)
|
| 173 |
""")
|
| 174 |
await db.commit()
|
| 175 |
logger.info("✅ قاعدة البيانات جاهزة ومؤمنة بنظام WAL Mode.")
|
| 176 |
|
| 177 |
-
# ============
|
| 178 |
async def add_job_to_queue(message: Message, album_info: Optional[Dict[str, int]] = None) -> bool:
|
| 179 |
if not message.media:
|
| 180 |
return False
|
|
@@ -220,7 +228,7 @@ async def add_job_to_queue(message: Message, album_info: Optional[Dict[str, int]
|
|
| 220 |
logger.error(f"خطأ في إضافة الرسالة {message_id}: {e}")
|
| 221 |
return False
|
| 222 |
|
| 223 |
-
# ============
|
| 224 |
def format_smart_caption(raw_cap: str, source_name: str, source_username: str, msg_id: int, album_index: int, album_total: int) -> str:
|
| 225 |
lines = []
|
| 226 |
if raw_cap and raw_cap.strip():
|
|
@@ -239,7 +247,7 @@ def format_smart_caption(raw_cap: str, source_name: str, source_username: str, m
|
|
| 239 |
|
| 240 |
return "\n".join(lines)
|
| 241 |
|
| 242 |
-
# ============ معالجة وإرسال الوظيفة
|
| 243 |
async def process_job(job: Dict[str, Any]) -> str:
|
| 244 |
chat_id = job["chat_id"]
|
| 245 |
msg_id = job["message_id"]
|
|
@@ -254,7 +262,7 @@ async def process_job(job: Dict[str, Any]) -> str:
|
|
| 254 |
|
| 255 |
await flood_manager.wait()
|
| 256 |
|
| 257 |
-
# 1. ال
|
| 258 |
try:
|
| 259 |
await app.copy_message(
|
| 260 |
chat_id=TARGET_CHAT,
|
|
@@ -262,7 +270,7 @@ async def process_job(job: Dict[str, Any]) -> str:
|
|
| 262 |
message_id=msg_id,
|
| 263 |
caption=caption
|
| 264 |
)
|
| 265 |
-
logger.info(f"⚡
|
| 266 |
return "SUCCESS"
|
| 267 |
except (FloodWait, FloodPremiumWait) as e:
|
| 268 |
flood_manager.handle_flood(getattr(e, 'value', 30))
|
|
@@ -270,12 +278,10 @@ async def process_job(job: Dict[str, Any]) -> str:
|
|
| 270 |
except MessageIdInvalid:
|
| 271 |
logger.warning(f"⚠️ الرسالة {msg_id} حُذفت من المصدر.")
|
| 272 |
return "DELETED"
|
| 273 |
-
except ChatForwardsRestricted:
|
| 274 |
-
logger.info(f"
|
| 275 |
-
except Exception as e:
|
| 276 |
-
logger.warning(f"تعذر النقل السريع ({e})، جاري استخدام محرك التنزيل والرفع الموثوق...")
|
| 277 |
|
| 278 |
-
# 2. الم
|
| 279 |
temp_file = None
|
| 280 |
try:
|
| 281 |
msg = await app.get_messages(chat_id, msg_id)
|
|
@@ -324,9 +330,9 @@ async def process_job(job: Dict[str, Any]) -> str:
|
|
| 324 |
except Exception:
|
| 325 |
pass
|
| 326 |
|
| 327 |
-
# ============ م
|
| 328 |
async def queue_worker_loop():
|
| 329 |
-
logger.info("⚙️
|
| 330 |
while True:
|
| 331 |
try:
|
| 332 |
if not app.is_connected:
|
|
@@ -372,18 +378,38 @@ async def queue_worker_loop():
|
|
| 372 |
logger.warning(f"توقف مؤقت بسبب قيود تيليجرام: {sec} ثانية")
|
| 373 |
await asyncio.sleep(sec + 1)
|
| 374 |
except Exception as e:
|
| 375 |
-
logger.error(f"خطأ
|
| 376 |
await asyncio.sleep(4)
|
| 377 |
|
| 378 |
-
# ============
|
| 379 |
-
async def
|
| 380 |
-
|
|
|
|
| 381 |
try:
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
|
|
|
|
|
|
|
|
|
| 387 |
last_id = 0
|
| 388 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 389 |
await db.execute("PRAGMA busy_timeout=30000;")
|
|
@@ -391,13 +417,14 @@ async def scrape_channel_with_checkpoint(chat_identifier: str, limit: int = 0) -
|
|
| 391 |
row = await cursor.fetchone()
|
| 392 |
if row:
|
| 393 |
last_id = row[0]
|
| 394 |
-
logger.info(f"📌 استئناف الفحص للقناة {chat_title} من الرسالة رقم: {last_id}")
|
| 395 |
|
|
|
|
|
|
|
| 396 |
count = 0
|
| 397 |
media_groups: Dict[str, List[Message]] = {}
|
| 398 |
highest_msg_id = last_id
|
| 399 |
|
| 400 |
-
async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0
|
| 401 |
if message.id <= last_id and last_id > 0:
|
| 402 |
break
|
| 403 |
|
|
@@ -409,14 +436,13 @@ async def scrape_channel_with_checkpoint(chat_identifier: str, limit: int = 0) -
|
|
| 409 |
mg_id = str(message.media_group_id)
|
| 410 |
media_groups.setdefault(mg_id, []).append(message)
|
| 411 |
else:
|
| 412 |
-
await add_job_to_queue(message)
|
| 413 |
-
|
| 414 |
|
| 415 |
if count > 0 and count % 100 == 0:
|
| 416 |
-
logger.info(f"📦 تم جدولة {count} ملف من {chat_title} حتى الآن...")
|
| 417 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 418 |
await db.execute("""
|
| 419 |
-
INSERT INTO scrape_checkpoints (chat_id,
|
| 420 |
VALUES (?, ?, ?, ?, 'in_progress')
|
| 421 |
ON CONFLICT(chat_id) DO UPDATE SET
|
| 422 |
last_scraped_id=excluded.last_scraped_id,
|
|
@@ -430,12 +456,12 @@ async def scrape_channel_with_checkpoint(chat_identifier: str, limit: int = 0) -
|
|
| 430 |
msgs.sort(key=lambda m: m.id)
|
| 431 |
total = len(msgs)
|
| 432 |
for idx, msg in enumerate(msgs, start=1):
|
| 433 |
-
await add_job_to_queue(msg, album_info={"total": total, "index": idx})
|
| 434 |
-
|
| 435 |
|
| 436 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 437 |
await db.execute("""
|
| 438 |
-
INSERT INTO scrape_checkpoints (chat_id,
|
| 439 |
VALUES (?, ?, ?, ?, 'completed')
|
| 440 |
ON CONFLICT(chat_id) DO UPDATE SET
|
| 441 |
last_scraped_id=excluded.last_scraped_id,
|
|
@@ -445,23 +471,57 @@ async def scrape_channel_with_checkpoint(chat_identifier: str, limit: int = 0) -
|
|
| 445 |
""", (chat_id, chat_title, highest_msg_id, count))
|
| 446 |
await db.commit()
|
| 447 |
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
return msg_result
|
| 451 |
except Exception as e:
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
finally:
|
| 456 |
-
stats["
|
| 457 |
|
| 458 |
-
# ============ رصد الرسائل الجديدة لحظياً
|
| 459 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 460 |
-
async def
|
| 461 |
try:
|
|
|
|
|
|
|
| 462 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 463 |
return
|
| 464 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
if message.media_group_id:
|
| 466 |
await asyncio.sleep(2.0)
|
| 467 |
try:
|
|
@@ -475,74 +535,72 @@ async def incoming_media_listener(client, message: Message):
|
|
| 475 |
else:
|
| 476 |
await add_job_to_queue(message)
|
| 477 |
|
| 478 |
-
logger.info(f"✨ رصد فوري لملف جديد من: {message.chat.title or message.chat.id}")
|
| 479 |
except Exception as e:
|
| 480 |
logger.error(f"خطأ في الرصد الفوري: {e}")
|
| 481 |
|
| 482 |
-
# ============ تحديد
|
| 483 |
async def resolve_target_chat():
|
| 484 |
-
global TARGET_CHAT
|
| 485 |
raw = TARGET_CHAT_RAW.strip()
|
| 486 |
if raw.lower() in ["me", "saved", ""]:
|
| 487 |
TARGET_CHAT = "me"
|
| 488 |
-
|
|
|
|
| 489 |
return
|
| 490 |
try:
|
| 491 |
chat_id_int = int(raw)
|
| 492 |
chat = await app.get_chat(chat_id_int)
|
| 493 |
TARGET_CHAT = chat_id_int
|
|
|
|
| 494 |
logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
|
| 495 |
except ValueError:
|
| 496 |
try:
|
| 497 |
chat = await app.get_chat(raw)
|
| 498 |
TARGET_CHAT = chat.id
|
|
|
|
| 499 |
logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
|
| 500 |
except Exception as e:
|
| 501 |
logger.error(f"تعذر العثور على الوجهة ({raw}): {e}. التحويل للرسائل المحفوظة.")
|
| 502 |
TARGET_CHAT = "me"
|
| 503 |
|
| 504 |
-
# ============ و
|
| 505 |
def create_dashboard():
|
| 506 |
-
with gr.Blocks(title="
|
| 507 |
gr.Markdown("""
|
| 508 |
-
#
|
| 509 |
-
**ن
|
| 510 |
-
* ✅
|
| 511 |
-
* ✅ ن
|
| 512 |
-
* ✅ د
|
| 513 |
-
* ✅ ا
|
| 514 |
""")
|
| 515 |
|
| 516 |
with gr.Row():
|
| 517 |
status_box = gr.Textbox(label="حالة النظام", value="يعمل بنشاط ✅", interactive=False)
|
| 518 |
-
|
|
|
|
| 519 |
transferred_box = gr.Number(label="الملفات المنقولة بنجاح", value=0, interactive=False)
|
| 520 |
-
failed_box = gr.Number(label="الملفات الفاشلة / المحذوفة", value=0, interactive=False)
|
| 521 |
|
| 522 |
gr.Markdown("---")
|
| 523 |
-
gr.Markdown("###
|
|
|
|
| 524 |
with gr.Row():
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
placeholder="@my_channel أو https://t.me/channel_name أو -100123456789"
|
| 528 |
-
)
|
| 529 |
-
max_limit = gr.Number(label="الحد الأقصى للرسائل (0 = كامل الأرشيف بدون توقف)", value=0)
|
| 530 |
-
start_btn = gr.Button("بدء الفحص والسحب الآن 📥", variant="primary")
|
| 531 |
|
| 532 |
-
scrape_status = gr.Textbox(label="
|
| 533 |
|
| 534 |
-
def
|
| 535 |
-
if not ch or not ch.strip():
|
| 536 |
-
return "⚠️ يرجى كتابة معرف أو رابط القناة أولاً."
|
| 537 |
if MAIN_LOOP and MAIN_LOOP.is_running():
|
| 538 |
asyncio.run_coroutine_threadsafe(
|
| 539 |
-
|
| 540 |
MAIN_LOOP
|
| 541 |
)
|
| 542 |
-
return
|
| 543 |
return "❌ تعذر إطلاق المهمة، تأكد من اتصال البوت."
|
| 544 |
|
| 545 |
-
|
| 546 |
|
| 547 |
return demo
|
| 548 |
|
|
@@ -558,7 +616,7 @@ def run_web_server():
|
|
| 558 |
|
| 559 |
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
| 560 |
|
| 561 |
-
# ============ الد
|
| 562 |
async def main():
|
| 563 |
global MAIN_LOOP
|
| 564 |
MAIN_LOOP = asyncio.get_running_loop()
|
|
@@ -572,14 +630,17 @@ async def main():
|
|
| 572 |
await resolve_target_chat()
|
| 573 |
await init_db()
|
| 574 |
|
| 575 |
-
# تشغيل محرك
|
| 576 |
asyncio.create_task(queue_worker_loop())
|
| 577 |
|
| 578 |
-
#
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
|
|
|
|
|
|
|
|
|
| 583 |
|
| 584 |
stats["status"] = "Active"
|
| 585 |
|
|
|
|
| 4 |
import time
|
| 5 |
import threading
|
| 6 |
import shutil
|
| 7 |
+
from typing import Optional, List, Dict, Any, Set
|
| 8 |
import aiosqlite
|
| 9 |
import gradio as gr
|
| 10 |
from hydrogram import Client, filters
|
| 11 |
from hydrogram.errors import FloodWait, RPCError
|
| 12 |
from hydrogram.types import (
|
| 13 |
InputMediaPhoto, InputMediaVideo, InputMediaDocument,
|
| 14 |
+
InputMediaAudio, Message, Chat
|
| 15 |
)
|
| 16 |
from fastapi import FastAPI
|
| 17 |
import uvicorn
|
|
|
|
| 33 |
except ImportError:
|
| 34 |
MessageIdInvalid = RPCError
|
| 35 |
|
| 36 |
+
try:
|
| 37 |
+
from hydrogram.errors import PeerIdInvalid
|
| 38 |
+
except ImportError:
|
| 39 |
+
PeerIdInvalid = RPCError
|
| 40 |
+
|
| 41 |
+
# ============ إعداد نظام السجلات ============
|
| 42 |
logging.basicConfig(
|
| 43 |
level=logging.INFO,
|
| 44 |
format='%(asctime)s | %(levelname)-7s | %(message)s',
|
| 45 |
datefmt='%Y-%m-%d %H:%M:%S'
|
| 46 |
)
|
| 47 |
+
logger = logging.getLogger("AutoArchiverPro")
|
| 48 |
|
| 49 |
# ============ الإعدادات والمتغيرات ============
|
| 50 |
API_ID = int(os.environ.get("API_ID", 0))
|
| 51 |
API_HASH = os.environ.get("API_HASH", "")
|
| 52 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
| 53 |
TARGET_CHAT_RAW = os.environ.get("TARGET_CHAT", "me")
|
| 54 |
+
AUTO_SCAN_ALL = os.environ.get("AUTO_SCAN_ALL", "1") == "1"
|
| 55 |
|
|
|
|
| 56 |
DATA_DIR = "/data" if os.path.exists("/data") else "/tmp/data"
|
| 57 |
DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
|
| 58 |
+
DB_PATH = os.path.join(DATA_DIR, "auto_archiver_v4.db")
|
| 59 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 60 |
|
| 61 |
# ============ إنشاء العميل ============
|
| 62 |
app = Client(
|
| 63 |
+
"auto_archiver",
|
| 64 |
api_id=API_ID,
|
| 65 |
api_hash=API_HASH,
|
| 66 |
session_string=SESSION_STRING,
|
| 67 |
in_memory=True,
|
| 68 |
workers=8,
|
| 69 |
max_concurrent_transmissions=4,
|
| 70 |
+
device_model="Universal Archiver Server",
|
| 71 |
system_version="Linux 64bit",
|
| 72 |
+
app_version="4.0.0",
|
| 73 |
lang_code="ar"
|
| 74 |
)
|
| 75 |
|
| 76 |
TARGET_CHAT = "me"
|
| 77 |
+
TARGET_CHAT_ID: Optional[int] = None
|
| 78 |
MAIN_LOOP: Optional[asyncio.AbstractEventLoop] = None
|
| 79 |
+
KNOWN_CHATS: Dict[int, Dict[str, Any]] = {}
|
| 80 |
|
| 81 |
+
# إحصائيات عامة
|
| 82 |
stats = {
|
| 83 |
"total_queued": 0,
|
| 84 |
"total_transferred": 0,
|
| 85 |
"total_failed": 0,
|
| 86 |
+
"discovered_chats": 0,
|
| 87 |
+
"active_scans": 0,
|
| 88 |
"status": "Starting..."
|
| 89 |
}
|
| 90 |
|
| 91 |
+
# ============ إدارة التحكم بالسرعة وتفادي الحظر ============
|
| 92 |
class SmartFloodManager:
|
| 93 |
+
def __init__(self, normal_delay: float = 1.6):
|
| 94 |
self.normal_delay = normal_delay
|
| 95 |
self.last_call = 0.0
|
| 96 |
self.lock = asyncio.Lock()
|
|
|
|
| 101 |
now = time.time()
|
| 102 |
if self.flood_until > now:
|
| 103 |
sleep_time = self.flood_until - now
|
| 104 |
+
logger.warning(f"⏳ FloodWait نشط - انتظار {sleep_time:.1f} ثانية...")
|
| 105 |
await asyncio.sleep(sleep_time)
|
| 106 |
|
| 107 |
now = time.time()
|
|
|
|
| 113 |
def handle_flood(self, seconds: int):
|
| 114 |
wait_seconds = max(seconds, 5) + 2
|
| 115 |
self.flood_until = time.time() + wait_seconds
|
| 116 |
+
logger.warning(f"🚨 استلام FloodWait من تيليجرام: {seconds} ثانية. تهدئة حتى {wait_seconds} ثانية.")
|
| 117 |
|
| 118 |
flood_manager = SmartFloodManager(normal_delay=1.8)
|
| 119 |
|
| 120 |
+
# ============ قاعدة البيانات ذاتية الإصلاح والتحديث ============
|
| 121 |
def cleanup_corrupted_files():
|
| 122 |
for ext in ["", "-wal", "-shm", "-journal"]:
|
| 123 |
p = f"{DB_PATH}{ext}"
|
|
|
|
| 134 |
cur = await db.execute("PRAGMA integrity_check;")
|
| 135 |
res = await cur.fetchone()
|
| 136 |
if not res or res[0] != "ok":
|
| 137 |
+
raise Exception("Integrity check failed")
|
| 138 |
except Exception as e:
|
| 139 |
+
logger.error(f"Database error ({e}), resetting...")
|
| 140 |
cleanup_corrupted_files()
|
| 141 |
|
| 142 |
async with aiosqlite.connect(DB_PATH) as db:
|
|
|
|
| 144 |
await db.execute("PRAGMA synchronous=NORMAL;")
|
| 145 |
await db.execute("PRAGMA busy_timeout=30000;")
|
| 146 |
|
| 147 |
+
# جدول الرسائل والوظائف
|
| 148 |
await db.execute("""
|
| 149 |
CREATE TABLE IF NOT EXISTS jobs (
|
| 150 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 167 |
await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status)")
|
| 168 |
await db.execute("CREATE INDEX IF NOT EXISTS idx_jobs_media_group ON jobs(media_group_id)")
|
| 169 |
|
| 170 |
+
# جدول نقاط الحفظ لكل محادثة (Checkpoints)
|
| 171 |
await db.execute("""
|
| 172 |
CREATE TABLE IF NOT EXISTS scrape_checkpoints (
|
| 173 |
chat_id INTEGER PRIMARY KEY,
|
| 174 |
+
chat_title TEXT,
|
| 175 |
+
chat_type TEXT,
|
| 176 |
last_scraped_id INTEGER DEFAULT 0,
|
| 177 |
total_queued INTEGER DEFAULT 0,
|
| 178 |
+
status TEXT DEFAULT 'idle', -- idle, in_progress, completed
|
| 179 |
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 180 |
)
|
| 181 |
""")
|
| 182 |
await db.commit()
|
| 183 |
logger.info("✅ قاعدة البيانات جاهزة ومؤمنة بنظام WAL Mode.")
|
| 184 |
|
| 185 |
+
# ============ تخزين الرسالة في الطابور ============
|
| 186 |
async def add_job_to_queue(message: Message, album_info: Optional[Dict[str, int]] = None) -> bool:
|
| 187 |
if not message.media:
|
| 188 |
return False
|
|
|
|
| 228 |
logger.error(f"خطأ في إضافة الرسالة {message_id}: {e}")
|
| 229 |
return False
|
| 230 |
|
| 231 |
+
# ============ إعداد الكابشن الذكي ============
|
| 232 |
def format_smart_caption(raw_cap: str, source_name: str, source_username: str, msg_id: int, album_index: int, album_total: int) -> str:
|
| 233 |
lines = []
|
| 234 |
if raw_cap and raw_cap.strip():
|
|
|
|
| 247 |
|
| 248 |
return "\n".join(lines)
|
| 249 |
|
| 250 |
+
# ============ معالجة وإرسال الوظيفة ============
|
| 251 |
async def process_job(job: Dict[str, Any]) -> str:
|
| 252 |
chat_id = job["chat_id"]
|
| 253 |
msg_id = job["message_id"]
|
|
|
|
| 262 |
|
| 263 |
await flood_manager.wait()
|
| 264 |
|
| 265 |
+
# 1. النسخ المباشر من السيرفرات (الأسرع والأقل استهلاكاً للموارد)
|
| 266 |
try:
|
| 267 |
await app.copy_message(
|
| 268 |
chat_id=TARGET_CHAT,
|
|
|
|
| 270 |
message_id=msg_id,
|
| 271 |
caption=caption
|
| 272 |
)
|
| 273 |
+
logger.info(f"⚡ نقل سريع ناجح: رسالة {msg_id} من [{source_name}]")
|
| 274 |
return "SUCCESS"
|
| 275 |
except (FloodWait, FloodPremiumWait) as e:
|
| 276 |
flood_manager.handle_flood(getattr(e, 'value', 30))
|
|
|
|
| 278 |
except MessageIdInvalid:
|
| 279 |
logger.warning(f"⚠️ الرسالة {msg_id} حُذفت من المصدر.")
|
| 280 |
return "DELETED"
|
| 281 |
+
except (ChatForwardsRestricted, Exception) as e:
|
| 282 |
+
logger.info(f"🔄 تحويل تلقائي للتحميل والرفع للرسالة {msg_id} (السبب: {e})")
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
# 2. خطة الأمان البديلة: التنزيل المباشر وإعادة الرفع التلقائي
|
| 285 |
temp_file = None
|
| 286 |
try:
|
| 287 |
msg = await app.get_messages(chat_id, msg_id)
|
|
|
|
| 330 |
except Exception:
|
| 331 |
pass
|
| 332 |
|
| 333 |
+
# ============ محرك تفريغ الطابور (Worker) ============
|
| 334 |
async def queue_worker_loop():
|
| 335 |
+
logger.info("⚙️ محرك ا��طابور قيد العمل...")
|
| 336 |
while True:
|
| 337 |
try:
|
| 338 |
if not app.is_connected:
|
|
|
|
| 378 |
logger.warning(f"توقف مؤقت بسبب قيود تيليجرام: {sec} ثانية")
|
| 379 |
await asyncio.sleep(sec + 1)
|
| 380 |
except Exception as e:
|
| 381 |
+
logger.error(f"خطأ في محرك الإرسال: {e}")
|
| 382 |
await asyncio.sleep(4)
|
| 383 |
|
| 384 |
+
# ============ تسخين ذاكرة المحادثات وحل خطأ PEER_ID_INVALID نهائياً ============
|
| 385 |
+
async def warm_up_dialogs_cache() -> List[Dict[str, Any]]:
|
| 386 |
+
logger.info("🔄 جاري فحص وتسخين ذاكرة القنوات والمجموعات المنضم إليها الحساب...")
|
| 387 |
+
discovered = []
|
| 388 |
try:
|
| 389 |
+
async for dialog in app.get_dialogs():
|
| 390 |
+
chat = dialog.chat
|
| 391 |
+
if TARGET_CHAT_ID and chat.id == TARGET_CHAT_ID:
|
| 392 |
+
continue
|
| 393 |
+
if chat.type in ["channel", "supergroup", "group"]:
|
| 394 |
+
chat_info = {
|
| 395 |
+
"id": chat.id,
|
| 396 |
+
"title": chat.title or f"Chat_{chat.id}",
|
| 397 |
+
"username": chat.username or "",
|
| 398 |
+
"type": chat.type
|
| 399 |
+
}
|
| 400 |
+
KNOWN_CHATS[chat.id] = chat_info
|
| 401 |
+
discovered.append(chat_info)
|
| 402 |
+
|
| 403 |
+
stats["discovered_chats"] = len(discovered)
|
| 404 |
+
logger.info(f"✅ تم اكتشاف وتأمين {len(discovered)} قناة ومجموعة بنجاح!")
|
| 405 |
+
return discovered
|
| 406 |
+
except Exception as e:
|
| 407 |
+
logger.error(f"خطأ أثناء جلب المحادثات: {e}")
|
| 408 |
+
return []
|
| 409 |
|
| 410 |
+
# ============ فحص أرشيف قناة مع نقطة استئناف ============
|
| 411 |
+
async def scrape_single_chat(chat_id: int, chat_title: str, limit: int = 0) -> int:
|
| 412 |
+
try:
|
| 413 |
last_id = 0
|
| 414 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 415 |
await db.execute("PRAGMA busy_timeout=30000;")
|
|
|
|
| 417 |
row = await cursor.fetchone()
|
| 418 |
if row:
|
| 419 |
last_id = row[0]
|
|
|
|
| 420 |
|
| 421 |
+
logger.info(f"🔍 فحص أرشيف: {chat_title} (استئناف من الرسالة {last_id})...")
|
| 422 |
+
|
| 423 |
count = 0
|
| 424 |
media_groups: Dict[str, List[Message]] = {}
|
| 425 |
highest_msg_id = last_id
|
| 426 |
|
| 427 |
+
async for message in app.get_chat_history(chat_id, limit=limit if limit > 0 else 0):
|
| 428 |
if message.id <= last_id and last_id > 0:
|
| 429 |
break
|
| 430 |
|
|
|
|
| 436 |
mg_id = str(message.media_group_id)
|
| 437 |
media_groups.setdefault(mg_id, []).append(message)
|
| 438 |
else:
|
| 439 |
+
if await add_job_to_queue(message):
|
| 440 |
+
count += 1
|
| 441 |
|
| 442 |
if count > 0 and count % 100 == 0:
|
|
|
|
| 443 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 444 |
await db.execute("""
|
| 445 |
+
INSERT INTO scrape_checkpoints (chat_id, chat_title, last_scraped_id, total_queued, status)
|
| 446 |
VALUES (?, ?, ?, ?, 'in_progress')
|
| 447 |
ON CONFLICT(chat_id) DO UPDATE SET
|
| 448 |
last_scraped_id=excluded.last_scraped_id,
|
|
|
|
| 456 |
msgs.sort(key=lambda m: m.id)
|
| 457 |
total = len(msgs)
|
| 458 |
for idx, msg in enumerate(msgs, start=1):
|
| 459 |
+
if await add_job_to_queue(msg, album_info={"total": total, "index": idx}):
|
| 460 |
+
count += 1
|
| 461 |
|
| 462 |
async with aiosqlite.connect(DB_PATH) as db:
|
| 463 |
await db.execute("""
|
| 464 |
+
INSERT INTO scrape_checkpoints (chat_id, chat_title, last_scraped_id, total_queued, status)
|
| 465 |
VALUES (?, ?, ?, ?, 'completed')
|
| 466 |
ON CONFLICT(chat_id) DO UPDATE SET
|
| 467 |
last_scraped_id=excluded.last_scraped_id,
|
|
|
|
| 471 |
""", (chat_id, chat_title, highest_msg_id, count))
|
| 472 |
await db.commit()
|
| 473 |
|
| 474 |
+
logger.info(f"✅ اكتمل فحص {chat_title}! جدولة {count} ملف جديد.")
|
| 475 |
+
return count
|
|
|
|
| 476 |
except Exception as e:
|
| 477 |
+
logger.error(f"خطأ أثناء فحص {chat_title} ({chat_id}): {e}")
|
| 478 |
+
return 0
|
| 479 |
+
|
| 480 |
+
# ============ الفحص الشامل لجميع القنوات والكروبات ============
|
| 481 |
+
async def scrape_all_joined_chats(limit_per_chat: int = 0) -> str:
|
| 482 |
+
stats["active_scans"] += 1
|
| 483 |
+
try:
|
| 484 |
+
chats = await warm_up_dialogs_cache()
|
| 485 |
+
if not chats:
|
| 486 |
+
return "لم يتم العثور على قنوات أو مجموعات في الحساب."
|
| 487 |
+
|
| 488 |
+
logger.info(f"🚀 بدء عملية الفحص الشامل لـ {len(chats)} قناة ومجموعة...")
|
| 489 |
+
total_all = 0
|
| 490 |
+
for idx, chat in enumerate(chats, 1):
|
| 491 |
+
c_id = chat["id"]
|
| 492 |
+
c_title = chat["title"]
|
| 493 |
+
logger.info(f"[{idx}/{len(chats)}] جاري فحص: {c_title}...")
|
| 494 |
+
queued = await scrape_single_chat(c_id, c_title, limit=limit_per_chat)
|
| 495 |
+
total_all += queued
|
| 496 |
+
await asyncio.sleep(1.0)
|
| 497 |
+
|
| 498 |
+
msg = f"🎉 اكتمل الفحص الشامل لجميع القنوات والكروبات ({len(chats)} محادثة)! تمت جدولة {total_all} ملف جديد."
|
| 499 |
+
logger.info(msg)
|
| 500 |
+
return msg
|
| 501 |
+
except Exception as e:
|
| 502 |
+
err = f"خطأ في الفحص الشامل: {e}"
|
| 503 |
+
logger.error(err)
|
| 504 |
+
return err
|
| 505 |
finally:
|
| 506 |
+
stats["active_scans"] = max(0, stats["active_scans"] - 1)
|
| 507 |
|
| 508 |
+
# ============ رصد الرسائل الجديدة لحظياً من كافة القنوات ============
|
| 509 |
@app.on_message(filters.incoming & ~filters.me & filters.media)
|
| 510 |
+
async def realtime_all_chats_handler(client, message: Message):
|
| 511 |
try:
|
| 512 |
+
if TARGET_CHAT_ID and message.chat.id == TARGET_CHAT_ID:
|
| 513 |
+
return
|
| 514 |
if str(message.chat.id) == str(TARGET_CHAT):
|
| 515 |
return
|
| 516 |
|
| 517 |
+
if message.chat.id not in KNOWN_CHATS and message.chat.type in ["channel", "supergroup", "group"]:
|
| 518 |
+
KNOWN_CHATS[message.chat.id] = {
|
| 519 |
+
"id": message.chat.id,
|
| 520 |
+
"title": message.chat.title or f"Chat_{message.chat.id}",
|
| 521 |
+
"username": message.chat.username or "",
|
| 522 |
+
"type": message.chat.type
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
if message.media_group_id:
|
| 526 |
await asyncio.sleep(2.0)
|
| 527 |
try:
|
|
|
|
| 535 |
else:
|
| 536 |
await add_job_to_queue(message)
|
| 537 |
|
| 538 |
+
logger.info(f"✨ رصد فوري لملف جديد من: [{message.chat.title or message.chat.id}]")
|
| 539 |
except Exception as e:
|
| 540 |
logger.error(f"خطأ في الرصد الفوري: {e}")
|
| 541 |
|
| 542 |
+
# ============ تحديد الوجهة ============
|
| 543 |
async def resolve_target_chat():
|
| 544 |
+
global TARGET_CHAT, TARGET_CHAT_ID
|
| 545 |
raw = TARGET_CHAT_RAW.strip()
|
| 546 |
if raw.lower() in ["me", "saved", ""]:
|
| 547 |
TARGET_CHAT = "me"
|
| 548 |
+
TARGET_CHAT_ID = None
|
| 549 |
+
logger.info("🎯 الوجهة: الرسائل المحفوظة (Saved Messages)")
|
| 550 |
return
|
| 551 |
try:
|
| 552 |
chat_id_int = int(raw)
|
| 553 |
chat = await app.get_chat(chat_id_int)
|
| 554 |
TARGET_CHAT = chat_id_int
|
| 555 |
+
TARGET_CHAT_ID = chat.id
|
| 556 |
logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
|
| 557 |
except ValueError:
|
| 558 |
try:
|
| 559 |
chat = await app.get_chat(raw)
|
| 560 |
TARGET_CHAT = chat.id
|
| 561 |
+
TARGET_CHAT_ID = chat.id
|
| 562 |
logger.info(f"🎯 الوجهة المحددة: {chat.title} ({TARGET_CHAT})")
|
| 563 |
except Exception as e:
|
| 564 |
logger.error(f"تعذر العثور على الوجهة ({raw}): {e}. التحويل للرسائل المحفوظة.")
|
| 565 |
TARGET_CHAT = "me"
|
| 566 |
|
| 567 |
+
# ============ لوحة التحكم (Gradio) ============
|
| 568 |
def create_dashboard():
|
| 569 |
+
with gr.Blocks(title="Universal Telegram Archiver 2026") as demo:
|
| 570 |
gr.Markdown("""
|
| 571 |
+
# 🌐 Universal Telegram Archiver Pro (النسخة الشاملة التلقائية)
|
| 572 |
+
**يسحب من جميع القنوات والكروبات المنضم إليها تلقائياً بدون استثناء وبدون ضياع ملف واحد:**
|
| 573 |
+
* ✅ حل مشكلة `PEER_ID_INVALID` بشكل جذري بتسخين الذاكرة التلقائي.
|
| 574 |
+
* ✅ فحص أرشيف كل القنوات والمجموعات المنضم إليها دفعة واحدة تلقائياً.
|
| 575 |
+
* ✅ رصد فوري لحظي لأي ملف أو ألبوم ينزل في أي قناة أو كروب.
|
| 576 |
+
* ✅ طابور ذكي دائم مع كتابة المصدر ورقم المقطع ونظام ضد الحظر.
|
| 577 |
""")
|
| 578 |
|
| 579 |
with gr.Row():
|
| 580 |
status_box = gr.Textbox(label="حالة النظام", value="يعمل بنشاط ✅", interactive=False)
|
| 581 |
+
chats_count = gr.Number(label="القنوات والكروبات المكتشفة", value=0, interactive=False)
|
| 582 |
+
queued_box = gr.Number(label="الملفات في الطابور", value=0, interactive=False)
|
| 583 |
transferred_box = gr.Number(label="الملفات المنقولة بنجاح", value=0, interactive=False)
|
|
|
|
| 584 |
|
| 585 |
gr.Markdown("---")
|
| 586 |
+
gr.Markdown("### ⚡ خيارات السحب والأرشفة:")
|
| 587 |
+
|
| 588 |
with gr.Row():
|
| 589 |
+
scan_all_btn = gr.Button("🔄 إعادة فحص وسحب الأرشيف من جميع القنوات والكروبات المنضم إليها الآن", variant="primary", scale=2)
|
| 590 |
+
limit_input = gr.Number(label="الحد الأقصى لكل محادثة (0 = كامل الأرشيف القديم)", value=0, scale=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
|
| 592 |
+
scrape_status = gr.Textbox(label="حالة الفحص والعمليات", interactive=False)
|
| 593 |
|
| 594 |
+
def trigger_scan_all(lim):
|
|
|
|
|
|
|
| 595 |
if MAIN_LOOP and MAIN_LOOP.is_running():
|
| 596 |
asyncio.run_coroutine_threadsafe(
|
| 597 |
+
scrape_all_joined_chats(int(lim)),
|
| 598 |
MAIN_LOOP
|
| 599 |
)
|
| 600 |
+
return "🚀 تم بدء عملية الفحص الشامل لجميع القنوات والكروبات في الخلفية بنجاح! راقب السجلات والطابور."
|
| 601 |
return "❌ تعذر إطلاق المهمة، تأكد من اتصال البوت."
|
| 602 |
|
| 603 |
+
scan_all_btn.click(fn=trigger_scan_all, inputs=[limit_input], outputs=[scrape_status])
|
| 604 |
|
| 605 |
return demo
|
| 606 |
|
|
|
|
| 616 |
|
| 617 |
uvicorn.run(fastapi_app, host="0.0.0.0", port=7860)
|
| 618 |
|
| 619 |
+
# ============ نقطة الدخول ============
|
| 620 |
async def main():
|
| 621 |
global MAIN_LOOP
|
| 622 |
MAIN_LOOP = asyncio.get_running_loop()
|
|
|
|
| 630 |
await resolve_target_chat()
|
| 631 |
await init_db()
|
| 632 |
|
| 633 |
+
# تشغيل محرك الطابور
|
| 634 |
asyncio.create_task(queue_worker_loop())
|
| 635 |
|
| 636 |
+
# تسخين الذاكرة وجلب كافة المحادثات
|
| 637 |
+
discovered = await warm_up_dialogs_cache()
|
| 638 |
+
logger.info(f"تم تسجيل {len(discovered)} محادثة جاهزة للأرشفة.")
|
| 639 |
+
|
| 640 |
+
# الفحص الشامل التلقائي لجميع القنوات عند التشغيل
|
| 641 |
+
if AUTO_SCAN_ALL:
|
| 642 |
+
logger.info("⚡ تفعيل الفحص الشامل التلقائي لجميع القنوات المنضم إليها في الخلفية...")
|
| 643 |
+
asyncio.create_task(scrape_all_joined_chats(limit_per_chat=0))
|
| 644 |
|
| 645 |
stats["status"] = "Active"
|
| 646 |
|