Update bot.py
Browse files29 unmodified lines303132333435363738394041422 unmodified lines454647484950515223 unmodified lines7677787980818212 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711723 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322331 unmodified line23523623723823924024123 unmodified lines26526626726826927027121 unmodified lines29329429529629729829929 unmodified linesDOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")os.makedirs(DOWNLOAD_DIR, exist_ok=True)# ============ العميل ============app = Client("archiver",api_id=API_ID,api_hash=API_HASH,session_string=SESSION_STRING,in_memory=True,device_model="Samsung Galaxy S23 Ultra",system_version="Android 14",app_version="10.14.1",2 unmodified linesTARGET_CHAT = None# 🔑 Lock واحد لكل العمليات — يمنع فتح DCs متعددةdownload_lock = asyncio.Lock()# ============ معرفة نوع الملف + الامتداد ============def get_media_info(message):23 unmodified linesreturn chat.first_name or chat.username or "خاص"return "مصدر"# ============ الألبومات ============media_groups = {}mg_lock = asyncio.Lock()12 unmodified linesmessages.sort(key=lambda m: m.id)logger.info(f"📦 ألبوم {mg_id} يحتوي على {len(messages)} ملفات")downloaded = []for i, msg in enumerate(messages):m_type, ext = get_media_info(msg)if not m_type:continuecap = msg.caption if i == 0 else ""src_name = get_source_name(msg)final_cap = f"{cap}\n\n📌 المصدر: {src_name}".strip() if cap else f"📌 المصدر: {src_name}"# 🔑 استخدام Lock + app.download_media() بدلاً من message.download()async with download_lock:try:file_path = await app.download_media(msg,file_name=f"{DOWNLOAD_DIR}/{chat_id}_{msg.id}{ext}")if file_path and os.path.exists(file_path) and os.path.getsize(file_path) > 0:downloaded.append((m_type, file_path, final_cap))logger.info(f"⬇️ تم التنزيل: {msg.id}")else:logger.warning(f"⚠️ فشل تنزيل: {msg.id}")except Exception as e:logger.error(f"❌ خطأ تنزيل {msg.id}: {e}")if not downloaded:return# 🔑 إرسال الألبوم تحت Lockasync with download_lock:try:media_list = []for idx, (m_type, fpath, cap) in enumerate(downloaded):item_cap = cap if idx == 0 else ""if m_type == "photo":media_list.append(InputMediaPhoto(media=fpath, caption=item_cap))elif m_type == "video":media_list.append(InputMediaVideo(media=fpath, caption=item_cap, supports_streaming=True))elif m_type == "doc":media_list.append(InputMediaDocument(media=fpath, caption=item_cap))elif m_type == "audio":media_list.append(InputMediaAudio(media=fpath, caption=item_cap))if media_list:await app.send_media_group(TARGET_CHAT, media=media_list)logger.info(f"✅ تم إرسال الألبوم {mg_id}")except FloodWait as e:logger.warning(f"⏳ FloodWait: {e.value} ثانية")await asyncio.sleep(e.value + 5)await app.send_media_group(TARGET_CHAT, media=media_list)except Exception as e:logger.error(f"❌ فشل إرسال الألبوم: {e}")finally:for _, fpath, _ in downloaded:try:if os.path.exists(fpath):os.remove(fpath)except:pass# ============ المعالج الرئيسي ============@app.on_message(filters.incoming & ~filters.me & filters.media)async def on_media(client, message):chat_id = message.chat.id2 unmodified linesreturnsrc_name = get_source_name(message)logger.info(f"📥 جديد من {chat_id} | {src_name} | نوع: {message.chat.type} | رسالة {message.id} | نوع: {message.media}")if message.media_group_id:key = (chat_id, message.media_group_id)async with mg_lock:3 unmodified linesmedia_groups[key].append(message)returnm_type, ext = get_media_info(message)if not m_type:returnsrc_name = get_source_name(message)raw_cap = message.caption or ""final_cap = f"{raw_cap}\n\n📌 المصدر: {src_name}".strip() if raw_cap else f"📌 المصدر: {src_name}"file_path = None# 🔑 Lock يضمن عملية واحدة فقط في الوقت — يمنع فتح DCs متعددةasync with download_lock:try:# 🔑 app.download_media() أكثر استقراراً من message.download()file_path = await app.download_media(message,file_name=f"{DOWNLOAD_DIR}/{chat_id}_{message.id}{ext}")if not file_path or not os.path.exists(file_path) or os.path.getsize(file_path) == 0:logger.warning(f"⚠️ فشل تنزيل الرسالة {message.id}")returnif m_type == "photo":await app.send_photo(TARGET_CHAT, photo=file_path, caption=final_cap)elif m_type == "video":await app.send_video(TARGET_CHAT, video=file_path, caption=final_cap, supports_streaming=True)elif m_type == "doc":await app.send_document(TARGET_CHAT, document=file_path, caption=final_cap)elif m_type == "audio":await app.send_audio(TARGET_CHAT, audio=file_path, caption=final_cap)elif m_type == "voice":await app.send_voice(TARGET_CHAT, voice=file_path, caption=final_cap)elif m_type == "video_note":await app.send_video_note(TARGET_CHAT, video_note=file_path)elif m_type == "animation":await app.send_animation(TARGET_CHAT, animation=file_path, caption=final_cap)logger.info(f"✅ تم الإرسال: {message.id}")except FloodWait as e:logger.warning(f"⏳ FloodWait: {e.value} ثانية")await asyncio.sleep(e.value + 5)except RPCError as e:logger.error(f"❌ خطأ Telegram: {e}")except Exception as e:logger.error(f"❌ خطأ: {e}")finally:if file_path and os.path.exists(file_path):try:os.remove(file_path)except:pass# ============ مراقبة عامة ============@app.on_message(filters.incoming & ~filters.me)1 unmodified lineif str(message.chat.id) == str(TARGET_CHAT):returnsrc_name = get_source_name(message)logger.info(f"👁️ رسالة من {message.chat.id} | نوع: {message.chat.type} | اسم: {src_name}")# ============ التحقق من القناة الهدف ============async def resolve_target_chat():23 unmodified linesgr.Textbox(label="الحالة",value="✅ نشط - يستقبل من الكل",interactive=False)21 unmodified lineslogger.info(f"🚀 البوت يعمل!")logger.info(f"👤 الحساب: {me.first_name} (@{me.username})")logger.info(f"🎯 القناة الهدف: {TARGET_CHAT}")logger.info("📡 المصدر: الكل (قنوات + مجموعات + خاص)")logger.info("=" * 50)stop_event = asyncio.Event()29 unmodified lines30313233343536373839404142432 unmodified lines464748495051525323 unmodified lines7778798081828312 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571582 unmodified lines1611621631641651661671681693 unmodified lines1731741751761771781791801811821831841851861871881891901 unmodified line19219319419519619719823 unmodified lines22222322422522622722821 unmodified lines25025125225325425525629 unmodified linesDOWNLOAD_DIR = os.path.join(DATA_DIR, "downloads")os.makedirs(DOWNLOAD_DIR, exist_ok=True)# ============ العميل — workers=1 يمنع فتح Media DCs متعددة ============app = Client("archiver",api_id=API_ID,api_hash=API_HASH,session_string=SESSION_STRING,in_memory=True,workers=1, # 🔑 المفتاح: worker واحد فقط — يمنع فتح Media DCs متعددةdevice_model="Samsung Galaxy S23 Ultra",system_version="Android 14",app_version="10.14.1",2 unmodified linesTARGET_CHAT = None# 🔑 Semaphore واحد — يضمن عملية واحدة فقط في الوقتdownload_sem = asyncio.Semaphore(1)# ============ معرفة نوع الملف + الامتداد ============def get_media_info(message):23 unmodified linesreturn chat.first_name or chat.username or "خاص"return "مصدر"# ============ إرسال الألبومات ============media_groups = {}mg_lock = asyncio.Lock()12 unmodified linesmessages.sort(key=lambda m: m.id)logger.info(f"📦 ألبوم {mg_id} يحتوي على {len(messages)} ملفات")# 🔑 المحاولة 1: استخدام copy (أسرع، لا يحتاج Media DC)async with download_sem:for msg in messages:try:await msg.copy(chat_id=TARGET_CHAT)logger.info(f"✅ تم النسخ: {msg.id}")await asyncio.sleep(2)except Exception as e:logger.warning(f"⚠️ فشل النسخ {msg.id}: {e}")# 🔑 المحاولة 2: تحميل وإرسالawait download_and_send_single(msg)async def download_and_send_single(message):"""تحميل وإرسال رسالة واحدة — fallback"""m_type, ext = get_media_info(message)if not m_type:returnsrc_name = get_source_name(message)raw_cap = message.caption or ""final_cap = f"{raw_cap}\n\n📌 المصدر: {src_name}".strip() if raw_cap else f"📌 المصدر: {src_name}"file_path = Nonetry:file_path = await app.download_media(message,file_name=f"{DOWNLOAD_DIR}/{message.chat.id}_{message.id}{ext}")if not file_path or not os.path.exists(file_path) or os.path.getsize(file_path) == 0:returnif m_type == "photo":await app.send_photo(TARGET_CHAT, photo=file_path, caption=final_cap)elif m_type == "video":await app.send_video(TARGET_CHAT, video=file_path, caption=final_cap, supports_streaming=True)elif m_type == "doc":await app.send_document(TARGET_CHAT, document=file_path, caption=final_cap)elif m_type == "audio":await app.send_audio(TARGET_CHAT, audio=file_path, caption=final_cap)elif m_type == "voice":await app.send_voice(TARGET_CHAT, voice=file_path, caption=final_cap)elif m_type == "video_note":await app.send_video_note(TARGET_CHAT, video_note=file_path)elif m_type == "animation":await app.send_animation(TARGET_CHAT, animation=file_path, caption=final_cap)logger.info(f"✅ تم الإرسال: {message.id}")except Exception as e:logger.error(f"❌ فشل الإرسال {message.id}: {e}")finally:if file_path and os.path.exists(file_path):try:os.remove(file_path)except:pass# ============ المعالج الرئيسي — يستقبل كل شيء حتى المحول ============@app.on_message(filters.incoming & ~filters.me & filters.media)async def on_media(client, message):chat_id = message.chat.id2 unmodified linesreturnsrc_name = get_source_name(message)logger.info(f"📥 جديد من {chat_id} | {src_name} | نوع: {message.chat.type} | رسالة {message.id} | نوع: {message.media} | محول: {message.forward_from_chat is not None}")# إذا ألبومif message.media_group_id:key = (chat_id, message.media_group_id)async with mg_lock:3 unmodified linesmedia_groups[key].append(message)return# رسالة منفردةasync with download_sem:# 🔑 المحاولة 1: copy (يعمل مع المحول أيضاً إذا القناة تسمح)try:await message.copy(chat_id=TARGET_CHAT)logger.info(f"✅ تم النسخ: {message.id}")returnexcept Exception as e:logger.warning(f"⚠️ فشل النسخ {message.id}: {e}")# 🔑 المحاولة 2: تحميل وإرسالawait download_and_send_single(message)# ============ مراقبة عامة ============@app.on_message(filters.incoming & ~filters.me)1 unmodified lineif str(message.chat.id) == str(TARGET_CHAT):returnsrc_name = get_source_name(message)logger.info(f"👁️ رسالة من {message.chat.id} | نوع: {message.chat.type} | اسم: {src_name} | محول: {message.forward_from_chat is not None}")# ============ التحقق من القناة الهدف ============async def resolve_target_chat():23 unmodified linesgr.Textbox(label="الحالة",value="✅ نشط - يستقبل من الكل حتى المحول",interactive=False)21 unmodified lineslogger.info(f"🚀 البوت يعمل!")logger.info(f"👤 الحساب: {me.first_name} (@{me.username})")logger.info(f"🎯 القناة الهدف: {TARGET_CHAT}")logger.info("📡 المصدر: الكل (قنوات + مجموعات + خاص + محول)")logger.info("=" * 50)stop_event = asyncio.Event()
bot.py+72-115