Update bot.py
Browse files
bot.py
CHANGED
|
@@ -1,19 +1,18 @@
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import sqlite3
|
| 4 |
-
import mimetypes
|
| 5 |
from threading import Thread
|
| 6 |
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 7 |
from pyrogram import Client, filters, idle
|
| 8 |
-
from pyrogram.types import InputMediaPhoto, InputMediaVideo
|
| 9 |
from pyrogram.errors import FloodWait
|
| 10 |
|
| 11 |
-
# --- 1. إعداد مساحات التخزين (
|
| 12 |
DATA_DIR = "/data"
|
| 13 |
DB_PATH = os.path.join(DATA_DIR, 'bot_memory.db')
|
| 14 |
|
| 15 |
-
# استخدام
|
| 16 |
-
DOWNLOAD_DIR = "
|
| 17 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 18 |
|
| 19 |
# --- 2. إعداد قاعدة البيانات ---
|
|
@@ -39,7 +38,7 @@ def mark_album_processed(album_id):
|
|
| 39 |
cursor.execute("INSERT OR IGNORE INTO processed_albums VALUES (?)", (album_id,))
|
| 40 |
conn.commit()
|
| 41 |
|
| 42 |
-
# --- 3. سيرفر الويب الوهمي (متوافق 100% مع UptimeRobot
|
| 43 |
class RequestHandler(BaseHTTPRequestHandler):
|
| 44 |
def do_GET(self):
|
| 45 |
body = b"Ultimate Speed Archiver is Running 24/7!"
|
|
@@ -62,7 +61,7 @@ def start_web_server():
|
|
| 62 |
try:
|
| 63 |
HTTPServer(('0.0.0.0', 7860), RequestHandler).serve_forever()
|
| 64 |
except Exception as e:
|
| 65 |
-
print(f"⚠️ تجاوز خطأ السيرفر
|
| 66 |
|
| 67 |
Thread(target=start_web_server, daemon=True).start()
|
| 68 |
|
|
@@ -80,31 +79,33 @@ app = Client(
|
|
| 80 |
api_hash=API_HASH,
|
| 81 |
session_string=SESSION_STRING,
|
| 82 |
sleep_threshold=300,
|
| 83 |
-
max_concurrent_transmissions=5,
|
| 84 |
-
workers=10
|
| 85 |
)
|
| 86 |
|
| 87 |
download_queue = asyncio.Queue()
|
| 88 |
upload_queue = asyncio.Queue()
|
| 89 |
|
| 90 |
-
# --- 5. الرادار: التقاط الملفات والألبومات ---
|
| 91 |
-
@app.on_message(filters.incoming & ~filters.me & (filters.channel | filters.group))
|
| 92 |
async def catch_new_messages(client, message):
|
| 93 |
-
# معالجة الألبومات (تجميع الصور والفيديوهات المرسلة معاً)
|
| 94 |
if message.media_group_id:
|
| 95 |
if not is_album_processed(str(message.media_group_id)):
|
| 96 |
mark_album_processed(str(message.media_group_id))
|
| 97 |
-
print(f"🚨 [رصد ألبوم] تم الت
|
| 98 |
-
|
|
|
|
| 99 |
return
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
print(f"🚨 [رصد] تم التقاط ملف منفرد من: {message.chat.title}")
|
| 105 |
-
await download_queue.put({'type': 'single', 'message': message})
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
async def downloader_worker(worker_id):
|
| 109 |
while True:
|
| 110 |
task = await download_queue.get()
|
|
@@ -130,18 +131,18 @@ async def downloader_worker(worker_id):
|
|
| 130 |
download_queue.task_done()
|
| 131 |
continue
|
| 132 |
|
| 133 |
-
print(f"⚡ [محمل {worker_id}] جارٍ تحميل الملف
|
| 134 |
file_path = await message.download(file_name=f"{DOWNLOAD_DIR}/")
|
| 135 |
|
| 136 |
if file_path:
|
| 137 |
await upload_queue.put({'type': 'single', 'file_path': file_path, 'message': message})
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
-
print(f"❌ خطأ
|
| 141 |
finally:
|
| 142 |
download_queue.task_done()
|
| 143 |
|
| 144 |
-
# --- 7. عامل الرفع الحا
|
| 145 |
async def uploader_worker():
|
| 146 |
while True:
|
| 147 |
task = await upload_queue.get()
|
|
@@ -164,12 +165,18 @@ async def uploader_worker():
|
|
| 164 |
media_group.append(InputMediaPhoto(media=file_path, caption=caption, caption_entities=entities))
|
| 165 |
elif msg.video:
|
| 166 |
media_group.append(InputMediaVideo(media=file_path, caption=caption, caption_entities=entities, supports_streaming=True))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
if media_group:
|
| 169 |
-
print("🚀
|
|
|
|
| 170 |
await app.send_media_group(TARGET_CHAT, media=media_group)
|
| 171 |
-
print("✅
|
| 172 |
|
|
|
|
| 173 |
for fp in files_to_remove:
|
| 174 |
if os.path.exists(fp): os.remove(fp)
|
| 175 |
|
|
@@ -179,7 +186,7 @@ async def uploader_worker():
|
|
| 179 |
caption = message.caption or ""
|
| 180 |
entities = message.caption_entities
|
| 181 |
|
| 182 |
-
print(f"🚀
|
| 183 |
if message.photo:
|
| 184 |
await app.send_photo(TARGET_CHAT, photo=file_path, caption=caption, caption_entities=entities)
|
| 185 |
elif message.video:
|
|
@@ -207,43 +214,52 @@ async def uploader_worker():
|
|
| 207 |
if os.path.exists(file_path): os.remove(file_path)
|
| 208 |
|
| 209 |
except FloodWait as e:
|
| 210 |
-
|
|
|
|
| 211 |
await asyncio.sleep(e.value + 5)
|
| 212 |
-
await upload_queue.put(task)
|
| 213 |
|
| 214 |
except Exception as e:
|
| 215 |
-
print(f"❌ خطأ
|
|
|
|
| 216 |
|
| 217 |
finally:
|
| 218 |
upload_queue.task_done()
|
| 219 |
await asyncio.sleep(2)
|
| 220 |
|
| 221 |
-
# --- 8. استرجاع
|
| 222 |
async def recover_orphaned_files():
|
| 223 |
if not os.path.exists(DOWNLOAD_DIR): return
|
| 224 |
-
for
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
| 227 |
try:
|
| 228 |
-
|
|
|
|
| 229 |
os.remove(file_path)
|
| 230 |
-
await asyncio.sleep(
|
|
|
|
|
|
|
|
|
|
| 231 |
except Exception as e:
|
| 232 |
-
print(f"❌ فشل
|
| 233 |
|
| 234 |
-
# --- 9. التشغيل المركزي
|
| 235 |
async def main():
|
| 236 |
await app.start()
|
| 237 |
|
| 238 |
-
print("🔄
|
| 239 |
try:
|
| 240 |
async for dialog in app.get_dialogs():
|
| 241 |
if dialog.chat.id == TARGET_CHAT:
|
| 242 |
print(f"✅ تم التعرف على القناة الهدف: {dialog.chat.title}")
|
| 243 |
break
|
| 244 |
except Exception as e:
|
| 245 |
-
|
| 246 |
|
|
|
|
| 247 |
await recover_orphaned_files()
|
| 248 |
|
| 249 |
for i in range(1, 4):
|
|
@@ -251,7 +267,7 @@ async def main():
|
|
| 251 |
|
| 252 |
asyncio.create_task(uploader_worker())
|
| 253 |
|
| 254 |
-
print("🤖
|
| 255 |
await idle()
|
| 256 |
await app.stop()
|
| 257 |
|
|
|
|
| 1 |
import os
|
| 2 |
import asyncio
|
| 3 |
import sqlite3
|
|
|
|
| 4 |
from threading import Thread
|
| 5 |
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 6 |
from pyrogram import Client, filters, idle
|
| 7 |
+
from pyrogram.types import InputMediaPhoto, InputMediaVideo, InputMediaDocument, InputMediaAudio
|
| 8 |
from pyrogram.errors import FloodWait
|
| 9 |
|
| 10 |
+
# --- 1. إعداد مساحات التخزين (تم العودة للقرص الدائم لحماية الملفات وقت الحظر) ---
|
| 11 |
DATA_DIR = "/data"
|
| 12 |
DB_PATH = os.path.join(DATA_DIR, 'bot_memory.db')
|
| 13 |
|
| 14 |
+
# استخدام التخزين الدائم لضمان عدم ضياع أي مقطع إذا انطفأ السيرفر أثناء حظر تيليجرام
|
| 15 |
+
DOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")
|
| 16 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 17 |
|
| 18 |
# --- 2. إعداد قاعدة البيانات ---
|
|
|
|
| 38 |
cursor.execute("INSERT OR IGNORE INTO processed_albums VALUES (?)", (album_id,))
|
| 39 |
conn.commit()
|
| 40 |
|
| 41 |
+
# --- 3. سيرفر الويب الوهمي (متوافق 100% مع UptimeRobot) ---
|
| 42 |
class RequestHandler(BaseHTTPRequestHandler):
|
| 43 |
def do_GET(self):
|
| 44 |
body = b"Ultimate Speed Archiver is Running 24/7!"
|
|
|
|
| 61 |
try:
|
| 62 |
HTTPServer(('0.0.0.0', 7860), RequestHandler).serve_forever()
|
| 63 |
except Exception as e:
|
| 64 |
+
print(f"⚠️ تجاوز خطأ السيرفر: {e}")
|
| 65 |
|
| 66 |
Thread(target=start_web_server, daemon=True).start()
|
| 67 |
|
|
|
|
| 79 |
api_hash=API_HASH,
|
| 80 |
session_string=SESSION_STRING,
|
| 81 |
sleep_threshold=300,
|
| 82 |
+
max_concurrent_transmissions=5,
|
| 83 |
+
workers=10
|
| 84 |
)
|
| 85 |
|
| 86 |
download_queue = asyncio.Queue()
|
| 87 |
upload_queue = asyncio.Queue()
|
| 88 |
|
| 89 |
+
# --- 5. الرادار الذكي: التقاط الملفات والألبومات بدون تفويت ---
|
| 90 |
+
@app.on_message(filters.incoming & ~filters.me & (filters.channel | filters.group) & filters.media)
|
| 91 |
async def catch_new_messages(client, message):
|
|
|
|
| 92 |
if message.media_group_id:
|
| 93 |
if not is_album_processed(str(message.media_group_id)):
|
| 94 |
mark_album_processed(str(message.media_group_id))
|
| 95 |
+
print(f"🚨 [رصد ألبوم] تجميع الأجزاء... (ننتظر 3 ثوانٍ لضمان وصول كل المقاطع)")
|
| 96 |
+
# تشغيل مهمة جانبية للانتظار حتى لا يتعطل الرادار عن باقي الرسائل
|
| 97 |
+
asyncio.create_task(queue_album_after_delay(message))
|
| 98 |
return
|
| 99 |
|
| 100 |
+
if not is_processed(message.chat.id, message.id):
|
| 101 |
+
print(f"🚨 [رصد مفرد] تم التقاط ملف من: {message.chat.title}")
|
| 102 |
+
await download_queue.put({'type': 'single', 'message': message})
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
async def queue_album_after_delay(message):
|
| 105 |
+
await asyncio.sleep(3) # التحديث الأهم: تأخير مقصود لتكتمل حزمة الألبوم في سيرفر تيليجرام
|
| 106 |
+
await download_queue.put({'type': 'album', 'message': message})
|
| 107 |
+
|
| 108 |
+
# --- 6. كتيبة التحميل (حفظ بالقرص الدائم) ---
|
| 109 |
async def downloader_worker(worker_id):
|
| 110 |
while True:
|
| 111 |
task = await download_queue.get()
|
|
|
|
| 131 |
download_queue.task_done()
|
| 132 |
continue
|
| 133 |
|
| 134 |
+
print(f"⚡ [محمل {worker_id}] جارٍ تحميل الملف الدائم (ID: {message.id})...")
|
| 135 |
file_path = await message.download(file_name=f"{DOWNLOAD_DIR}/")
|
| 136 |
|
| 137 |
if file_path:
|
| 138 |
await upload_queue.put({'type': 'single', 'file_path': file_path, 'message': message})
|
| 139 |
|
| 140 |
except Exception as e:
|
| 141 |
+
print(f"❌ خطأ بالتحميل: {e}")
|
| 142 |
finally:
|
| 143 |
download_queue.task_done()
|
| 144 |
|
| 145 |
+
# --- 7. عامل الرفع الصبور (يحترم الحظر ويحفظ الملفات) ---
|
| 146 |
async def uploader_worker():
|
| 147 |
while True:
|
| 148 |
task = await upload_queue.get()
|
|
|
|
| 165 |
media_group.append(InputMediaPhoto(media=file_path, caption=caption, caption_entities=entities))
|
| 166 |
elif msg.video:
|
| 167 |
media_group.append(InputMediaVideo(media=file_path, caption=caption, caption_entities=entities, supports_streaming=True))
|
| 168 |
+
elif msg.audio:
|
| 169 |
+
media_group.append(InputMediaAudio(media=file_path, caption=caption, caption_entities=entities))
|
| 170 |
+
elif msg.document:
|
| 171 |
+
media_group.append(InputMediaDocument(media=file_path, caption=caption, caption_entities=entities))
|
| 172 |
|
| 173 |
if media_group:
|
| 174 |
+
print("🚀 رفع ألبوم متكامل...")
|
| 175 |
+
# رفع الألبوم (تيليجرام قد يفصل المستندات عن الصور، Pyrogram يتعامل معها)
|
| 176 |
await app.send_media_group(TARGET_CHAT, media=media_group)
|
| 177 |
+
print("✅ الألبوم ارتفع بنجاح!")
|
| 178 |
|
| 179 |
+
# لا نحذف الملفات إلا بعد نجاح الرفع 100%
|
| 180 |
for fp in files_to_remove:
|
| 181 |
if os.path.exists(fp): os.remove(fp)
|
| 182 |
|
|
|
|
| 186 |
caption = message.caption or ""
|
| 187 |
entities = message.caption_entities
|
| 188 |
|
| 189 |
+
print(f"🚀 رفع ملف مفرد...")
|
| 190 |
if message.photo:
|
| 191 |
await app.send_photo(TARGET_CHAT, photo=file_path, caption=caption, caption_entities=entities)
|
| 192 |
elif message.video:
|
|
|
|
| 214 |
if os.path.exists(file_path): os.remove(file_path)
|
| 215 |
|
| 216 |
except FloodWait as e:
|
| 217 |
+
# الخدعة الذهبية: نعيد المهمة للطابور، وننام، والملف بأمان في الهارد دسك!
|
| 218 |
+
print(f"⏳ [حظر إرسال] تيليجرام مقفل مؤقتاً. سننتظر {e.value} ثانية. الملفات مخزنة بأمان ولن تضيع!")
|
| 219 |
await asyncio.sleep(e.value + 5)
|
| 220 |
+
await upload_queue.put(task)
|
| 221 |
|
| 222 |
except Exception as e:
|
| 223 |
+
print(f"❌ خطأ غير متوقع بالرفع: {e}")
|
| 224 |
+
# في حال وجود خطأ آخر غير الحظر، نحتفظ بالملف ليتم استرجاعه عند إعادة التشغيل
|
| 225 |
|
| 226 |
finally:
|
| 227 |
upload_queue.task_done()
|
| 228 |
await asyncio.sleep(2)
|
| 229 |
|
| 230 |
+
# --- 8. المنقذ: استرجاع ملفات ما قبل الانطفاء/الحظر ---
|
| 231 |
async def recover_orphaned_files():
|
| 232 |
if not os.path.exists(DOWNLOAD_DIR): return
|
| 233 |
+
files = [f for f in os.listdir(DOWNLOAD_DIR) if os.path.isfile(os.path.join(DOWNLOAD_DIR, f))]
|
| 234 |
+
if files:
|
| 235 |
+
print(f"🔍 [عملية إنقاذ] تم العثور على {len(files)} ملفات مخزنة من الجلسة السابقة بسبب حظر أو انطفاء!")
|
| 236 |
+
for filename in files:
|
| 237 |
+
file_path = os.path.join(DOWNLOAD_DIR, filename)
|
| 238 |
try:
|
| 239 |
+
# نرفع الملفات المعلقة كمستندات لضمان عدم ضياعها
|
| 240 |
+
await app.send_document(TARGET_CHAT, document=file_path, caption="♻️ مل�� مسترجع من الذاكرة الاحتياطية (كان معلقاً)")
|
| 241 |
os.remove(file_path)
|
| 242 |
+
await asyncio.sleep(3) # تجنب الحظر أثناء الاسترجاع
|
| 243 |
+
except FloodWait as e:
|
| 244 |
+
print(f"⏳ لا يزال الحظر مستمراً، ننتظر {e.value} ثانية...")
|
| 245 |
+
await asyncio.sleep(e.value + 5)
|
| 246 |
except Exception as e:
|
| 247 |
+
print(f"❌ فشل إنقاذ الملف {filename}: {e}")
|
| 248 |
|
| 249 |
+
# --- 9. التشغيل المركزي ---
|
| 250 |
async def main():
|
| 251 |
await app.start()
|
| 252 |
|
| 253 |
+
print("🔄 تنشيط ذاكرة الحساب لجلب الأكسس هاش...")
|
| 254 |
try:
|
| 255 |
async for dialog in app.get_dialogs():
|
| 256 |
if dialog.chat.id == TARGET_CHAT:
|
| 257 |
print(f"✅ تم التعرف على القناة الهدف: {dialog.chat.title}")
|
| 258 |
break
|
| 259 |
except Exception as e:
|
| 260 |
+
pass
|
| 261 |
|
| 262 |
+
# فور التشغيل، ابحث عن أي ملفات كانت معلقة بسبب حظر وارفعها
|
| 263 |
await recover_orphaned_files()
|
| 264 |
|
| 265 |
for i in range(1, 4):
|
|
|
|
| 267 |
|
| 268 |
asyncio.create_task(uploader_worker())
|
| 269 |
|
| 270 |
+
print("🤖 جيمي: صائد الملفات المدرّع يعمل الآن! لا ضياع بعد اليوم...")
|
| 271 |
await idle()
|
| 272 |
await app.stop()
|
| 273 |
|