Spaces:
Running
Running
Upload 7 files
Browse filesFiles changed (7)
- DockerfileAdded+13
- README.mdAdded+13
- app.pyAdded+30
- bot_core.pyAdded+1322
- config.pyAdded+23
- database.pyAdded+412
- requirements.txtAdded+3
12345678910111213FROM python:3.9-slim
WORKDIR /code
# إنشاء مجلد البيانات الدائمةRUN mkdir -p /data
COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0"]12345678910111213---title: Teleautoadminbotemoji: 📉colorFrom: greencolorTo: yellowsdk: dockerapp_file: app.pypinned: falselicense: apache-2.0---
# بوت النشر التلقائي عبر تيليجراميعمل على Hugging Face مع Docker.123456789101112131415161718192021222324252627282930import asyncioimport threading
import streamlit as st
# إنشاء event loop لهذا الخيط قبل أي استيراد لـ pyrogramtry: asyncio.get_event_loop()except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
st.set_page_config(page_title="Telegram Auto Poster")st.title("🤖 بوت النشر التلقائي")
# متغير عام داخل نفس عملية Streamlit حتى لا يتم تشغيل البوت أكثر من مرة عند rerunif "bot_thread" not in st.session_state: st.session_state.bot_thread = None
if st.session_state.bot_thread is None or not st.session_state.bot_thread.is_alive(): from bot_core import run_bot
bot_thread = threading.Thread(target=run_bot, daemon=True, name="telegram-auto-poster") bot_thread.start() st.session_state.bot_thread = bot_thread st.success("تم تشغيل البوت بنجاح!")else: st.success("البوت يعمل مسبقاً.")
st.info("البوت يعمل في الخلفية. استخدم تيليجرام للتحكم.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322import asyncioimport reimport loggingimport tempfileimport osimport time
from pyrogram import Client, filtersfrom pyrogram.handlers import MessageHandler, CallbackQueryHandlerfrom pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButtonfrom pyrogram.errors import MessageNotModified
import configimport database as db
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
bot_client = Noneuser_client = Noneuser_states = {}_middle_peer_warmed = False_middle_auto_ignore_until = 0.0
def is_admin(user_id): return user_id in config.ADMINS
def clean_text(text): if not text: return text
if isinstance(text, str): text = re.sub(r'https?://\S+', '', text) text = re.sub(r'@\w+', '', text)
for word in db.get_blocked_words(): if word and word in text: return None
return '\n'.join(line for line in text.splitlines() if line.strip())
return text
def apply_tail(text, tail): if tail: return f"{text}\n{tail}" if text else tail return text
async def notify_admins(text): for admin_id in config.ADMINS: try: await bot_client.send_message(admin_id, f"⚠️ {text}") except Exception as e: logger.error(f"فشل إشعار الأدمن {admin_id}: {e}")
async def hydrate_peer(client, chat_id, label="peer"): """يحاول تحميل الـ peer داخل جلسة Pyrogram حتى لا يظهر Peer id invalid.""" try: chat = await client.get_chat(int(chat_id)) logger.info(f"✅ تم تحميل {label}: {getattr(chat, 'id', chat_id)}") return chat except Exception as first_error: logger.warning(f"⚠️ فشل get_chat أول مرة لـ {label}={chat_id}: {first_error}. سيتم فحص الحوارات...")
try: async for dialog in client.get_dialogs(limit=300): if dialog.chat and int(dialog.chat.id) == int(chat_id): logger.info(f"✅ تم العثور على {label} داخل الحوارات: {chat_id}") return dialog.chat except Exception as dialog_error: logger.warning(f"⚠️ فشل فحص الحوارات لـ {label}: {dialog_error}")
chat = await client.get_chat(int(chat_id)) return chat
async def warm_middle_peer(): """تحميل القناة الوسيطة داخل جلسة الحساب والبوت قبل أي تحويل ميديا.""" global _middle_peer_warmed if _middle_peer_warmed: return True
ok = True try: await hydrate_peer(user_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / user_client") except Exception as e: ok = False logger.error(f"❌ user_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}")
try: await hydrate_peer(bot_client, config.MIDDLE_CHANNEL, "القناة الوسيطة / bot_client") except Exception as e: ok = False logger.error(f"❌ bot_client لا يستطيع الوصول للقناة الوسيطة {config.MIDDLE_CHANNEL}: {e}")
_middle_peer_warmed = ok return ok
async def forward_to_middle(source_chat_id, message_ids): """يحّول رسالة أو مجموعة رسائل إلى القناة الوسيطة مع إعادة محاولة عند Peer id invalid.""" await warm_middle_peer() try: return await user_client.forward_messages( chat_id=config.MIDDLE_CHANNEL, from_chat_id=int(source_chat_id), message_ids=message_ids ) except Exception as e: logger.warning(f"⚠️ فشل التوجيه للوسيطة، سيتم إعادة تحميل الـ peer والمحاولة مرة ثانية: {e}") global _middle_peer_warmed _middle_peer_warmed = False await warm_middle_peer() return await user_client.forward_messages( chat_id=config.MIDDLE_CHANNEL, from_chat_id=int(source_chat_id), message_ids=message_ids )
async def copy_middle_messages_to_target(target, middle_messages, caption=None): """ينسخ رسائل الوسيطة لقناة النشر. يحاول الحفاظ على الألبوم قدر الإمكان.""" if not isinstance(middle_messages, (list, tuple)): middle_messages = [middle_messages]
middle_messages = [m for m in middle_messages if m] if not middle_messages: return False
# إذا كانت مجموعة ميديا، نحاول copy_media_group حتى تبقى كألبوم. if len(middle_messages) > 1: try: captions = None if caption: captions = [caption] + [""] * (len(middle_messages) - 1) await bot_client.copy_media_group( chat_id=int(target), from_chat_id=config.MIDDLE_CHANNEL, message_id=middle_messages[0].id, captions=captions ) logger.info(f"✅ نُشر ألبوم ميديا إلى {target} بعدد {len(middle_messages)}") return True except Exception as album_error: logger.warning(f"⚠️ فشل copy_media_group إلى {target}، سيتم النسخ رسالة رسالة: {album_error}")
for idx, m in enumerate(middle_messages): await bot_client.copy_message( chat_id=int(target), from_chat_id=config.MIDDLE_CHANNEL, message_id=m.id, caption=caption if idx == 0 and caption else None ) await asyncio.sleep(0.25)
logger.info(f"✅ نُشر ميديا إلى {target} بعدد {len(middle_messages)}") return True
async def safe_edit(callback, text, reply_markup=None): try: await callback.edit_message_text(text, reply_markup=reply_markup) except MessageNotModified: try: await callback.answer() except Exception: pass except Exception as e: logger.error(f"فشل تعديل الرسالة: {e}") try: await callback.answer("حدث خطأ أثناء تحديث القائمة.", show_alert=True) except Exception: pass
async def resolve_chat_id(raw, prefer_user=True): chat = await resolve_chat_info(raw, prefer_user=prefer_user) return int(chat.id)
def normalize_chat_input(raw): raw = str(raw).strip() match = re.match(r'(?:https?://)?t\.me/([A-Za-z0-9_]+)', raw) if match: raw = "@" + match.group(1) return raw
def split_bulk_lines(text): items = [] for line in str(text or "").splitlines(): line = line.strip() if not line: continue if "," in line and "t.me/" not in line: items.extend([p.strip() for p in line.split(",") if p.strip()]) else: items.append(line) seen = set() unique = [] for item in items: key = normalize_chat_input(item).lower() if key not in seen: seen.add(key) unique.append(item) return unique
async def resolve_chat_info(raw, prefer_user=True): raw = normalize_chat_input(raw) value = int(raw) if re.fullmatch(r"-?\d+", raw) else raw clients = [user_client, bot_client] if prefer_user else [bot_client, user_client] last_error = None for c in [x for x in clients if x]: try: return await c.get_chat(value) except Exception as e: last_error = e raise last_error or ValueError("تعذر جلب معلومات القناة")
def chat_title(chat, fallback=""): return getattr(chat, "title", None) or getattr(chat, "first_name", None) or getattr(chat, "username", None) or str(fallback)
def chat_username(chat): return getattr(chat, "username", None) or ""
def chat_link_from_username(username): return f"https://t.me/{username}" if username else ""
def chat_type_name(chat): return str(getattr(chat, "type", "")).replace("ChatType.", "")
def chat_meta(chat, fallback=""): username = chat_username(chat) title = chat_title(chat, fallback) return { "name": title, "title": title, "username": username, "link": chat_link_from_username(username), "chat_type": chat_type_name(chat), }
def entity_name(record_or_id, is_source=False): if isinstance(record_or_id, dict): return record_or_id.get("title") or record_or_id.get("name") or record_or_id.get("username") or str(record_or_id.get("id", "")) if is_source and hasattr(db, "get_source_meta"): return entity_name(db.get_source_meta(record_or_id)) return str(record_or_id)
def entity_details_line(item, is_source=False): if is_source: meta = db.get_source_meta(item) if not isinstance(item, dict) else item item_id = meta.get("id", item) else: meta = item item_id = item.get("id") name = entity_name(meta) username = meta.get("username") or "" username_txt = f"@{username}" if username else "لا يوجد يوزر" return f"• {name}\n {username_txt}\n ID: `{item_id}`"
async def show_public_sources_menu_from_message(message): srcs = db.get_public_sources() meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs] text = f"**المصادر العامة ({len(srcs)}):**\n" text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد." buttons = [ [InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src")], [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")], ] await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
async def show_blocked_words_menu_from_message(message): words = db.get_blocked_words() text = "**الكلمات المحظورة:**\n" + (", ".join(words) if words else "لا توجد.") buttons = [ [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")], [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")], ] await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
async def show_special_sources_menu_from_message(message, ch_id): ch = db.get_channel(ch_id) if not ch: await message.reply("❌ القناة غير موجودة.") return sources = ch.get("special_sources", []) text = "**المصادر المخصصة:**\n" text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد." buttons = [ [InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")], ] await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
def format_bulk_report(title, results): ok = [r for r in results if r[0] == "ok"] exists = [r for r in results if r[0] == "exists"] failed = [r for r in results if r[0] == "fail"] lines = [title, "", f"✅ تمت الإضافة: {len(ok)}", f"⚠️ موجود مسبقاً: {len(exists)}", f"❌ فشل: {len(failed)}"] if ok: lines.append("\n**المضافة:**") lines.extend([f"• {name}" for _, name, _ in ok[:30]]) if exists: lines.append("\n**الموجودة مسبقاً:**") lines.extend([f"• {name}" for _, name, _ in exists[:20]]) if failed: lines.append("\n**الفاشلة:**") lines.extend([f"• {raw}: {err}" for _, raw, err in failed[:20]]) return "\n".join(lines)
main_keyboard = InlineKeyboardMarkup([ [ InlineKeyboardButton("📢 إدارة قنوات النشر", callback_data="menu_channels"), InlineKeyboardButton("🌐 إدارة المصادر العامة", callback_data="menu_public_src") ], [ InlineKeyboardButton("🚫 إدارة الكلمات المحظورة", callback_data="menu_blocked"), InlineKeyboardButton("📊 إدارة الإحصائيات", callback_data="stats") ], [ InlineKeyboardButton("📥 تصدير الإعدادات", callback_data="export_data"), InlineKeyboardButton("📤 استيراد الإعدادات", callback_data="import_data") ]])
async def start(client, message): user_id = message.from_user.id user_states.pop(user_id, None)
logger.info(f"📥 /start من ID: {user_id}")
if not is_admin(user_id): await message.reply(f"❌ غير مصرح. معرفك: `{user_id}`") return
await message.reply("أهلاً بك في لوحة تحكم البوت:", reply_markup=main_keyboard)
async def export_callback(client, callback): try: data_str = db.export_data()
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False, encoding='utf-8') as tmp: tmp.write(data_str) tmp_path = tmp.name
await callback.message.reply_document(document=tmp_path, file_name=f"backup_{int(time.time())}.json") os.unlink(tmp_path) await callback.answer("تم إرسال ملف النسخة الاحتياطية.") except Exception as e: logger.error(f"فشل التصدير: {e}") await callback.answer("فشل التصدير.", show_alert=True)
async def import_callback(client, callback): user_states[callback.from_user.id] = {"state": "waiting_import"} await safe_edit(callback, "أرسل ملف JSON الذي تريد استيراده:")
async def handle_import(client, message): if not is_admin(message.from_user.id): return
uid = message.from_user.id
if uid not in user_states or user_states[uid].get("state") != "waiting_import": return
if not message.document: await message.reply("❌ أرفق ملف JSON صحيح.") return
try: file_path = await message.download() with open(file_path, "r", encoding="utf-8") as f: data = f.read()
result = db.import_data(data) if isinstance(result, dict): report = ( "✅ تم استيراد الإعدادات بنجاح.\n\n" f"• قنوات النشر: {result.get('channels', 0)}\n" f"• المصادر العامة: {result.get('public_sources', 0)}\n" f"• الكلمات المحظورة: {result.get('blocked_words', 0)}\n" f"• آخر رسائل المصادر: {result.get('last_source_messages', 0)}" ) else: report = "✅ تم استيراد الإعدادات بنجاح." await message.reply(report, reply_markup=main_keyboard) except Exception as e: await message.reply(f"❌ فشل الاستيراد: {e}") finally: user_states.pop(uid, None)
def channel_buttons(ch_id, ch): paused_text = "⏸️ موقوفة" if ch.get('paused') else "✅ شغالة"
return InlineKeyboardMarkup([ [InlineKeyboardButton(f"⏯️ {paused_text}", callback_data=f"toggle_{ch_id}")], [InlineKeyboardButton("📝 التوقيع", callback_data=f"tailmenu_{ch_id}")], [InlineKeyboardButton("🔍 المصادر المخصصة", callback_data=f"specsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف القناة", callback_data=f"delchannel_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")] ])
async def menu_channels(client, callback): channels = db.get_all_channels()
if not channels: text = "لا توجد قنوات." buttons = [[InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]] else: text = f"**قنوات النشر ({len(channels)}):**\n" buttons = [] for ch in channels: paused = " ⏸️" if ch.get('paused') else "" name = entity_name(ch) username = ch.get("username") or "" username_txt = f"@{username}" if username else "لا يوجد يوزر" text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n" buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")]) buttons.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]) await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def show_channels_menu_from_message(message): channels = db.get_all_channels() if not channels: text = "لا توجد قنوات." buttons = [[InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]] else: text = f"**قنوات النشر ({len(channels)}):**\n" buttons = [] for ch in channels: paused = " ⏸️" if ch.get('paused') else "" name = entity_name(ch) username = ch.get("username") or "" username_txt = f"@{username}" if username else "لا يوجد يوزر" text += f"\n✅ {name}{paused}\n {username_txt}\n ID: `{ch['id']}`\n" buttons.append([InlineKeyboardButton(f"{name} ⚙️", callback_data=f"ch_{ch['id']}")]) buttons.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]) await message.reply(text, reply_markup=InlineKeyboardMarkup(buttons))
async def channel_settings(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id) if not ch: await callback.answer("غير موجودة.") return name = entity_name(ch) username = ch.get("username") or "" username_txt = f"@{username}" if username else "لا يوجد يوزر" text = ( f"📢 **اسم القناة:**\n{name}\n\n" f"👤 **اليوزر:** {username_txt}\n" f"🆔 **ID:** `{ch_id}`\n" f"📊 **الحالة:** {'⏸️ موقوفة' if ch.get('paused') else '✅ شغالة'}\n" f"🧾 **عدد المنشورات:** {ch.get('posts_count', 0)}\n" f"📝 **التوقيع:** {ch.get('tail') or 'لا يوجد'}" ) await safe_edit(callback, text, channel_buttons(ch_id, ch))
async def add_channel_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_channel_id"} await safe_edit(callback, "أرسل قناة واحدة أو عدة قنوات نشر.\nكل رابط/يوزر/ID بسطر مستقل:")
async def toggle_pause(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
db.update_channel(ch_id, "paused", not ch.get("paused")) await callback.answer("تم التحديث.") await channel_settings(client, callback)
async def delete_channel_prompt(client, callback): channels = db.get_all_channels() if not channels: await callback.answer("لا توجد قنوات.") return buttons = [] for ch in channels: name = entity_name(ch) buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confirm_del_{ch['id']}")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels")]) await safe_edit(callback, "اختر القناة التي تريد حذفها:", InlineKeyboardMarkup(buttons))
async def confirm_delete_channel(client, callback): ch_id = callback.data.split("_", 2)[2] db.delete_channel(ch_id) await callback.answer("تم الحذف.") await menu_channels(client, callback)
async def tail_menu(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
current = ch.get("tail", "") text = f"التوقيع الحالي:\n`{current}`" if current else "لا يوجد توقيع."
buttons = [ [InlineKeyboardButton("✏️ تعديل/إضافة", callback_data=f"edittail_{ch_id}")], [InlineKeyboardButton("🗑 حذف التوقيع", callback_data=f"deltail_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def edit_tail_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_tail", "ch_id": ch_id} await safe_edit(callback, "أرسل نص التوقيع الجديد:")
async def delete_tail(client, callback): ch_id = callback.data.split("_", 1)[1] db.update_channel(ch_id, "tail", "") await callback.answer("تم حذف التوقيع.") await tail_menu(client, callback)
async def menu_public_sources(client, callback): srcs = db.get_public_sources() meta_list = db.get_all_public_sources_with_meta() if hasattr(db, "get_all_public_sources_with_meta") else [{"id": s, "name": str(s)} for s in srcs] text = f"**المصادر العامة ({len(srcs)}):**\n" text += "\n\n".join(entity_details_line(m, is_source=True) for m in meta_list) if srcs else "لا توجد." buttons = [[InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src")], [InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]] await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_public_src_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_public_source"} await safe_edit(callback, "أرسل مصدر واحد أو عدة مصادر عامة.\nكل رابط/يوزر/ID بسطر مستقل:")
async def del_public_src_prompt(client, callback): srcs = db.get_public_sources() if not srcs: await callback.answer("لا توجد مصادر.") return buttons = [] for idx, src in enumerate(srcs): name = entity_name(src, is_source=True) buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"del_pub_idx_{idx}")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_public_src")]) await safe_edit(callback, "اختر المصدر للحذف:", InlineKeyboardMarkup(buttons))
async def confirm_del_public_src(client, callback): idx = int(callback.data.split("_")[-1]) srcs = db.get_public_sources()
if idx < 0 or idx >= len(srcs): await callback.answer("المصدر غير موجود.") return
db.remove_public_source(srcs[idx]) await callback.answer("تم الحذف.") await menu_public_sources(client, callback)
async def menu_blocked_words(client, callback): words = db.get_blocked_words()
text = "**الكلمات المحظورة:**\n" text += ", ".join(words) if words else "لا توجد."
buttons = [ [InlineKeyboardButton("➕ إضافة كلمة", callback_data="add_blocked_word")], [InlineKeyboardButton("🗑 حذف كلمة", callback_data="del_blocked_word")], [InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")] ]
await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_blocked_word_prompt(client, callback): user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = {"state": "waiting_blocked_word"} await safe_edit(callback, "أرسل الكلمة المحظورة:")
async def del_blocked_word_prompt(client, callback): words = db.get_blocked_words()
if not words: await callback.answer("لا توجد.") return
buttons = []
for idx, word in enumerate(words): buttons.append([InlineKeyboardButton(f"حذف {word}", callback_data=f"delword_idx_{idx}")])
buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_blocked")]) await safe_edit(callback, "اختر الكلمة:", InlineKeyboardMarkup(buttons))
async def confirm_del_blocked_word(client, callback): idx = int(callback.data.split("_")[-1]) words = db.get_blocked_words()
if idx < 0 or idx >= len(words): await callback.answer("الكلمة غير موجودة.") return
db.remove_blocked_word(words[idx]) await callback.answer("تم الحذف.") await menu_blocked_words(client, callback)
async def manage_special_sources(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id) if not ch: await callback.answer("غير موجودة.") return sources = ch.get("special_sources", []) text = "**المصادر المخصصة:**\n" text += "\n".join(f"• {entity_name(s, is_source=True)}\n ID: `{s}`" for s in sources) if sources else "لا توجد." buttons = [[InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}")], [InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")], [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")]] await safe_edit(callback, text, InlineKeyboardMarkup(buttons))
async def add_special_source_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] user_states.pop(callback.from_user.id, None) user_states[callback.from_user.id] = { "state": "waiting_special_source", "ch_id": ch_id } await safe_edit(callback, "أرسل رابط أو يوزر أو ID المصدر المخصص:")
async def delete_special_source_prompt(client, callback): ch_id = callback.data.split("_", 1)[1] ch = db.get_channel(ch_id) if not ch: await callback.answer("غير موجودة.") return sources = ch.get("special_sources", []) if not sources: await callback.answer("لا توجد مصادر.") return buttons = [] for idx, src in enumerate(sources): name = entity_name(src, is_source=True) buttons.append([InlineKeyboardButton(f"🗑 حذف {name}", callback_data=f"confdelspec_{ch_id}_{idx}")]) buttons.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"specsrc_{ch_id}")]) await safe_edit(callback, "اختر المصدر لحذفه:", InlineKeyboardMarkup(buttons))
async def confirm_delete_special_source(client, callback): parts = callback.data.split("_") ch_id = parts[1] idx = int(parts[2])
ch = db.get_channel(ch_id)
if not ch: await callback.answer("غير موجودة.") return
sources = ch.get("special_sources", [])
if idx < 0 or idx >= len(sources): await callback.answer("المصدر غير موجود.") return
sources.pop(idx) db.update_channel(ch_id, "special_sources", sources)
await callback.answer("تم الحذف.") await manage_special_sources(client, callback)
async def show_stats(client, callback): channels = db.get_all_channels() total_posts = sum(ch.get("posts_count", 0) for ch in channels) pub_src = len(db.get_public_sources()) words = len(db.get_blocked_words())
text = "📊 **الإحصائيات:**\n\n" text += f"• إجمالي المنشورات: **{total_posts}**\n" text += f"• قنوات النشر: {len(channels)}\n" text += f"• المصادر العامة: {pub_src}\n" text += f"• الكلمات المحظورة: {words}\n\n"
if channels: text += "**تفصيل المنشورات:**\n" for ch in channels: text += f"`{ch['id']}`: {ch.get('posts_count', 0)}\n"
await safe_edit( callback, text, InlineKeyboardMarkup([[InlineKeyboardButton("🔙 رجوع", callback_data="main_menu")]]) )
async def handle_text_input(client, message): if not is_admin(message.from_user.id): return uid = message.from_user.id if uid not in user_states: return state = user_states[uid].get("state") text = message.text.strip() try: if state == "waiting_channel_id": results = [] for raw in split_bulk_lines(text): try: chat = await resolve_chat_info(raw, prefer_user=False) meta = chat_meta(chat, raw) created = db.add_channel(chat.id, **meta) results.append(("ok" if created else "exists", meta["title"], raw)) except Exception as e: results.append(("fail", raw, str(e))) await message.reply(format_bulk_report("📢 نتيجة إضافة قنوات النشر", results)) await show_channels_menu_from_message(message) elif state == "waiting_tail": ch_id = user_states[uid]["ch_id"] db.update_channel(ch_id, "tail", text) await message.reply("✅ تم حفظ التوقيع.") ch = db.get_channel(ch_id) if ch: await message.reply(f"إعدادات القناة: {entity_name(ch)}", reply_markup=channel_buttons(ch_id, ch)) elif state == "waiting_public_source": results = [] for raw in split_bulk_lines(text): try: chat = await resolve_chat_info(raw, prefer_user=True) meta = chat_meta(chat, raw) created = db.add_public_source(chat.id, **meta) results.append(("ok" if created else "exists", meta["title"], raw)) except Exception as e: results.append(("fail", raw, str(e))) await message.reply(format_bulk_report("🌐 نتيجة إضافة المصادر العامة", results)) await show_public_sources_menu_from_message(message) elif state == "waiting_blocked_word": added = 0 exists = 0 for word in split_bulk_lines(text): if db.add_blocked_word(word): added += 1 else: exists += 1 await message.reply(f"✅ تمت إضافة {added} كلمة.\n⚠️ موجودة مسبقاً/فارغة: {exists}") await show_blocked_words_menu_from_message(message) elif state == "waiting_special_source": ch_id = user_states[uid]["ch_id"] ch = db.get_channel(ch_id) if not ch: await message.reply("❌ القناة غير موجودة.") return sources = ch.get("special_sources", []) results = [] for raw in split_bulk_lines(text): try: chat = await resolve_chat_info(raw, prefer_user=True) meta = chat_meta(chat, raw) db.update_source_meta(chat.id, **meta) if hasattr(db, "update_source_meta") else None if int(chat.id) not in [int(x) for x in sources]: sources.append(int(chat.id)) results.append(("ok", meta["title"], raw)) else: results.append(("exists", meta["title"], raw)) except Exception as e: results.append(("fail", raw, str(e))) db.update_channel(ch_id, "special_sources", sources) await message.reply(format_bulk_report("🔍 نتيجة إضافة المصادر المخصصة", results)) await show_special_sources_menu_from_message(message, ch_id) except Exception as e: logger.error(f"خطأ في إدخال المستخدم: {e}") await message.reply(f"❌ فشل التنفيذ: {e}") finally: user_states.pop(uid, None)
def _to_int_set(values): result = set() for value in values or []: try: result.add(int(value)) except Exception: pass return result
def get_targets_for_source(source_id): """يرجع قنوات النشر التي يجب أن تستقبل منشوراً من هذا المصدر.""" source_id = int(source_id) all_channels = db.get_all_channels() public_sources = _to_int_set(db.get_public_sources()) target_ids = set()
logger.info(f"🧭 فحص المصدر {source_id}") logger.info(f"🧭 المصادر العامة المخزونة: {sorted(public_sources)}") logger.info(f"🧭 عدد قنوات النشر: {len(all_channels)}")
if source_id in public_sources: logger.info("🟢 المصدر مطابق للمصادر العامة") for ch in all_channels: specials = ch.get("special_sources") or [] paused = bool(ch.get("paused")) logger.info(f"🧭 قناة {ch.get('id')} | paused={paused} | special_sources={specials}") if not specials and not paused: try: target_ids.add(int(ch["id"])) except Exception as e: logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}") else: logger.info("🟡 المصدر غير موجود ضمن المصادر العامة")
for ch in all_channels: paused = bool(ch.get("paused")) specials = _to_int_set(ch.get("special_sources") or []) if source_id in specials and not paused: try: target_ids.add(int(ch["id"])) logger.info(f"🟢 المصدر مطابق لمصدر مخصص للقناة {ch.get('id')}") except Exception as e: logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}")
logger.info(f"🎯 القنوات المستهدفة: {target_ids}") return target_ids
def blocked_word_in_text(text): if not text: return None for word in db.get_blocked_words(): if word and word in text: return word return None
def unsupported_media_reason(message): """يرجع سبب التجاهل إذا كان المنشور يحتوي ملصق أو صورة متحركة/GIF.""" if getattr(message, "sticker", None): return "ملصق" if getattr(message, "animation", None): return "صورة متحركة / GIF" return None
def mark_middle_auto_forward_window(seconds=4): """يمنع middle_channel_handler من نشر النسخة التي وصلت للوسيطة تلقائياً حتى لا تتكرر.""" global _middle_auto_ignore_until _middle_auto_ignore_until = max(_middle_auto_ignore_until, time.monotonic() + seconds)
def is_middle_auto_forward_window_active(): return time.monotonic() <= _middle_auto_ignore_until
async def publish_source_message(message, source_id, origin="updates"): raw_text = message.text or message.caption or "" source_id = int(source_id)
logger.info(f"📨 [{origin}] رسالة من {source_id} | message_id={message.id} | نص: {str(raw_text)[:80]}...")
target_ids = get_targets_for_source(source_id) if not target_ids: logger.info("🟡 لا توجد قنوات مستهدفة لهذا المصدر، تم اعتبار المنشور معالجاً حتى لا يتكرر.") return True
bad_word = blocked_word_in_text(raw_text) if bad_word: logger.info(f"⛔ منشور مرفوض بسبب كلمة محظورة: {bad_word}") return True
unsupported_reason = unsupported_media_reason(message) if unsupported_reason: logger.info(f"⛔ تم تجاهل المنشور لأنه يحتوي {unsupported_reason}") return True
if message.media: try: mark_middle_auto_forward_window() fwd = await forward_to_middle(message.chat.id, message.id) mark_middle_auto_forward_window() await asyncio.sleep(0.5) middle_messages = fwd if isinstance(fwd, list) else [fwd] middle_messages = [m for m in middle_messages if m] logger.info(f"✅ تم تمرير منشور ميديا إلى الوسيطة | ids={[m.id for m in middle_messages]}") except Exception as e: logger.error(f"فشل التوجيه للوسيطة من المصدر {source_id}: {e}") await notify_admins(f"فشل توجيه رسالة من {source_id} إلى الوسيطة: {e}") return False
any_success = False for target in target_ids: try: ch = db.get_channel(target) if not ch: logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") continue
cleaned = clean_text(raw_text) if cleaned is None: logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") continue
final = apply_tail(cleaned, ch.get("tail", "")) ok = await copy_middle_messages_to_target(target, middle_messages, final if final else None) if ok: db.increment_post_count(target) any_success = True await asyncio.sleep(0.5)
except Exception as e: logger.error(f"نشر فاشل إلى {target}: {e}") await notify_admins(f"فشل النشر إلى {target}: {e}")
return any_success
else: any_success = False for target in target_ids: try: ch = db.get_channel(target) if not ch: logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") continue
cleaned = clean_text(raw_text) if cleaned is None: logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") continue
final = apply_tail(cleaned, ch.get("tail", ""))
if final: await bot_client.send_message(target, final) else: logger.info("🟡 منشور نصي فارغ بعد التنظيف؛ لن يتم إرساله.") continue
db.increment_post_count(target) any_success = True logger.info(f"✅ نُشر نص إلى {target}") await asyncio.sleep(0.5)
except Exception as e: logger.error(f"إرسال فاشل إلى {target}: {e}") await notify_admins(f"فشل الإرسال إلى {target}: {e}")
return any_success
async def publish_source_album(messages, source_id, origin="polling"): """ينشر مجموعة ميديا من المصدر إلى الوسيطة ثم إلى قنوات النشر بنفس ترتيب الرسائل.""" if not messages: return True
messages = sorted(messages, key=lambda m: m.id) first = messages[0] raw_text = first.caption or first.text or "" source_id = int(source_id) ids = [m.id for m in messages]
logger.info(f"📨 [{origin}] ألبوم من {source_id} | message_ids={ids} | نص: {str(raw_text)[:80]}...")
target_ids = get_targets_for_source(source_id) if not target_ids: logger.info("🟡 لا توجد قنوات مستهدفة لهذا الألبوم، تم اعتباره معالجاً حتى لا يتكرر.") return True
bad_word = blocked_word_in_text(raw_text) if bad_word: logger.info(f"⛔ ألبوم مرفوض بسبب كلمة محظورة: {bad_word}") return True
for item in messages: unsupported_reason = unsupported_media_reason(item) if unsupported_reason: logger.info(f"⛔ تم تجاهل الألبوم لأنه يحتوي {unsupported_reason}") return True
try: mark_middle_auto_forward_window() fwd = await forward_to_middle(source_id, ids) mark_middle_auto_forward_window() await asyncio.sleep(0.8) middle_messages = fwd if isinstance(fwd, list) else [fwd] middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) logger.info(f"✅ تم تمرير الألبوم إلى الوسيطة | middle_ids={[m.id for m in middle_messages]}") except Exception as e: logger.error(f"فشل توجيه الألبوم للوسيطة من المصدر {source_id}: {e}") await notify_admins(f"فشل توجيه ألبوم من {source_id} إلى الوسيطة: {e}") return False
any_success = False for target in target_ids: try: ch = db.get_channel(target) if not ch: logger.warning(f"القناة {target} غير موجودة في قاعدة البيانات") continue
cleaned = clean_text(raw_text) if cleaned is None: logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") continue
final = apply_tail(cleaned, ch.get("tail", "")) ok = await copy_middle_messages_to_target(target, middle_messages, final if final else None) if ok: db.increment_post_count(target) any_success = True await asyncio.sleep(0.5)
except Exception as e: logger.error(f"نشر الألبوم فاشل إلى {target}: {e}") await notify_admins(f"فشل نشر ألبوم إلى {target}: {e}")
return any_success
async def user_message_handler(client, message): logger.info(f"🔥 user_client استلم تحديث | chat={getattr(message.chat, 'id', None)} | type={getattr(message.chat, 'type', None)}")
if not message.chat or message.chat.type not in ("channel", "supergroup"): return
await publish_source_message(message, int(message.chat.id), origin="updates")
async def poll_public_sources_loop(): """يفحص المصادر العامة دورياً، لأن Updates لا تصل أحياناً على Hugging Face.""" await asyncio.sleep(8) logger.info("🔁 بدأ نظام الفحص الدوري للمصادر العامة Polling")
while True: try: public_sources = db.get_public_sources() if not public_sources: logger.info("🔁 لا توجد مصادر عامة للفحص.") await asyncio.sleep(25) continue
logger.info(f"🔁 فحص المصادر العامة: {public_sources}")
for source in public_sources: try: source_id = int(source) except Exception: logger.warning(f"مصدر غير رقمي تم تجاهله: {source}") continue
try: last_seen = db.get_last_source_message(source_id) messages = []
async for msg in user_client.get_chat_history(source_id, limit=8): if not msg or not getattr(msg, "id", None): continue messages.append(msg)
if not messages: logger.info(f"🔁 المصدر {source_id}: لا توجد رسائل مقروءة.") continue
newest_id = max(m.id for m in messages)
if last_seen is None: db.set_last_source_message(source_id, newest_id) logger.info(f"🔁 المصدر {source_id}: أول تشغيل، تم حفظ آخر رسالة {newest_id} بدون نشر القديم.") continue
new_messages = [m for m in messages if m.id > int(last_seen)] new_messages.sort(key=lambda m: m.id)
if not new_messages: logger.info(f"🔁 المصدر {source_id}: لا توجد منشورات جديدة. last_seen={last_seen}") continue
logger.info(f"🔁 المصدر {source_id}: تم العثور على {len(new_messages)} منشور جديد.")
processed_ids = set() i = 0 while i < len(new_messages): msg = new_messages[i] if msg.id in processed_ids: i += 1 continue
media_group_id = getattr(msg, "media_group_id", None) if media_group_id: group = [m for m in new_messages if getattr(m, "media_group_id", None) == media_group_id] group.sort(key=lambda m: m.id) ok = await publish_source_album(group, source_id, origin="polling") if ok: for gm in group: processed_ids.add(gm.id) db.set_last_source_message(source_id, max(gm.id for gm in group)) else: logger.warning(f"⚠️ لم يتم تحديث last_seen للألبوم {media_group_id} حتى يعاد المحاولة لاحقاً") await asyncio.sleep(1) else: ok = await publish_source_message(msg, source_id, origin="polling") if ok: processed_ids.add(msg.id) db.set_last_source_message(source_id, msg.id) else: logger.warning(f"⚠️ لم يتم تحديث last_seen للرسالة {msg.id} حتى تعاد المحاولة لاحقاً") await asyncio.sleep(1) i += 1
except Exception as e: logger.exception(f"خطأ أثناء فحص المصدر {source}: {e}") await notify_admins(f"فشل فحص المصدر {source}: {e}")
await asyncio.sleep(25)
except Exception as e: logger.exception(f"خطأ عام في حلقة Polling: {e}") await asyncio.sleep(30)
async def middle_channel_handler(client, message): if int(message.chat.id) != int(config.MIDDLE_CHANNEL): return
if is_middle_auto_forward_window_active(): logger.info(f"🟡 تم تجاهل رسالة وسيطة تلقائية لمنع التكرار | message_id={message.id}") return
logger.info("📥 رسالة في الوسيطة، جارٍ النشر...")
all_channels = db.get_all_channels() raw_text = message.text or message.caption or ""
unsupported_reason = unsupported_media_reason(message) if unsupported_reason: logger.info(f"⛔ تم تجاهل رسالة الوسيطة لأنها تحتوي {unsupported_reason}") return
if raw_text and any(w in raw_text for w in db.get_blocked_words()): logger.info("⛔ كلمة محظورة - لم تُنشر") return
for ch in all_channels: if ch.get("paused"): continue
target = int(ch["id"])
try: cleaned = clean_text(raw_text) if raw_text else "" if cleaned is None: continue
final = apply_tail(cleaned, ch.get("tail", ""))
if message.media: await bot_client.copy_message( chat_id=target, from_chat_id=config.MIDDLE_CHANNEL, message_id=message.id, caption=final if final else None ) else: await bot_client.send_message(target, final if final else ".")
db.increment_post_count(target) logger.info(f"✅ نُشر من الوسيطة إلى {target}") await asyncio.sleep(0.5)
except Exception as e: logger.error(f"نشر فاشل من الوسيطة إلى {target}: {e}") await notify_admins(f"فشل النشر من الوسيطة إلى {target}: {e}")
def register_bot_handlers(app: Client): app.add_handler(MessageHandler(start, filters.command("start"))) app.add_handler(MessageHandler(handle_import, filters.document))
async def callback_dispatcher(client, callback): data = callback.data
if data == "main_menu": await safe_edit(callback, "القائمة الرئيسية:", main_keyboard) elif data == "menu_channels": await menu_channels(client, callback) elif data.startswith("ch_"): await channel_settings(client, callback) elif data == "add_channel": await add_channel_prompt(client, callback) elif data.startswith("toggle_"): await toggle_pause(client, callback) elif data.startswith("delchannel_"): await delete_channel_prompt(client, callback) elif data.startswith("confirm_del_"): await confirm_delete_channel(client, callback) elif data.startswith("tailmenu_"): await tail_menu(client, callback) elif data.startswith("edittail_"): await edit_tail_prompt(client, callback) elif data.startswith("deltail_"): await delete_tail(client, callback) elif data == "menu_public_src": await menu_public_sources(client, callback) elif data == "add_public_src": await add_public_src_prompt(client, callback) elif data == "del_public_src": await del_public_src_prompt(client, callback) elif data.startswith("del_pub_idx_"): await confirm_del_public_src(client, callback) elif data == "menu_blocked": await menu_blocked_words(client, callback) elif data == "add_blocked_word": await add_blocked_word_prompt(client, callback) elif data == "del_blocked_word": await del_blocked_word_prompt(client, callback) elif data.startswith("delword_idx_"): await confirm_del_blocked_word(client, callback) elif data.startswith("specsrc_"): await manage_special_sources(client, callback) elif data.startswith("addspecsrc_"): await add_special_source_prompt(client, callback) elif data.startswith("delspecsrc_"): await delete_special_source_prompt(client, callback) elif data.startswith("confdelspec_"): await confirm_delete_special_source(client, callback) elif data == "stats": await show_stats(client, callback) elif data == "export_data": await export_callback(client, callback) elif data == "import_data": await import_callback(client, callback) else: await callback.answer("غير معروف.")
app.add_handler(CallbackQueryHandler(callback_dispatcher)) app.add_handler(MessageHandler(handle_text_input, filters.text & filters.private))
def register_user_handlers(app: Client): # نلتقط كل رسائل حساب المستخدم ثم نفلتر داخل user_message_handler # هذا يساعدنا نعرف هل SESSION_STRING يلتقط المصادر العامة أو لا app.add_handler(MessageHandler(user_message_handler))
def register_middle_handlers(app: Client): app.add_handler(MessageHandler(middle_channel_handler, filters.chat(config.MIDDLE_CHANNEL)))
async def run_clients(): global bot_client, user_client
os.makedirs("/data/sessions", exist_ok=True)
bot_client = Client( "/data/sessions/bot_session", api_id=config.API_ID, api_hash=config.API_HASH, bot_token=config.BOT_TOKEN )
user_client = Client( "/data/sessions/user_session", api_id=config.API_ID, api_hash=config.API_HASH, session_string=config.SESSION_STRING )
register_bot_handlers(bot_client) register_user_handlers(user_client) register_middle_handlers(bot_client)
await bot_client.start() await user_client.start()
await warm_middle_peer()
logger.info("✅ البوتان شغّالان") asyncio.create_task(poll_public_sources_loop()) logger.info("✅ تم تشغيل نظام Polling للمصادر العامة") await asyncio.Event().wait()
def run_bot(): lock_file = "/tmp/telegram_bot_core_running.lock"
if os.path.exists(lock_file): logger.warning("⚠️ البوت يعمل مسبقاً، تم منع تشغيل نسخة ثانية.") return
with open(lock_file, "w") as f: f.write(str(os.getpid()))
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop)
try: loop.run_until_complete(run_clients()) except KeyboardInterrupt: pass except Exception as e: logger.exception(f"توقف البوت بسبب خطأ: {e}") finally: try: if bot_client: loop.run_until_complete(bot_client.stop()) except Exception: pass
try: if user_client: loop.run_until_complete(user_client.stop()) except Exception: pass
try: if os.path.exists(lock_file): os.remove(lock_file) except Exception: pass
loop.close()1234567891011121314151617181920212223import os
API_ID = int(os.getenv("API_ID", "0"))API_HASH = os.getenv("API_HASH", "")BOT_TOKEN = os.getenv("BOT_TOKEN", "")SESSION_STRING = os.getenv("SESSION_STRING", "")
# قراءة قائمة الأدمن من متغير ADMINS (أرقام مفصولة بفواصل)admins_str = os.getenv("ADMINS", "")ADMINS = [int(x.strip()) for x in admins_str.split(",") if x.strip()]
# إذا لم يُضبط ADMINS نحاول استخدام ADMIN_ID القديم (للتوافق)if not ADMINS: old_admin = os.getenv("ADMIN_ID", "") if old_admin: ADMINS = [int(old_admin)]
MIDDLE_CHANNEL = int(os.getenv("MIDDLE_CHANNEL", "0"))
if not all([API_ID, API_HASH, BOT_TOKEN, SESSION_STRING, MIDDLE_CHANNEL]): raise ValueError("جميع المتغيرات الأساسية مطلوبة")if not ADMINS: raise ValueError("يجب تعيين ADMINS على الأقل معرف أدمن واحد")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412import jsonimport osimport timefrom threading import Lock
DB_FILE = "/data/data.json"BACKUP_DIR = "/data/backups"SCHEMA_VERSION = 2lock = Lock()
DEFAULT_BLOCKED_WORDS = [ "إعلان", "اعلان", "تبادل", "ممول", "تمويل", "للتواصل", "اشتراك", "تابعونا", "اشترك", "قناتنا", "بوت", "عبر البوت", "عرض خاص", "لفترة محدودة", "اضغط هنا", "لمشاهدة المزيد", "حصرياً", "تم النشر بواسطة"]
DEFAULT_DATA = { "schema_version": SCHEMA_VERSION, "channels": {}, "public_sources": [], "source_meta": {}, "blocked_words": DEFAULT_BLOCKED_WORDS, "allowed_users": [], "last_source_messages": {}, "settings": {},}
def _now(): return int(time.time())
def _dedupe_int_list(values): out = [] seen = set() for value in values or []: try: item = int(value) except Exception: item = value key = str(item) if key not in seen: seen.add(key) out.append(item) return out
def _normalize_channel(cid, value): if not isinstance(value, dict): value = {"name": str(value)} value.setdefault("name", value.get("title") or str(cid)) value.setdefault("title", value.get("name") or str(cid)) value.setdefault("username", "") value.setdefault("link", "") value.setdefault("chat_type", "") value.setdefault("tail", "") value.setdefault("special_sources", []) value.setdefault("paused", False) value.setdefault("posts_count", 0) value.setdefault("added_at", _now()) value["special_sources"] = _dedupe_int_list(value.get("special_sources", [])) return value
def _normalize_source_meta(source_id, value=None): if not isinstance(value, dict): value = {} sid = str(source_id) value.setdefault("id", int(source_id) if str(source_id).lstrip('-').isdigit() else source_id) value.setdefault("name", value.get("title") or sid) value.setdefault("title", value.get("name") or sid) value.setdefault("username", "") value.setdefault("link", "") value.setdefault("chat_type", "") value.setdefault("added_at", _now()) value.setdefault("paused", False) return value
def _normalize_data(data): if not isinstance(data, dict): data = {}
for key, value in DEFAULT_DATA.items(): if key not in data: data[key] = value.copy() if isinstance(value, (list, dict)) else value
if not isinstance(data.get("channels"), dict): data["channels"] = {} if not isinstance(data.get("public_sources"), list): data["public_sources"] = [] if not isinstance(data.get("source_meta"), dict): data["source_meta"] = {} if not isinstance(data.get("blocked_words"), list): data["blocked_words"] = DEFAULT_BLOCKED_WORDS.copy() if not isinstance(data.get("allowed_users"), list): data["allowed_users"] = [] if not isinstance(data.get("last_source_messages"), dict): data["last_source_messages"] = {} if not isinstance(data.get("settings"), dict): data["settings"] = {}
data["schema_version"] = SCHEMA_VERSION data["public_sources"] = _dedupe_int_list(data.get("public_sources", []))
channels = {} for cid, ch in data.get("channels", {}).items(): channels[str(cid)] = _normalize_channel(cid, ch) data["channels"] = channels
meta = {} for source in data["public_sources"]: sid = str(source) meta[sid] = _normalize_source_meta(source, data.get("source_meta", {}).get(sid, {})) for sid, value in data.get("source_meta", {}).items(): if sid not in meta: meta[sid] = _normalize_source_meta(sid, value) data["source_meta"] = meta
# normalize last source ids as strings data["last_source_messages"] = {str(k): v for k, v in data.get("last_source_messages", {}).items()} return data
def _read(): os.makedirs("/data", exist_ok=True)
if not os.path.exists(DB_FILE): with open(DB_FILE, "w", encoding="utf-8") as f: json.dump(DEFAULT_DATA, f, ensure_ascii=False, indent=2)
try: with open(DB_FILE, "r", encoding="utf-8") as f: data = json.load(f) except Exception: data = DEFAULT_DATA.copy()
return _normalize_data(data)
def _write(data): os.makedirs("/data", exist_ok=True) data = _normalize_data(data)
tmp_file = DB_FILE + ".tmp" with open(tmp_file, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) os.replace(tmp_file, DB_FILE)
def _write_backup(data): try: os.makedirs(BACKUP_DIR, exist_ok=True) backup_file = os.path.join(BACKUP_DIR, f"backup_{int(time.time())}.json") with open(backup_file, "w", encoding="utf-8") as f: json.dump(_normalize_data(data), f, ensure_ascii=False, indent=2) # keep last 5 backups only files = sorted([os.path.join(BACKUP_DIR, x) for x in os.listdir(BACKUP_DIR) if x.endswith('.json')]) for old in files[:-5]: try: os.remove(old) except Exception: pass except Exception: pass
def get_all_channels(): with lock: data = _read() return [{"id": k, **v} for k, v in data["channels"].items()]
def add_channel(channel_id, name="", title="", username="", link="", chat_type=""): cid = str(channel_id) with lock: data = _read() created = cid not in data["channels"] if created: data["channels"][cid] = _normalize_channel(cid, { "name": title or name or cid, "title": title or name or cid, "username": username or "", "link": link or "", "chat_type": chat_type or "", "tail": "", "special_sources": [], "paused": False, "posts_count": 0, "added_at": _now(), }) else: ch = data["channels"][cid] if title or name: ch["name"] = title or name ch["title"] = title or name if username is not None: ch["username"] = username or ch.get("username", "") if link is not None: ch["link"] = link or ch.get("link", "") if chat_type is not None: ch["chat_type"] = chat_type or ch.get("chat_type", "") _write(data) if created: _write_backup(data) return created
def delete_channel(channel_id): cid = str(channel_id) with lock: data = _read() if cid in data["channels"]: del data["channels"][cid] _write(data) _write_backup(data) return True return False
def update_channel(channel_id, key, value): cid = str(channel_id) with lock: data = _read() if cid in data["channels"]: data["channels"][cid][key] = value _write(data) _write_backup(data) return True return False
def increment_post_count(channel_id): cid = str(channel_id) with lock: data = _read() if cid in data["channels"]: data["channels"][cid].setdefault("posts_count", 0) data["channels"][cid]["posts_count"] += 1 _write(data) return True return False
def get_channel(channel_id): cid = str(channel_id) with lock: data = _read() return data["channels"].get(cid)
def get_public_sources(): with lock: data = _read() return data["public_sources"]
def get_source_meta(source_id): sid = str(source_id) with lock: data = _read() return data.get("source_meta", {}).get(sid, _normalize_source_meta(source_id))
def get_all_public_sources_with_meta(): with lock: data = _read() return [{"id": s, **data.get("source_meta", {}).get(str(s), _normalize_source_meta(s))} for s in data["public_sources"]]
def add_public_source(source_id, name="", title="", username="", link="", chat_type=""): try: source_id = int(source_id) except Exception: pass sid = str(source_id)
with lock: data = _read() created = source_id not in data["public_sources"] if created: data["public_sources"].append(source_id) old = data.setdefault("source_meta", {}).get(sid, {}) meta = _normalize_source_meta(source_id, old) if title or name: meta["name"] = title or name meta["title"] = title or name if username is not None: meta["username"] = username or meta.get("username", "") if link is not None: meta["link"] = link or meta.get("link", "") if chat_type is not None: meta["chat_type"] = chat_type or meta.get("chat_type", "") data["source_meta"][sid] = meta _write(data) if created: _write_backup(data) return created
def update_source_meta(source_id, **kwargs): sid = str(source_id) with lock: data = _read() meta = _normalize_source_meta(source_id, data.setdefault("source_meta", {}).get(sid, {})) for key, value in kwargs.items(): if value is not None: meta[key] = value data["source_meta"][sid] = meta _write(data) return True
def remove_public_source(source_id): try: source_id = int(source_id) except Exception: pass sid = str(source_id)
with lock: data = _read() if source_id in data["public_sources"]: data["public_sources"].remove(source_id) data["last_source_messages"].pop(sid, None) data.get("source_meta", {}).pop(sid, None) _write(data) _write_backup(data) return True return False
def get_blocked_words(): with lock: data = _read() return data["blocked_words"]
def add_blocked_word(word): word = str(word).strip() if not word: return False with lock: data = _read() if word not in data["blocked_words"]: data["blocked_words"].append(word) _write(data) _write_backup(data) return True return False
def remove_blocked_word(word): word = str(word).strip() with lock: data = _read() if word in data["blocked_words"]: data["blocked_words"].remove(word) _write(data) _write_backup(data) return True return False
def get_last_source_message(source_id): with lock: data = _read() value = data.get("last_source_messages", {}).get(str(source_id)) try: return int(value) if value is not None else None except Exception: return None
def set_last_source_message(source_id, message_id): with lock: data = _read() data.setdefault("last_source_messages", {})[str(source_id)] = int(message_id) _write(data) return True
def reset_last_source_message(source_id): with lock: data = _read() if str(source_id) in data.get("last_source_messages", {}): del data["last_source_messages"][str(source_id)] _write(data) _write_backup(data) return True return False
def export_data(): with lock: data = _read() return json.dumps(_normalize_data(data), ensure_ascii=False, indent=2)
def import_data(json_str): with lock: new_data = json.loads(json_str) new_data = _normalize_data(new_data) _write(new_data) _write_backup(new_data) return { "channels": len(new_data.get("channels", {})), "public_sources": len(new_data.get("public_sources", [])), "blocked_words": len(new_data.get("blocked_words", [])), "last_source_messages": len(new_data.get("last_source_messages", {})), }123pyrogram>=2.0.0tgcryptostreamlitDockerfileAdded+13
README.mdAdded+13
app.pyAdded+30
bot_core.pyAdded+1322
config.pyAdded+23
database.pyAdded+412
requirements.txtAdded+3