Update bot.py
Browse files
bot.py
CHANGED
|
@@ -5,19 +5,22 @@ import mimetypes
|
|
| 5 |
from threading import Thread
|
| 6 |
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 7 |
from pyrogram import Client, filters, idle
|
|
|
|
| 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 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 15 |
|
| 16 |
-
# --- 2. إعداد قاعدة البيانات
|
| 17 |
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 18 |
cursor = conn.cursor()
|
| 19 |
-
cursor.execute(
|
| 20 |
-
cursor.execute('''CREATE TABLE
|
| 21 |
conn.commit()
|
| 22 |
|
| 23 |
def is_processed(chat_id, msg_id):
|
|
@@ -28,7 +31,15 @@ def mark_processed(chat_id, msg_id):
|
|
| 28 |
cursor.execute("INSERT OR IGNORE INTO processed VALUES (?, ?)", (chat_id, msg_id))
|
| 29 |
conn.commit()
|
| 30 |
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
class RequestHandler(BaseHTTPRequestHandler):
|
| 33 |
def do_GET(self):
|
| 34 |
self.send_response(200)
|
|
@@ -44,7 +55,7 @@ def start_web_server():
|
|
| 44 |
|
| 45 |
Thread(target=start_web_server, daemon=True).start()
|
| 46 |
|
| 47 |
-
# --- 4. إعداد البوت ---
|
| 48 |
API_ID = int(os.environ.get("API_ID", 0))
|
| 49 |
API_HASH = os.environ.get("API_HASH", "")
|
| 50 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
|
@@ -52,126 +63,185 @@ SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
|
| 52 |
target_env = os.environ.get("TARGET_CHAT", "")
|
| 53 |
TARGET_CHAT = int(target_env) if target_env.lstrip('-').isdigit() else target_env
|
| 54 |
|
| 55 |
-
app = Client(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
# طابورين منفصلين تماماً (واحد للتحميل السريع، وواحد للرفع الهادئ)
|
| 58 |
download_queue = asyncio.Queue()
|
| 59 |
upload_queue = asyncio.Queue()
|
| 60 |
|
| 61 |
-
# --- 5. الرادار: التقاط الملفات ال
|
| 62 |
-
@app.on_message(filters.incoming & ~filters.me & (filters.channel | filters.group)
|
| 63 |
async def catch_new_messages(client, message):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
async def downloader_worker(worker_id):
|
| 70 |
while True:
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
try:
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
except Exception as e:
|
| 85 |
-
print(f"❌ خطأ
|
| 86 |
finally:
|
| 87 |
download_queue.task_done()
|
| 88 |
|
| 89 |
-
# --- 7. عامل الرفع ال
|
| 90 |
async def uploader_worker():
|
| 91 |
while True:
|
| 92 |
task = await upload_queue.get()
|
| 93 |
-
|
| 94 |
-
message = task['message']
|
| 95 |
|
| 96 |
try:
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
except FloodWait as e:
|
| 118 |
-
print(f"⚠️ [حظر إرسال]
|
| 119 |
await asyncio.sleep(e.value + 5)
|
| 120 |
await upload_queue.put(task)
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
-
print(f"❌ خطأ
|
| 124 |
-
if os.path.exists(file_path): os.remove(file_path)
|
| 125 |
|
| 126 |
finally:
|
| 127 |
upload_queue.task_done()
|
| 128 |
-
await asyncio.sleep(
|
| 129 |
|
| 130 |
-
# --- 8.
|
| 131 |
async def recover_orphaned_files():
|
| 132 |
-
|
| 133 |
for filename in os.listdir(DOWNLOAD_DIR):
|
| 134 |
file_path = os.path.join(DOWNLOAD_DIR, filename)
|
| 135 |
if os.path.isfile(file_path):
|
| 136 |
-
print(f"♻️ تم العثور على ملف معلق: {filename} | جاري رفعه كمستند لتجنب فقدانه...")
|
| 137 |
try:
|
| 138 |
-
await app.send_document(TARGET_CHAT, document=file_path, caption="ملف مسترجع من الذاكرة
|
| 139 |
os.remove(file_path)
|
| 140 |
-
await asyncio.sleep(
|
| 141 |
except Exception as e:
|
| 142 |
-
print(f"❌ فشل رفع
|
| 143 |
-
print("🧹 تم تنظيف المساحة بالكامل. البوت مستعد!")
|
| 144 |
|
| 145 |
-
# --- 9. التشغيل المركزي ---
|
| 146 |
async def main():
|
| 147 |
await app.start()
|
| 148 |
|
| 149 |
-
print("🔄 جاري تنشيط ذاكرة الحساب
|
| 150 |
try:
|
| 151 |
-
found = False
|
| 152 |
async for dialog in app.get_dialogs():
|
| 153 |
if dialog.chat.id == TARGET_CHAT:
|
| 154 |
-
print(f"✅ تم
|
| 155 |
-
found = True
|
| 156 |
break
|
| 157 |
-
|
| 158 |
-
if not found:
|
| 159 |
-
print("⚠️ لم يتم العثور على القناة في محادثاتك، تأكد أن الحساب منضم إليها!")
|
| 160 |
-
|
| 161 |
except Exception as e:
|
| 162 |
-
print(f"⚠️
|
| 163 |
|
| 164 |
-
# 1. استرجاع وحفظ أي ملفات معلقة
|
| 165 |
await recover_orphaned_files()
|
| 166 |
|
| 167 |
-
# 2. تشغيل 3 عمال تحميل لمنع ضياع المقاطع
|
| 168 |
for i in range(1, 4):
|
| 169 |
asyncio.create_task(downloader_worker(i))
|
| 170 |
|
| 171 |
-
# 3. تشغيل عامل رفع وحيد
|
| 172 |
asyncio.create_task(uploader_worker())
|
| 173 |
|
| 174 |
-
print("🤖 بوت (صائد الملفات السري
|
| 175 |
await idle()
|
| 176 |
await app.stop()
|
| 177 |
|
|
|
|
| 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. إعداد مساحات التخزين (استغلال الرام /dev/shm للسرعة الخارقة) ---
|
| 12 |
DATA_DIR = "/data"
|
| 13 |
DB_PATH = os.path.join(DATA_DIR, 'bot_memory.db')
|
| 14 |
+
|
| 15 |
+
# استخدام ذاكرة RAM بدلاً من الهارد لزيادة سرعة التحميل والرفع
|
| 16 |
+
DOWNLOAD_DIR = "/dev/shm/downloads"
|
| 17 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 18 |
|
| 19 |
+
# --- 2. إعداد قاعدة البيانات ---
|
| 20 |
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 21 |
cursor = conn.cursor()
|
| 22 |
+
cursor.execute('''CREATE TABLE IF NOT EXISTS processed (chat_id INTEGER, msg_id INTEGER, UNIQUE(chat_id, msg_id))''')
|
| 23 |
+
cursor.execute('''CREATE TABLE IF NOT EXISTS processed_albums (album_id TEXT UNIQUE)''')
|
| 24 |
conn.commit()
|
| 25 |
|
| 26 |
def is_processed(chat_id, msg_id):
|
|
|
|
| 31 |
cursor.execute("INSERT OR IGNORE INTO processed VALUES (?, ?)", (chat_id, msg_id))
|
| 32 |
conn.commit()
|
| 33 |
|
| 34 |
+
def is_album_processed(album_id):
|
| 35 |
+
cursor.execute("SELECT 1 FROM processed_albums WHERE album_id=?", (album_id,))
|
| 36 |
+
return cursor.fetchone() is not None
|
| 37 |
+
|
| 38 |
+
def mark_album_processed(album_id):
|
| 39 |
+
cursor.execute("INSERT OR IGNORE INTO processed_albums VALUES (?)", (album_id,))
|
| 40 |
+
conn.commit()
|
| 41 |
+
|
| 42 |
+
# --- 3. سيرفر الويب الوهمي ---
|
| 43 |
class RequestHandler(BaseHTTPRequestHandler):
|
| 44 |
def do_GET(self):
|
| 45 |
self.send_response(200)
|
|
|
|
| 55 |
|
| 56 |
Thread(target=start_web_server, daemon=True).start()
|
| 57 |
|
| 58 |
+
# --- 4. إعداد البوت مع خيارات السرعة المتوازية ---
|
| 59 |
API_ID = int(os.environ.get("API_ID", 0))
|
| 60 |
API_HASH = os.environ.get("API_HASH", "")
|
| 61 |
SESSION_STRING = os.environ.get("SESSION_STRING", "")
|
|
|
|
| 63 |
target_env = os.environ.get("TARGET_CHAT", "")
|
| 64 |
TARGET_CHAT = int(target_env) if target_env.lstrip('-').isdigit() else target_env
|
| 65 |
|
| 66 |
+
app = Client(
|
| 67 |
+
"my_userbot",
|
| 68 |
+
api_id=API_ID,
|
| 69 |
+
api_hash=API_HASH,
|
| 70 |
+
session_string=SESSION_STRING,
|
| 71 |
+
sleep_threshold=300,
|
| 72 |
+
max_concurrent_transmissions=5, # تسريع نقل الأجزاء المتوازية
|
| 73 |
+
workers=10 # زيادة عدد العمال لمعالجة الرسائل
|
| 74 |
+
)
|
| 75 |
|
|
|
|
| 76 |
download_queue = asyncio.Queue()
|
| 77 |
upload_queue = asyncio.Queue()
|
| 78 |
|
| 79 |
+
# --- 5. الرادار: التقاط الملفات والألبومات ---
|
| 80 |
+
@app.on_message(filters.incoming & ~filters.me & (filters.channel | filters.group))
|
| 81 |
async def catch_new_messages(client, message):
|
| 82 |
+
# معالجة الألبومات (تجميع الصور والفيديوهات المرسلة معاً)
|
| 83 |
+
if message.media_group_id:
|
| 84 |
+
if not is_album_processed(str(message.media_group_id)):
|
| 85 |
+
mark_album_processed(str(message.media_group_id))
|
| 86 |
+
print(f"🚨 [رصد ألبوم] تم التقاط ألبوم مجاميع من: {message.chat.title}")
|
| 87 |
+
await download_queue.put({'type': 'album', 'message': message})
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
# معالجة الوسائط المفردة
|
| 91 |
+
if message.photo or message.video or message.document or message.audio or message.animation or message.voice:
|
| 92 |
+
if not is_processed(message.chat.id, message.id):
|
| 93 |
+
print(f"🚨 [رصد] تم التقاط ملف منفرد من: {message.chat.title}")
|
| 94 |
+
await download_queue.put({'type': 'single', 'message': message})
|
| 95 |
+
|
| 96 |
+
# --- 6. كتيبة التحميل إلى الـ RAM ---
|
| 97 |
async def downloader_worker(worker_id):
|
| 98 |
while True:
|
| 99 |
+
task = await download_queue.get()
|
| 100 |
+
task_type = task['type']
|
| 101 |
+
message = task['message']
|
| 102 |
+
|
|
|
|
| 103 |
try:
|
| 104 |
+
if task_type == 'album':
|
| 105 |
+
album_msgs = await app.get_media_group(message.chat.id, message.id)
|
| 106 |
+
downloaded_media = []
|
| 107 |
+
|
| 108 |
+
for msg in album_msgs:
|
| 109 |
+
file_path = await msg.download(file_name=f"{DOWNLOAD_DIR}/")
|
| 110 |
+
if file_path:
|
| 111 |
+
downloaded_media.append({'path': file_path, 'msg': msg})
|
| 112 |
+
mark_processed(msg.chat.id, msg.id)
|
| 113 |
|
| 114 |
+
if downloaded_media:
|
| 115 |
+
await upload_queue.put({'type': 'album', 'items': downloaded_media})
|
| 116 |
+
|
| 117 |
+
elif task_type == 'single':
|
| 118 |
+
if is_processed(message.chat.id, message.id):
|
| 119 |
+
download_queue.task_done()
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
print(f"⚡ [محمل {worker_id}] جارٍ تحميل الملف إلى الرام (ID: {message.id})...")
|
| 123 |
+
file_path = await message.download(file_name=f"{DOWNLOAD_DIR}/")
|
| 124 |
+
|
| 125 |
+
if file_path:
|
| 126 |
+
await upload_queue.put({'type': 'single', 'file_path': file_path, 'message': message})
|
| 127 |
+
|
| 128 |
except Exception as e:
|
| 129 |
+
print(f"❌ خطأ أثناء التحميل: {e}")
|
| 130 |
finally:
|
| 131 |
download_queue.task_done()
|
| 132 |
|
| 133 |
+
# --- 7. عامل الرفع الحافظ للجودة والتجمعات ---
|
| 134 |
async def uploader_worker():
|
| 135 |
while True:
|
| 136 |
task = await upload_queue.get()
|
| 137 |
+
task_type = task['type']
|
|
|
|
| 138 |
|
| 139 |
try:
|
| 140 |
+
if task_type == 'album':
|
| 141 |
+
media_group = []
|
| 142 |
+
files_to_remove = []
|
| 143 |
+
|
| 144 |
+
for item in task['items']:
|
| 145 |
+
file_path = item['path']
|
| 146 |
+
msg = item['msg']
|
| 147 |
+
files_to_remove.append(file_path)
|
| 148 |
+
|
| 149 |
+
caption = msg.caption or ""
|
| 150 |
+
entities = msg.caption_entities
|
| 151 |
+
|
| 152 |
+
if msg.photo:
|
| 153 |
+
media_group.append(InputMediaPhoto(media=file_path, caption=caption, caption_entities=entities))
|
| 154 |
+
elif msg.video:
|
| 155 |
+
media_group.append(InputMediaVideo(media=file_path, caption=caption, caption_entities=entities, supports_streaming=True))
|
| 156 |
+
|
| 157 |
+
if media_group:
|
| 158 |
+
print("🚀 جارٍ رفع الألبوم كاملاً كمجموعة واحدة...")
|
| 159 |
+
await app.send_media_group(TARGET_CHAT, media=media_group)
|
| 160 |
+
print("✅ تم رفع الألبوم بنجاح!")
|
| 161 |
+
|
| 162 |
+
for fp in files_to_remove:
|
| 163 |
+
if os.path.exists(fp): os.remove(fp)
|
| 164 |
+
|
| 165 |
+
elif task_type == 'single':
|
| 166 |
+
file_path = task['file_path']
|
| 167 |
+
message = task['message']
|
| 168 |
+
caption = message.caption or ""
|
| 169 |
+
entities = message.caption_entities
|
| 170 |
+
|
| 171 |
+
print(f"🚀 جارٍ الرفع لقناتك...")
|
| 172 |
+
if message.photo:
|
| 173 |
+
await app.send_photo(TARGET_CHAT, photo=file_path, caption=caption, caption_entities=entities)
|
| 174 |
+
elif message.video:
|
| 175 |
+
# ضمان الحفاظ على جودة الفيديو والتشغيل المباشر وعدم تحوله لصورة
|
| 176 |
+
await app.send_video(
|
| 177 |
+
TARGET_CHAT,
|
| 178 |
+
video=file_path,
|
| 179 |
+
caption=caption,
|
| 180 |
+
caption_entities=entities,
|
| 181 |
+
duration=message.video.duration,
|
| 182 |
+
width=message.video.width,
|
| 183 |
+
height=message.video.height,
|
| 184 |
+
supports_streaming=True
|
| 185 |
+
)
|
| 186 |
+
elif message.animation:
|
| 187 |
+
await app.send_animation(TARGET_CHAT, animation=file_path, caption=caption, caption_entities=entities)
|
| 188 |
+
elif message.audio:
|
| 189 |
+
await app.send_audio(TARGET_CHAT, audio=file_path, caption=caption, caption_entities=entities)
|
| 190 |
+
elif message.voice:
|
| 191 |
+
await app.send_voice(TARGET_CHAT, voice=file_path, caption=caption, caption_entities=entities)
|
| 192 |
+
else:
|
| 193 |
+
await app.send_document(TARGET_CHAT, document=file_path, caption=caption, caption_entities=entities)
|
| 194 |
+
|
| 195 |
+
mark_processed(message.chat.id, message.id)
|
| 196 |
+
print(f"✅ تم الرفع بنجاح!")
|
| 197 |
+
if os.path.exists(file_path): os.remove(file_path)
|
| 198 |
|
| 199 |
except FloodWait as e:
|
| 200 |
+
print(f"⚠️ [حظر إرسال] انتظار {e.value} ثانية...")
|
| 201 |
await asyncio.sleep(e.value + 5)
|
| 202 |
await upload_queue.put(task)
|
| 203 |
|
| 204 |
except Exception as e:
|
| 205 |
+
print(f"❌ خطأ أثناء الرفع: {e}")
|
|
|
|
| 206 |
|
| 207 |
finally:
|
| 208 |
upload_queue.task_done()
|
| 209 |
+
await asyncio.sleep(2)
|
| 210 |
|
| 211 |
+
# --- 8. استرجاع الملفات المعلقة من الرام ---
|
| 212 |
async def recover_orphaned_files():
|
| 213 |
+
if not os.path.exists(DOWNLOAD_DIR): return
|
| 214 |
for filename in os.listdir(DOWNLOAD_DIR):
|
| 215 |
file_path = os.path.join(DOWNLOAD_DIR, filename)
|
| 216 |
if os.path.isfile(file_path):
|
|
|
|
| 217 |
try:
|
| 218 |
+
await app.send_document(TARGET_CHAT, document=file_path, caption="ملف مسترجع من الذاكرة.")
|
| 219 |
os.remove(file_path)
|
| 220 |
+
await asyncio.sleep(2)
|
| 221 |
except Exception as e:
|
| 222 |
+
print(f"❌ فشل رفع ملف معلق: {e}")
|
|
|
|
| 223 |
|
| 224 |
+
# --- 9. التشغيل المركزي وتنشيط الذاكرة ---
|
| 225 |
async def main():
|
| 226 |
await app.start()
|
| 227 |
|
| 228 |
+
print("🔄 جاري تنشيط ذاكرة الحساب لجلب الأكسس هاش الخاص بالقنوات...")
|
| 229 |
try:
|
|
|
|
| 230 |
async for dialog in app.get_dialogs():
|
| 231 |
if dialog.chat.id == TARGET_CHAT:
|
| 232 |
+
print(f"✅ تم التعرف على القناة الهدف: {dialog.chat.title}")
|
|
|
|
| 233 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
except Exception as e:
|
| 235 |
+
print(f"⚠️ تنبيه تنشيط الذاكرة: {e}")
|
| 236 |
|
|
|
|
| 237 |
await recover_orphaned_files()
|
| 238 |
|
|
|
|
| 239 |
for i in range(1, 4):
|
| 240 |
asyncio.create_task(downloader_worker(i))
|
| 241 |
|
|
|
|
| 242 |
asyncio.create_task(uploader_worker())
|
| 243 |
|
| 244 |
+
print("🤖 بوت (صائد الملفات الأسطوري) يعمل بكامل قوته وسرعته الآن!")
|
| 245 |
await idle()
|
| 246 |
await app.stop()
|
| 247 |
|