diff --git "a/bot_core.py" "b/bot_core.py" new file mode 100644 --- /dev/null +++ "b/bot_core.py" @@ -0,0 +1,3186 @@ +import asyncio +import re +import logging +import tempfile +import os +import time +import html +import hashlib +import difflib + +from pyrogram import Client, filters +from pyrogram.handlers import MessageHandler, CallbackQueryHandler +from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton +try: + from pyrogram.types import MessageEntity + from pyrogram.enums import MessageEntityType +except Exception: + MessageEntity = None + MessageEntityType = None +from pyrogram.errors import MessageNotModified +from pyrogram.enums import ParseMode + +import config +import database as db + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) +logging.getLogger("pyrogram").setLevel(logging.WARNING) +logging.getLogger("pyrogram.session").setLevel(logging.WARNING) +logging.getLogger("pyrogram.connection").setLevel(logging.WARNING) +logging.getLogger("pyrogram.dispatcher").setLevel(logging.WARNING) + +bot_client = None +user_client = None +user_states = {} +_middle_peer_warmed = False +_middle_auto_ignore_until = 0.0 +_middle_album_buffers = {} +_middle_album_tasks = {} + + +def is_admin(user_id): + return user_id in config.ADMINS + +def clean_text(text, source_id=None): + """تنظيف نهائي قبل النشر. يرجع None إذا النص يحتوي كلمة محظورة.""" + if not text: + return text + + if isinstance(text, str): + text = full_clean_text(text, source_id=source_id) + + 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 + + +def get_publish_delay_for_channel(channel_id, default=0.5): + try: + return db.get_channel_publish_delay(channel_id, default) if hasattr(db, "get_channel_publish_delay") else default + except Exception: + return default + +def is_channel_bold_enabled(channel_id): + try: + return bool(db.get_channel_bold_publish(channel_id, True)) if hasattr(db, "get_channel_bold_publish") else True + except Exception: + return True + + +def _utf16_len(text): + try: + return len(str(text or "").encode("utf-16-le")) // 2 + except Exception: + return len(str(text or "")) + + +def _entity_type(name): + if MessageEntityType is None: + return None + try: + return getattr(MessageEntityType, name) + except Exception: + return None + + +def build_quote_entities_for_channel(text, channel_id, content_type="text"): + """يبني entities رسمية للاقتباس حتى لا نعتمد على HTML blockquote إذا ما يدعمه Pyrogram.""" + if not text: + return None + if not is_channel_quote_enabled(channel_id, content_type): + return None + if MessageEntity is None or MessageEntityType is None: + return None + + length = _utf16_len(text) + if length <= 0: + return None + + entities = [] + blockquote_type = _entity_type("BLOCKQUOTE") + bold_type = _entity_type("BOLD") + + if blockquote_type is not None: + try: + entities.append(MessageEntity(type=blockquote_type, offset=0, length=length)) + except Exception: + return None + + if is_channel_bold_enabled(channel_id) and bold_type is not None: + try: + entities.append(MessageEntity(type=bold_type, offset=0, length=length)) + except Exception: + pass + + return entities or None + + +def _html_quote_text_for_channel(text, channel_id): + """يبني اقتباس Telegram الرسمي بصيغة HTML بدون إضافة رموز مرئية مثل ▌.""" + escaped = html.escape(str(text or "")) + if is_channel_bold_enabled(channel_id): + escaped = f"{escaped}" + return f"
{escaped}" + + +def format_outgoing_payload_for_channel(text, channel_id, content_type="text"): + """يرجع النص + parse_mode + entities. عند تفعيل الاقتباس نستخدم Telegram Quote الرسمي فقط.""" + if not text: + return text, None, None + + if is_channel_quote_enabled(channel_id, content_type): + # المحاولة الأولى: entities رسمية إذا كان إصدار Pyrogram يدعم BLOCKQUOTE. + entities = build_quote_entities_for_channel(str(text), channel_id, content_type) + if entities: + return str(text), None, entities + # المحاولة الثانية: HTML blockquote الرسمي. لا نضيف أي ▌ أو رموز شكلية. + return _html_quote_text_for_channel(text, channel_id), ParseMode.HTML, None + + formatted, parse_mode = format_outgoing_text_for_channel(text, channel_id) + return formatted, parse_mode, None + + +def format_outgoing_text_for_channel(text, channel_id): + """يرجع النص مع ParseMode المناسب. ترتيب ال��اشتاك/التوقيع يتم قبل هذه الدالة.""" + if not text: + return text, None + + bold_enabled = is_channel_bold_enabled(channel_id) + + escaped = html.escape(str(text)) + if bold_enabled: + escaped = f"{escaped}" + + if bold_enabled: + return escaped, ParseMode.HTML + return str(text), None + +def channel_display_name(ch_or_id): + ch = ch_or_id if isinstance(ch_or_id, dict) else db.get_channel(ch_or_id) + if isinstance(ch, dict): + name = entity_name(ch) + cid = ch.get("id") or ch_or_id + return f"{name} | ID: `{cid}`" + return f"ID: `{ch_or_id}`" + + +def source_display_name(src_id): + meta = db.get_source_meta(src_id) if hasattr(db, "get_source_meta") else {"id": src_id} + return f"{entity_name(meta)} | ID: `{src_id}`" + + +def pair_buttons(buttons): + """يرتب الأزرار المفردة على عمودين قدر الإمكان.""" + rows = [] + pending = [] + for item in buttons: + if isinstance(item, list): + if pending: + rows.append(pending) + pending = [] + rows.append(item) + else: + pending.append(item) + if len(pending) == 2: + rows.append(pending) + pending = [] + if pending: + rows.append(pending) + return rows + + + + +def grid_buttons(buttons, max_cols=3): + """يرتب الأزرار المفردة بعمودين فقط حتى تظهر أسماء الأزرار بوضوح.""" + rows = [] + pending = [] + max_cols = 2 + for item in buttons: + if isinstance(item, list): + if pending: + rows.append(pending) + pending = [] + rows.append(item) + else: + pending.append(item) + if len(pending) >= max_cols: + rows.append(pending) + pending = [] + if pending: + rows.append(pending) + return rows + + +def nav_row(back=None): + row = [] + if back: + row.append(InlineKeyboardButton("🔙 رجوع", callback_data=back)) + row.append(InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")) + return row + + +def append_channel_hashtags(text, channel_id): + try: + tags = db.get_channel_hashtags(channel_id) if hasattr(db, "get_channel_hashtags") else [] + except Exception: + tags = [] + if not tags: + return text + tag_line = " ".join(tags) + return f"{text}\n\n{tag_line}" if text else tag_line + + +def compose_channel_post_text(news_text, channel_id, tail=""): + """يرتب المنشور دائماً: الخبر ثم الهاشتاك ثم التوقيع ثم الفاصل.""" + parts = [] + news_text = str(news_text or "").strip() + if news_text: + parts.append(news_text) + try: + tags = db.get_channel_hashtags(channel_id) if hasattr(db, "get_channel_hashtags") else [] + except Exception: + tags = [] + if tags: + parts.append(" ".join(tags).strip()) + tail = str(tail or "").strip() + if tail: + parts.append(tail) + if "---" not in tail and "—" not in tail: + parts.append("------------") + return "\n\n".join([p for p in parts if p]) + +def is_channel_quote_enabled(channel_id, content_type="text"): + try: + if hasattr(db, "get_channel_quote_type"): + return bool(db.get_channel_quote_type(channel_id, content_type, False)) + return bool(db.get_channel_quote_publish(channel_id, False)) if hasattr(db, "get_channel_quote_publish") else False + except Exception: + return False + + +def get_channel_quote_types_safe(channel_id): + try: + if hasattr(db, "get_channel_quote_types"): + return db.get_channel_quote_types(channel_id) + except Exception: + pass + enabled = is_channel_quote_enabled(channel_id, "text") + return {"text": enabled, "photo": enabled, "video": enabled, "album": enabled} + + + +def is_ignore_short_posts_enabled(): + try: + return bool(db.get_ignore_short_posts()) if hasattr(db, "get_ignore_short_posts") else False + except Exception: + return False + + +def is_short_post_text(text, min_words=5, min_chars=20): + cleaned = compact_text(text or "") + if not cleaned: + return False + word_count = len([w for w in cleaned.split() if w.strip()]) + char_count = len(cleaned) + return word_count < int(min_words) or char_count < int(min_chars) + + +def should_ignore_short_post(text): + return is_ignore_short_posts_enabled() and is_short_post_text(text) + + +def record_channel_success(channel_id): + try: + if hasattr(db, "record_channel_publish_success"): + db.record_channel_publish_success(channel_id) + except Exception: + pass + + +async def record_channel_failure_and_maybe_alert(channel_id, error): + count = None + try: + if hasattr(db, "record_channel_publish_failure"): + count = db.record_channel_publish_failure(channel_id, error, limit=5) + except Exception: + pass + if count and int(count) >= 5: + await notify_admins(f"تم إيقاف قناة النشر تلقائياً بعد {count} أخطاء متتالية:\n{channel_display_name(channel_id)}\n\nالخطأ: {error}") + +async def notify_admins(text): + try: + if hasattr(db, "add_last_error"): + db.add_last_error("admin_alert", text) + except Exception: + pass + 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 hydrate_publish_channel(channel_id): + """تهيئة قناة نشر قبل الإرسال، خصوصاً بعد الاستيراد.""" + ch = db.get_channel(channel_id) if hasattr(db, "get_channel") else None + candidates = [] + if ch: + username = ch.get("username") or "" + link = ch.get("link") or "" + if username: + candidates.append("@" + username.lstrip("@")) + if link: + candidates.append(link) + candidates.append(int(channel_id)) + last_error = None + for item in candidates: + try: + return await bot_client.get_chat(item) + except Exception as e: + last_error = e + raise last_error or ValueError(f"تعذر تهيئة قناة النشر {channel_id}") + + +async def hydrate_source_channel(source_id): + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {} + candidates = [] + username = meta.get("username") or "" if isinstance(meta, dict) else "" + link = meta.get("link") or "" if isinstance(meta, dict) else "" + if username: + candidates.append("@" + username.lstrip("@")) + if link: + candidates.append(link) + candidates.append(int(source_id)) + last_error = None + for item in candidates: + try: + return await user_client.get_chat(item) + except Exception as e: + last_error = e + raise last_error or ValueError(f"تعذر تهيئة المصدر {source_id}") + + +async def safe_send_channel_message(target, text, parse_mode=None, entities=None): + """إرسال نص مع محاولة تهيئة peer وإعادة محاولة مرة واحدة.""" + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل الإرسال: {e}") + + async def _send_once(): + if entities: + try: + return await bot_client.send_message(target, text, entities=entities) + except TypeError: + # fallback رسمي للاقتباس إذا كان إصدار Pyrogram لا يدعم entities في send_message + return await bot_client.send_message(target, _html_quote_text_for_channel(text, target), parse_mode=ParseMode.HTML) + return await bot_client.send_message(target, text, parse_mode=parse_mode) + + try: + return await _send_once() + except Exception as first_error: + if "Peer id invalid" in str(first_error) or "PEER_ID_INVALID" in str(first_error): + await hydrate_publish_channel(target) + return await _send_once() + raise + +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, parse_mode=None, content_type=None, caption_entities=None): + """ينسخ رسائل الوسيطة لقناة النشر. للألبومات يستخدم forward_messages كحل ثابت مع Pyrofork.""" + if not isinstance(middle_messages, (list, tuple)): + middle_messages = [middle_messages] + + middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) + if not middle_messages: + return False + + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل النسخ: {e}") + + is_album = len(middle_messages) > 1 or bool(getattr(middle_messages[0], "media_group_id", None)) + + if is_album and len(middle_messages) > 1: + ids = [int(m.id) for m in middle_messages] + # pyrofork الحالي عندك يرجع خطأ topics مع copy_media_group، لذلك نعتمد forward_messages للألبوم. + try: + mark_middle_auto_forward_window() + sent = await bot_client.forward_messages( + chat_id=int(target), + from_chat_id=config.MIDDLE_CHANNEL, + message_ids=ids + ) + mark_middle_auto_forward_window() + sent_list = sent if isinstance(sent, list) else [sent] + sent_ids = [m.id for m in sent_list if getattr(m, "id", None)] + if hasattr(db, "record_published_messages"): + db.record_published_messages(target, sent_ids, content_type or "album") + logger.info(f"✅ نُشر ألبوم إلى {target} عبر forward_messages | count={len(sent_ids)}") + return True + except Exception as forward_error: + logger.error(f"❌ فشل نشر الألبوم عبر forward_messages إلى {target}: {forward_error}") + try: + if hasattr(db, "add_last_error"): + db.add_last_error("forward_album", f"{target}: {forward_error}") + except Exception: + pass + return False + + sent_ids = [] + for idx, m in enumerate(middle_messages): + kwargs = dict( + chat_id=int(target), + from_chat_id=config.MIDDLE_CHANNEL, + message_id=m.id, + caption=caption if idx == 0 and caption else None, + parse_mode=None if (idx == 0 and caption and caption_entities) else (parse_mode if idx == 0 and caption else None) + ) + if idx == 0 and caption and caption_entities: + kwargs["caption_entities"] = caption_entities + try: + sent = await bot_client.copy_message(**kwargs) + except TypeError: + kwargs.pop("caption_entities", None) + if idx == 0 and caption and caption_entities: + kwargs["caption"] = _html_quote_text_for_channel(caption, target) + kwargs["parse_mode"] = ParseMode.HTML + else: + kwargs["parse_mode"] = parse_mode if idx == 0 and caption else None + sent = await bot_client.copy_message(**kwargs) + if getattr(sent, "id", None): + sent_ids.append(sent.id) + await asyncio.sleep(0.25) + + try: + if hasattr(db, "record_published_messages"): + db.record_published_messages(target, sent_ids, content_type or "photo") + except Exception: + pass + 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 + + +def split_terms_lines(text): + """يقسم النص إلى عناصر جماعية: كل سطر عنصر، ويدعم الفواصل إذا ما بيها روابط.""" + items = [] + for line in str(text or "").splitlines(): + line = line.strip() + if not line: + continue + if "," in line and "http" not 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() + out = [] + for item in items: + key = item.lower() + if key not in seen: + seen.add(key) + out.append(item) + return out + + +async def resolve_chat_info_timeout(raw, prefer_user=True, timeout=8): + """يجلب معلومات القناة/المصدر بمهلة حتى لا يعلق البوت عند الإضافة.""" + return await asyncio.wait_for(resolve_chat_info(raw, prefer_user=prefer_user), timeout=timeout) + + +def apply_source_remove_terms(text, source_id): + """التنظيف الذكي: يحذف عناصر هذا المصدر فقط ولا يمنع المنشور.""" + if not text: + return text + try: + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + except Exception: + terms = [] + cleaned = str(text) + for term in terms: + cleaned = remove_term_variants(cleaned, term) + return compact_text(cleaned) + + +# ===== Phase 3 Part 1: advanced filters and cleaning ===== +EMOJI_PATTERN = re.compile( + "[" + "\U0001F1E6-\U0001F1FF" + "\U0001F300-\U0001F5FF" + "\U0001F600-\U0001F64F" + "\U0001F680-\U0001F6FF" + "\U0001F700-\U0001F77F" + "\U0001F780-\U0001F7FF" + "\U0001F800-\U0001F8FF" + "\U0001F900-\U0001F9FF" + "\U0001FA00-\U0001FAFF" + "\u2600-\u27BF" + "]+", + flags=re.UNICODE +) + +HIDDEN_CHARS_PATTERN = re.compile(r"[\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b\u200c\u200d\ufeff]") + + +def compact_text(text): + text = str(text or "") + text = HIDDEN_CHARS_PATTERN.sub("", text) + text = "\n".join(line.strip() for line in text.splitlines() if line.strip()) + text = re.sub(r"[ \t]{2,}", " ", text) + return text.strip() + + +def remove_term_variants(text, term): + """يحذف الكلمة كما هي، وكهاشتاك، ومع تحويل الفراغات إلى _ أو -.""" + if not text or not term: + return text + term = str(term).strip() + if not term: + return text + + base = term.lstrip("#@").strip() + variants = {term, base} + if base: + variants.add("#" + base) + variants.add("@" + base) + variants.add("#" + base.replace(" ", "_")) + variants.add("#" + base.replace(" ", "-")) + variants.add(base.replace(" ", "_")) + variants.add(base.replace(" ", "-")) + + cleaned = str(text) + for variant in sorted(variants, key=len, reverse=True): + if not variant: + continue + pattern = re.escape(variant) + # حدود مرنة حتى لا تلتصق الكلمات بباقي النص + cleaned = re.sub(r"(? best: + best = ratio + if ratio >= threshold: + return True, ratio + return False, best + + +def remember_published_text(text): + fp, normalized = make_similarity_fp(text) + if fp and hasattr(db, "add_recent_fingerprint"): + try: + db.add_recent_fingerprint(fp, normalized) + except Exception: + pass + + +def content_types_status_line(source_id): + labels = {"text": "نصوص", "photo": "صور", "video": "فيديو", "album": "ألبومات", "voice": "بصمات", "audio": "صوتيات", "document": "ملفات"} + try: + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {} + except Exception: + types = {} + if not types: + types = {"text": True, "photo": True, "video": True, "album": True} + return " | ".join(("✅ " if types.get(k, True) else "❌ ") + v for k, v in labels.items()) + + + +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="global_clean") + ], + [ + InlineKeyboardButton("📊 الإحصائيات", callback_data="stats"), + InlineKeyboardButton("💾 الاستيراد / التصدير", callback_data="backup_menu") + ], + [ + InlineKeyboardButton("🟢 حالة النظام", callback_data="system_status"), + InlineKeyboardButton("🧪 فحص شامل", callback_data="full_check") + ], + [ + InlineKeyboardButton("🛠 إدارة التشغيل", callback_data="ops_menu") + ] +]) + + +async def backup_menu(client, callback): + text = "**💾 الاستيراد / التصدير**\n\nاختر العملية المطلوبة:" + buttons = [ + [ + InlineKeyboardButton("📥 تصدير البيانات", callback_data="export_data"), + InlineKeyboardButton("📤 استيراد البيانات", callback_data="import_data") + ], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")] + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +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('global_remove_terms', 0)}\n" + f"• إعدادات المصادر: {result.get('source_meta', 0)}\n" + f"• آخر رسائل المصادر: {result.get('last_source_messages', 0)}" + ) + else: + report = "✅ تم استيراد الإعدادات بنجاح." + await message.reply(report + "\n\n🔄 جارٍ تهيئة القنوات والمصادر بعد الاستيراد...", reply_markup=main_keyboard) + try: + await warm_all_peers_after_import() + await message.reply("✅ تمت تهيئة القنوات والمصادر بعد الاستيراد. المفروض النشر يشتغل بدون إعادة إضافة يدوية.") + except Exception as e: + logger.error(f"فشل تهيئة الاستيراد: {e}") + await message.reply(f"⚠️ تم الاستيراد، لكن فشلت التهيئة التلقائية: {e}") + except Exception as e: + await message.reply(f"❌ فشل الاستيراد: {e}") + finally: + user_states.pop(uid, None) + + +CONTENT_TYPE_LABELS = { + "text": "النصوص", + "photo": "الصور", + "video": "الفيديوهات", + "album": "الألبومات", +} + + +async def purge_published_prompt(client, callback): + try: + _, ch_id, kind = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + label = CONTENT_TYPE_LABELS.get(kind, kind) + ids = db.get_published_message_ids(ch_id, kind) if hasattr(db, "get_published_message_ids") else [] + ch = db.get_channel(ch_id) + text = ( + f"⚠️ **تأكيد حذف {label} من قناة النشر**\n\n" + f"{channel_display_name(ch or ch_id)}\n\n" + f"عدد الرسائل المسجلة للحذف: {len(ids)}\n\n" + "سيحذف البوت فقط الرسائل التي يعرف IDs مالتهن والمنشورة بعد إضافة هذا النظام." + ) + buttons = [ + [InlineKeyboardButton(f"✅ نعم، احذف {label}", callback_data=f"confirmpurge|{ch_id}|{kind}")], + [InlineKeyboardButton("❌ إلغاء", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def confirm_purge_published(client, callback): + try: + _, ch_id, kind = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + ids = db.get_published_message_ids(ch_id, kind) if hasattr(db, "get_published_message_ids") else [] + if not ids: + await callback.answer("لا توجد رسائل محفوظة من هذا النوع.", show_alert=True) + await channel_settings(client, callback) + return + + deleted = 0 + failed = 0 + deleted_ids = [] + for i in range(0, len(ids), 100): + chunk = ids[i:i+100] + try: + await bot_client.delete_messages(int(ch_id), chunk) + deleted += len(chunk) + deleted_ids.extend(chunk) + except Exception: + # إذا فشل الحذف الجماعي، نحاول واحدة واحدة + for mid in chunk: + try: + await bot_client.delete_messages(int(ch_id), int(mid)) + deleted += 1 + deleted_ids.append(mid) + except Exception as e: + failed += 1 + try: + if hasattr(db, "add_last_error"): + db.add_last_error("purge_message", f"{ch_id}/{kind}/{mid}: {e}") + except Exception: + pass + await asyncio.sleep(0.3) + + if hasattr(db, "clear_published_message_ids"): + db.clear_published_message_ids(ch_id, kind, None if failed == 0 else deleted_ids) + + label = CONTENT_TYPE_LABELS.get(kind, kind) + await notify_admins(f"تم حذف {label} من {channel_display_name(ch_id)}\n✅ المحذوف: {deleted}\n❌ فشل: {failed}") + await safe_edit(callback, f"🧹 **نتيجة حذف {label}:**\n\n✅ تم حذف: {deleted}\n❌ فشل: {failed}", InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع للقناة", callback_data=f"ch_{ch_id}"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")] + ])) + + +def channel_buttons(ch_id, ch): + paused_text = "⏸️ موقوفة" if ch.get('paused') else "✅ شغالة" + bold_text = "✅ الخط السميك" if ch.get("bold_publish", True) else "❌ الخط السميك" + quote_types = get_channel_quote_types_safe(ch_id) + quote_count = sum(1 for v in quote_types.values() if v) + quote_text = f"💬 الاقتباس ({quote_count}/4)" + buttons = [ + InlineKeyboardButton(f"⏯️ {paused_text}", callback_data=f"toggle_{ch_id}"), + InlineKeyboardButton(f"🅱️ {bold_text}", callback_data=f"togglebold_{ch_id}"), + InlineKeyboardButton(quote_text, callback_data=f"quotemenu_{ch_id}"), + InlineKeyboardButton("🏷 هاشتاكات", callback_data=f"hashtags_{ch_id}"), + InlineKeyboardButton("🧪 اختبار نشر", callback_data=f"testpub_{ch_id}"), + InlineKeyboardButton("📝 التوقيع", callback_data=f"tailmenu_{ch_id}"), + InlineKeyboardButton("⏱ سرعة النشر", callback_data=f"speedmenu_{ch_id}"), + InlineKeyboardButton("🔍 المصادر المخصصة", callback_data=f"specsrc_{ch_id}"), + InlineKeyboardButton("🗑 حذف القناة", callback_data=f"delchannel_{ch_id}"), + InlineKeyboardButton("🧹 حذف النصوص", callback_data=f"purgepub|{ch_id}|text"), + InlineKeyboardButton("🧹 حذف الصور", callback_data=f"purgepub|{ch_id}|photo"), + InlineKeyboardButton("🧹 حذف الفيديوهات", callback_data=f"purgepub|{ch_id}|video"), + InlineKeyboardButton("🧹 حذف الألبومات", callback_data=f"purgepub|{ch_id}|album"), + ] + rows = grid_buttons(buttons, 3) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data="menu_channels"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")]) + return InlineKeyboardMarkup(rows) + + +async def toggle_channel_bold(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + current = bool(ch.get("bold_publish", True)) + if hasattr(db, "set_channel_bold_publish"): + db.set_channel_bold_publish(ch_id, not current) + else: + db.update_channel(ch_id, "bold_publish", not current) + await callback.answer("تم تحديث خيار الخط السميك.") + await channel_settings(client, callback) + +async def menu_channels(client, callback): + channels = db.get_all_channels() + + if not channels: + text = "لا توجد قنوات." + rows = [ + [InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], + nav_row("main_menu") + ] + else: + text = f"**قنوات النشر ({len(channels)}):**\n" + btns = [] + 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" + btns.append(InlineKeyboardButton(f"⚙️ {name}", callback_data=f"ch_{ch['id']}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) + rows.append(nav_row("main_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def show_channels_menu_from_message(message): + channels = db.get_all_channels() + if not channels: + text = "لا توجد قنوات." + rows = [ + [InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")], + nav_row("main_menu") + ] + else: + text = f"**قنوات النشر ({len(channels)}):**\n" + btns = [] + 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" + btns.append(InlineKeyboardButton(f"⚙️ {name}", callback_data=f"ch_{ch['id']}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة قناة/قنوات", callback_data="add_channel")]) + rows.append(nav_row("main_menu")) + await message.reply(text, reply_markup=InlineKeyboardMarkup(rows)) + +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 'لا يوجد'}\n" + f"🅱️ **النشر بخط سميك:** {'✅ مفعل' if ch.get('bold_publish', True) else '❌ متوقف'}\n" + f"💬 **النشر كاقتباس:** {'✅ مفعل' if ch.get('quote_publish', False) else '❌ متوقف'}\n" + f"🏷 **الهاشتاكات:** {' '.join(ch.get('hashtags', []) or []) or 'لا توجد'}\n" + f"⚠️ **أخطاء متتالية:** {ch.get('fail_count', 0)}" + ) + 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 "لا توجد." + btns = [] + for meta in meta_list: + sid = meta.get("id") + paused = " ⏸️" if is_source_paused(sid) else "" + btns.append(InlineKeyboardButton(f"⚙️ {entity_name(meta)}{paused}", callback_data=f"srcset|{sid}|menu_public_src")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة مصدر/مصادر", callback_data="add_public_src"), InlineKeyboardButton("🗑 حذف مصدر عام", callback_data="del_public_src")]) + rows.append(nav_row("main_menu")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +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, "أرسل كلمة أو عدة كلمات محظورة.\nكل كلمة/عبارة بسطر مستقل:") + +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 "لا توجد." + btns = [] + for s in sources: + paused = " ⏸️" if is_source_paused(s) else "" + btns.append(InlineKeyboardButton(f"⚙️ {entity_name(s, is_source=True)}{paused}", callback_data=f"srcset|{s}|specsrc_{ch_id}")) + rows = grid_buttons(btns, 2 if len(btns) <= 8 else 3) + rows.append([InlineKeyboardButton("➕ إضافة", callback_data=f"addspecsrc_{ch_id}"), InlineKeyboardButton("🗑 حذف", callback_data=f"delspecsrc_{ch_id}")]) + rows.append(nav_row(f"ch_{ch_id}")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def source_cleanup_menu(client, callback): + parts = callback.data.split("|", 2) + source_id = parts[1] + back = parts[2] if len(parts) > 2 else "menu_public_src" + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + name = entity_name(meta) + text = f"🧹 **التنظيف الذكي للمصدر:**\n{name}\nID: `{source_id}`\n\n" + text += "العناصر الحالية:\n" + ("\n".join(f"• `{t}`" for t in terms) if terms else "لا توجد عناصر.") + buttons = [ + [InlineKeyboardButton("➕ إضافة عناصر جماعياً", callback_data=f"addclean|{source_id}|{back}")], + [InlineKeyboardButton("🗑 حذف عناصر جماعياً", callback_data=f"delclean|{source_id}|{back}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def add_source_cleanup_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_source_cleanup_add", "source_id": source_id, "back": back} + await safe_edit(callback, "أرسل عناصر التنظيف الذكي لهذا المصدر.\nكل كلمة/هاشتاك/يوزر بسطر مستقل:") + + +async def del_source_cleanup_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_source_cleanup_del", "source_id": source_id, "back": back} + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + current = "\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر حالياً." + await safe_edit(callback, "أرسل العناصر التي تريد حذفها من التنظيف الذكي.\nكل عنصر بسطر مستقل.\n\nالحالي:\n" + current) + + +async def source_settings_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + name = entity_name(meta) + paused = is_source_paused(source_id) + remove_emoji = db.get_source_remove_emoji(source_id) if hasattr(db, "get_source_remove_emoji") else False + terms = db.get_source_remove_terms(source_id) if hasattr(db, "get_source_remove_terms") else [] + text = ( + f"⚙️ **إعدادات المصدر:**\n{name}\n\n" + f"🆔 ID: `{source_id}`\n" + f"📊 الحالة: {'⏸️ موقوف' if paused else '✅ شغال'}\n" + f"😀 حذف الإيموجي: {'✅ مفعل' if remove_emoji else '❌ متوقف'}\n" + f"📦 أنواع المحتوى:\n{content_types_status_line(source_id)}\n" + f"🧹 عناصر التنظيف الذكي: {len(terms)}" + ) + btns = [ + InlineKeyboardButton("⏯️ تشغيل/إيقاف", callback_data=f"togglesource|{source_id}|{back}"), + InlineKeyboardButton("😀 الإيموجي", callback_data=f"toggleemoji|{source_id}|{back}"), + InlineKeyboardButton("📦 المحتوى", callback_data=f"contentmenu|{source_id}|{back}"), + InlineKeyboardButton("🧹 التنظيف", callback_data=f"clean_src|{source_id}|{back}"), + InlineKeyboardButton("📊 الإحصائيات", callback_data=f"srcstats|{source_id}|{back}"), + InlineKeyboardButton("📋 السجل", callback_data=f"srclog|{source_id}|{back}"), + InlineKeyboardButton("🧪 اختبار", callback_data=f"testsrc|{source_id}|{back}"), + InlineKeyboardButton("📑 نسخ الإعدادات", callback_data=f"copysrc|{source_id}|{back}"), + InlineKeyboardButton("📋 لصق الإعدادات", callback_data=f"pastesrc|{source_id}|{back}"), + ] + rows = grid_buttons(btns, 2) + rows.append(nav_row(back)) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def toggle_source_enabled(client, callback): + _, source_id, back = callback.data.split("|", 2) + new_state = not is_source_paused(source_id) + if hasattr(db, "set_source_paused"): + db.set_source_paused(source_id, new_state) + await callback.answer("تم إيقاف المصدر." if new_state else "تم تشغيل المصدر.") + callback.data = f"srcset|{source_id}|{back}" + await source_settings_menu(client, callback) + + +async def toggle_source_emoji(client, callback): + _, source_id, back = callback.data.split("|", 2) + current = db.get_source_remove_emoji(source_id) if hasattr(db, "get_source_remove_emoji") else False + if hasattr(db, "set_source_remove_emoji"): + db.set_source_remove_emoji(source_id, not current) + await callback.answer("تم التحديث.") + callback.data = f"srcset|{source_id}|{back}" + await source_settings_menu(client, callback) + + +async def source_content_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False} + labels = {"text": "نصوص", "photo": "صور", "video": "فيديو", "album": "ألبومات", "voice": "بصمات", "audio": "صوتيات", "document": "ملفات"} + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + text = f"📦 **فلتر أنواع المحتوى:**\n{entity_name(meta)}\n\nاختر نوع أو أكثر. الافتراضي هو الكل." + btns = [] + for key, label in labels.items(): + mark = "✅" if types.get(key, True) else "❌" + btns.append(InlineKeyboardButton(f"{mark} {label}", callback_data=f"togglectype|{source_id}|{key}|{back}")) + rows = grid_buttons(btns, 2) + rows.append(nav_row(f"srcset|{source_id}|{back}")) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def toggle_content_type(client, callback): + _, source_id, ctype, back = callback.data.split("|", 3) + types = db.get_source_content_types(source_id) if hasattr(db, "get_source_content_types") else {"text": True, "photo": True, "video": True, "album": True, "voice": False, "audio": False, "document": False} + new_value = not bool(types.get(ctype, True)) + ok = True + if hasattr(db, "set_source_content_type"): + ok = db.set_source_content_type(source_id, ctype, new_value) + if not ok: + await callback.answer("لا يمكن إيقاف كل الأنواع. لازم يبقى نوع واحد على الأقل.", show_alert=True) + else: + await callback.answer("تم التحديث.") + callback.data = f"contentmenu|{source_id}|{back}" + await source_content_menu(client, callback) + + +async def global_cleanup_menu(client, callback): + terms = db.get_global_remove_terms() if hasattr(db, "get_global_remove_terms") else [] + text = "🧹 **قائمة الحذف العامة:**\n\n" + text += "تنطبق على كل المصادر قبل النشر.\n\n" + text += "العناصر الحالية:\n" + ("\n".join(f"• `{t}`" for t in terms) if terms else "لا توجد عناصر.") + rows = [ + [InlineKeyboardButton("➕ إضافة جماعية", callback_data="addglobalclean"), InlineKeyboardButton("🗑 حذف جماعي", callback_data="delglobalclean")], + nav_row("main_menu") + ] + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + +async def add_global_cleanup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_global_cleanup_add"} + await safe_edit(callback, "أرسل كلمات/هاشتاكات/أسماء للحذف العام.\nكل عنصر بسطر مستقل:") + + +async def del_global_cleanup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_global_cleanup_del"} + terms = db.get_global_remove_terms() if hasattr(db, "get_global_remove_terms") else [] + current = "\n".join(f"• {t}" for t in terms) if terms else "لا توجد عناصر حالياً." + await safe_edit(callback, "أرسل العناصر التي تريد حذفها من قائمة الحذف العامة.\nكل عنصر بسطر مستقل.\n\nالحالي:\n" + current) + + + +async def channel_speed_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("publish_delay", None) + text = ( + f"⏱ **سرعة النشر للقناة:**\n{entity_name(ch)}\n\n" + f"الحالية: {'افتراضي' if current in (None, '') else str(current) + ' ثانية'}\n\n" + "اختر قيمة سريعة أو اضغط تخصيص. 0 يعني رجوع للوضع الافتراضي." + ) + buttons = [ + [InlineKeyboardButton("افتراضي", callback_data=f"setspeed|{ch_id}|default")], + [InlineKeyboardButton("1 ثانية", callback_data=f"setspeed|{ch_id}|1"), InlineKeyboardButton("3 ثواني", callback_data=f"setspeed|{ch_id}|3")], + [InlineKeyboardButton("5 ثواني", callback_data=f"setspeed|{ch_id}|5"), InlineKeyboardButton("10 ثواني", callback_data=f"setspeed|{ch_id}|10")], + [InlineKeyboardButton("✏️ تخصيص رقم", callback_data=f"customspeed_{ch_id}")], + [InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ] + await safe_edit(callback, text, InlineKeyboardMarkup(buttons)) + + +async def set_channel_speed(client, callback): + _, ch_id, value = callback.data.split("|", 2) + if value == "default": + db.set_channel_publish_delay(ch_id, None) if hasattr(db, "set_channel_publish_delay") else None + await callback.answer("تم ضبطها على الافتراضي.") + else: + db.set_channel_publish_delay(ch_id, float(value)) if hasattr(db, "set_channel_publish_delay") else None + await callback.answer(f"تم ضبطها على {value} ثانية.") + callback.data = f"speedmenu_{ch_id}" + await channel_speed_menu(client, callback) + + +async def custom_channel_speed_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_channel_speed", "ch_id": ch_id} + await safe_edit(callback, "أرسل عدد الثواني لهذه القناة.\nمثال: 1 أو 2.5 أو 10\nأرسل 0 للرجوع للوضع الافتراضي:") + + +def _format_ts(ts): + if not ts: + return "لا يوجد" + try: + return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(ts))) + except Exception: + return str(ts) + + +async def source_stats_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + stats = db.get_source_stats(source_id) if hasattr(db, "get_source_stats") else {} + text = ( + f"📊 **إحصائيات المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + f"• المستلمة: {stats.get('received', 0)}\n" + f"• المنشورة: {stats.get('published', 0)}\n" + f"• المرفوضة: {stats.get('rejected', 0)}\n" + f"• المتجاهلة: {stats.get('ignored', 0)}\n" + f"• المكررة: {stats.get('duplicates', 0)}\n" + f"• الأخطاء: {stats.get('errors', 0)}\n" + f"• آخر رسالة: {stats.get('last_message_id') or 'لا يوجد'}\n" + f"• آخر حدث: {stats.get('last_event') or 'لا يوجد'}\n" + f"• السبب: {stats.get('last_reason') or 'لا يوجد'}\n" + f"• الوقت: {_format_ts(stats.get('last_ts'))}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + +async def source_log_menu(client, callback): + _, source_id, back = callback.data.split("|", 2) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": str(source_id)} + logs = db.get_source_logs(source_id, 20) if hasattr(db, "get_source_logs") else [] + text = f"📋 **سجل المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + if not logs: + text += "لا توجد عمليات مسجلة." + else: + rows = [] + for item in reversed(logs[-20:]): + rows.append(f"• {_format_ts(item.get('ts'))} | {item.get('event')} | msg={item.get('message_id')} | {item.get('reason') or ''}") + text += "\n".join(rows[:20]) + await safe_edit(callback, text[:3900], InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + +async def test_source(client, callback): + _, source_id, back = callback.data.split("|", 2) + source_id_int = int(source_id) + meta = db.get_source_meta(source_id) if hasattr(db, "get_source_meta") else {"name": source_id} + kind = source_kind_label(source_id_int) + targets = sorted(get_targets_for_source(source_id_int)) + last_seen = db.get_last_source_message(source_id_int) if hasattr(db, "get_last_source_message") else None + try: + last_msg = None + async for msg in user_client.get_chat_history(source_id_int, limit=1): + last_msg = msg + break + access = "✅ متاح" + last_id = getattr(last_msg, "id", None) if last_msg else "لا يوجد" + preview = (getattr(last_msg, "text", None) or getattr(last_msg, "caption", None) or "")[:120] if last_msg else "" + except Exception as e: + access = f"❌ فشل: {e}" + last_id = "غير معروف" + preview = "" + text = ( + f"🧪 **اختبار المصدر:**\n{entity_name(meta)}\nID: `{source_id}`\n\n" + f"• الوصول: {access}\n" + f"• النوع: {kind}\n" + f"• آخر ID محفوظ: {last_seen or 'لا يوجد'}\n" + f"• آخر رسالة بالقناة: {last_id}\n" + f"• القنوات المستهدفة: {targets if targets else 'لا توجد'}\n" + f"• معاينة: {preview or 'لا يوجد'}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + +async def copy_source_settings_prompt(client, callback): + _, source_id, back = callback.data.split("|", 2) + user_states[callback.from_user.id] = {"state": "source_settings_copied", "source_id": source_id, "back": back} + await callback.answer("تم نسخ إعدادات المصدر. ادخل لمصدر آخر واضغط لصق الإعدادات.", show_alert=True) + callback.data = f"srcset|{source_id}|{back}" + await source_settings_menu(client, callback) + + +async def paste_source_settings(client, callback): + _, target_source_id, back = callback.data.split("|", 2) + saved = user_states.get(callback.from_user.id, {}) + from_source_id = saved.get("source_id") if saved.get("state") == "source_settings_copied" else None + if not from_source_id: + await callback.answer("ماكو إعدادات منسوخة. اضغط أولاً نسخ الإعدادات من مصدر آخر.", show_alert=True) + return + if str(from_source_id) == str(target_source_id): + await callback.answer("هذا نفس المصدر المنسوخ.", show_alert=True) + return + copied = db.copy_source_settings(from_source_id, [target_source_id]) if hasattr(db, "copy_source_settings") else 0 + await callback.answer("تم لصق الإعدادات." if copied else "فشل لصق الإعدادات.", show_alert=True) + callback.data = f"srcset|{target_source_id}|{back}" + await source_settings_menu(client, callback) + +async def system_status_menu(client, callback): + channels = db.get_all_channels() + public_count = len(db.get_public_sources()) + special_sources = set() + for ch in channels: + for src in ch.get("special_sources") or []: + try: + special_sources.add(int(src)) + except Exception: + pass + last_error = db.get_system_value("last_error", "لا يوجد") if hasattr(db, "get_system_value") else "لا يوجد" + text = ( + "🟢 **حالة النظام**\n\n" + f"• البوت: {'✅ متصل' if bot_client else '❌ غير معروف'}\n" + f"• الجلسة: {'✅ متصلة' if user_client else '❌ غير معروف'}\n" + f"• الوسيطة: `{config.MIDDLE_CHANNEL}`\n" + f"• قنوات النشر: {len(channels)}\n" + f"• المصادر العامة: {public_count}\n" + f"• المصادر الخاصة: {len(special_sources)}\n" + f"• مصادر الفحص الكلية: {len(get_polling_sources())}\n" + f"• آخر خطأ: {last_error}" + ) + await safe_edit(callback, text, InlineKeyboardMarkup([ + [InlineKeyboardButton("🧪 فحص شامل", callback_data="full_check")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + +async def full_check_menu(client, callback): + lines = ["🧪 **الفحص الشامل**", ""] + try: + await user_client.get_me() + lines.append("✅ الجلسة تعمل") + except Exception as e: + lines.append(f"❌ الجلسة: {e}") + try: + await bot_client.get_me() + lines.append("✅ البوت يعمل") + except Exception as e: + lines.append(f"❌ البوت: {e}") + try: + await warm_middle_peer() + lines.append("✅ الوسيطة تم فحصها") + except Exception as e: + lines.append(f"❌ الوسيطة: {e}") + channels = db.get_all_channels() + ok_ch = 0 + fail_ch = [] + for ch in channels[:80]: + try: + await hydrate_publish_channel(int(ch["id"])) + ok_ch += 1 + except Exception as e: + fail_ch.append(f"{entity_name(ch)}: {e}") + lines.append(f"✅ قنوات النشر المتاحة: {ok_ch}/{len(channels)}") + if fail_ch: + lines.append("⚠️ قنوات فشلت:") + lines.extend(["• " + x[:150] for x in fail_ch[:10]]) + sources = get_polling_sources() + ok_src = 0 + fail_src = [] + for src in sources[:120]: + try: + await hydrate_source_channel(int(src)) + ok_src += 1 + except Exception as e: + fail_src.append(f"{src}: {e}") + lines.append(f"✅ المصادر المتاحة: {ok_src}/{len(sources)}") + if fail_src: + lines.append("⚠️ مصادر فشلت:") + lines.extend(["• " + x[:150] for x in fail_src[:10]]) + await safe_edit(callback, "\n".join(lines)[:3900], InlineKeyboardMarkup([ + [InlineKeyboardButton("🟢 حالة النظام", callback_data="system_status")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + +async def warm_all_peers_after_import(): + await warm_middle_peer() + for ch in db.get_all_channels(): + try: + await hydrate_publish_channel(int(ch["id"])) + except Exception as e: + logger.warning(f"فشل تهيئة قناة نشر بعد الاستيراد {ch.get('id')}: {e}") + for src in get_polling_sources(): + try: + await hydrate_source_channel(int(src)) + except Exception as e: + logger.warning(f"فشل تهيئة مصدر بعد الاستيراد {src}: {e}") + + + +async def channel_quote_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + qt = get_channel_quote_types_safe(ch_id) + text = ( + f"💬 **إعدادات الاقتباس لقناة:**\n{channel_display_name(ch)}\n\n" + "اختر الأنواع التي تريد نشرها كاقتباس رسمي:\n\n" + f"• النصوص: {'✅ مفعل' if qt.get('text') else '❌ متوقف'}\n" + f"• الصور: {'✅ مفعل' if qt.get('photo') else '❌ متوقف'}\n" + f"• الفيديو: {'✅ مفعل' if qt.get('video') else '❌ متوقف'}\n" + f"• الألبومات: {'✅ مفعل' if qt.get('album') else '❌ متوقف'}" + ) + labels = {"text": "النصوص", "photo": "الصور", "video": "الفيديو", "album": "الألبومات"} + buttons = [] + for key in ["text", "photo", "video", "album"]: + mark = "✅" if qt.get(key) else "❌" + buttons.append(InlineKeyboardButton(f"{mark} {labels[key]}", callback_data=f"toggleqtype|{ch_id}|{key}")) + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")]) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def toggle_channel_quote_type(client, callback): + try: + _, ch_id, qtype = callback.data.split("|", 2) + except Exception: + await callback.answer("طلب غير صالح.", show_alert=True) + return + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + current = get_channel_quote_types_safe(ch_id).get(qtype, False) + if hasattr(db, "set_channel_quote_type"): + db.set_channel_quote_type(ch_id, qtype, not current) + else: + db.update_channel(ch_id, "quote_publish", not current) + await callback.answer("تم تحديث خيار الاقتباس.") + callback.data = f"quotemenu_{ch_id}" + await channel_quote_menu(client, callback) + + +async def toggle_channel_quote(client, callback): + # توافق قديم: إذا وصل callback قديم، افتح قائمة الأنواع بدل تبديل عام. + callback.data = callback.data.replace("togglequote_", "quotemenu_", 1) + await channel_quote_menu(client, callback) + + +async def channel_hashtags_menu(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + tags = db.get_channel_hashtags(ch_id) if hasattr(db, "get_channel_hashtags") else ch.get("hashtags", []) + text = ( + f"🏷 **هاشتاكات قناة النشر:**\n{channel_display_name(ch)}\n\n" + "تضاف تلقائياً أسفل المنشور لهذه القناة فقط.\n\n" + "الحالية:\n" + ("\n".join(f"• `{t}`" for t in tags) if tags else "لا توجد.") + ) + buttons = [ + InlineKeyboardButton("➕ إضافة جماعية", callback_data=f"addhashtags_{ch_id}"), + InlineKeyboardButton("🗑 حذف جماعي", callback_data=f"delhashtags_{ch_id}"), + ] + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🔙 رجوع", callback_data=f"ch_{ch_id}"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")]) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def add_channel_hashtags_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_channel_hashtags_add", "ch_id": ch_id} + await safe_edit(callback, "أرسل هاشتاك أو مجموعة هاشتاكات.\nكل هاشتاك بسطر مستقل:") + + +async def del_channel_hashtags_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_channel_hashtags_del", "ch_id": ch_id} + tags = db.get_channel_hashtags(ch_id) if hasattr(db, "get_channel_hashtags") else [] + current = "\n".join(f"• {t}" for t in tags) if tags else "لا توجد هاشتاكات حالياً." + await safe_edit(callback, "أرسل الهاشتاكات التي تريد حذفها.\nكل هاشتاك بسطر مستقل.\n\nالحالي:\n" + current) + + +async def test_publish_channel(client, callback): + ch_id = callback.data.split("_", 1)[1] + ch = db.get_channel(ch_id) + if not ch: + await callback.answer("القناة غير موجودة.") + return + try: + text = compose_channel_post_text(f"✅ اختبار نشر ناجح\n{entity_name(ch)}", ch_id, ch.get("tail", "")) + formatted, parse_mode, entities = format_outgoing_payload_for_channel(text, ch_id, "text") + await safe_send_channel_message(int(ch_id), formatted, parse_mode=parse_mode, entities=entities) + record_channel_success(ch_id) + await callback.answer("تم إرسال اختبار النشر.") + await notify_admins(f"تم اختبار النشر بنجاح إلى:\n{channel_display_name(ch)}") + except Exception as e: + await record_channel_failure_and_maybe_alert(ch_id, e) + await callback.answer("فشل اختبار النشر.", show_alert=True) + await notify_admins(f"فشل اختبار النشر إلى:\n{channel_display_name(ch)}\n\n{e}") + + +async def operations_menu(client, callback): + maintenance = db.is_maintenance_mode() if hasattr(db, "is_maintenance_mode") else False + ignore_short = is_ignore_short_posts_enabled() + text = ( + "🛠 **إدارة التشغيل**\n\n" + f"وضع الصيانة: {'✅ مفعل' if maintenance else '❌ متوقف'}\n" + f"تجاهل المنشورات القصيرة: {'✅ مفعل' if ignore_short else '❌ متوقف'}\n\n" + "وضع الصيانة يوقف النشر، لكن يبقي فحص المصادر مستمر حتى لا تتراكم الأخبار.\n" + "تجاهل المنشورات القصيرة يمنع نشر أي نص/كابشن أقل من 5 كلمات أو أقل من 20 حرف." + ) + buttons = [ + InlineKeyboardButton("🛠 تبديل الصيانة", callback_data="toggle_maintenance"), + InlineKeyboardButton("🚫 تبديل القصيرة", callback_data="toggle_short_posts"), + InlineKeyboardButton("🧪 اختبار كل القنوات", callback_data="test_all_channels"), + InlineKeyboardButton("⚠️ آخر الأخطاء", callback_data="errors_menu"), + ] + rows = grid_buttons(buttons, 2) + rows.append([InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")]) + await safe_edit(callback, text, InlineKeyboardMarkup(rows)) + + +async def toggle_maintenance_mode(client, callback): + current = db.is_maintenance_mode() if hasattr(db, "is_maintenance_mode") else False + if hasattr(db, "set_maintenance_mode"): + db.set_maintenance_mode(not current) + await callback.answer("تم تشغيل وضع الصيانة." if not current else "تم إيقاف وضع الصيانة.") + await operations_menu(client, callback) + + + +async def toggle_short_posts_filter(client, callback): + current = is_ignore_short_posts_enabled() + if hasattr(db, "set_ignore_short_posts"): + db.set_ignore_short_posts(not current) + await callback.answer("تم تحديث فلتر المنشورات القصيرة.") + await operations_menu(client, callback) + + +async def errors_menu(client, callback): + errors = db.get_last_errors(20) if hasattr(db, "get_last_errors") else [] + text = "⚠️ **آخر الأخطاء:**\n\n" + if not errors: + text += "لا توجد أخطاء مسجلة." + else: + rows_txt = [] + for e in reversed(errors[-20:]): + rows_txt.append(f"• {_format_ts(e.get('ts'))}\n {e.get('context')}\n `{str(e.get('error'))[:180]}`") + text += "\n\n".join(rows_txt) + buttons = [ + [InlineKeyboardButton("🗑 مسح الأخطاء", callback_data="clear_errors")], + [InlineKeyboardButton("🔙 رجوع", callback_data="ops_menu"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")] + ] + await safe_edit(callback, text[:3900], InlineKeyboardMarkup(buttons)) + + +async def clear_errors(client, callback): + if hasattr(db, "clear_last_errors"): + db.clear_last_errors() + await callback.answer("تم مسح لوحة الأخطاء.") + await errors_menu(client, callback) + + +async def named_backup_prompt(client, callback): + user_states.pop(callback.from_user.id, None) + user_states[callback.from_user.id] = {"state": "waiting_named_backup"} + await safe_edit(callback, "أرسل اسم النسخة الاحتياطية.\nمثال:\nstable_before_platform") + + +async def test_all_channels(client, callback): + channels = db.get_all_channels() + ok = 0 + fail = 0 + for ch in channels: + if ch.get("paused"): + continue + try: + ch_id = int(ch["id"]) + text = compose_channel_post_text(f"✅ اختبار نشر جماعي ناجح\n{entity_name(ch)}", ch_id, ch.get("tail", "")) + formatted, parse_mode, entities = format_outgoing_payload_for_channel(text, ch_id, "text") + await safe_send_channel_message(ch_id, formatted, parse_mode=parse_mode, entities=entities) + record_channel_success(ch_id) + ok += 1 + await asyncio.sleep(get_publish_delay_for_channel(ch_id)) + except Exception as e: + fail += 1 + await record_channel_failure_and_maybe_alert(ch.get("id"), e) + await safe_edit(callback, f"🧪 **نتيجة اختبار كل القنوات:**\n\n✅ نجح: {ok}\n❌ فشل: {fail}", InlineKeyboardMarkup([ + [InlineKeyboardButton("🔙 رجوع", callback_data="ops_menu"), InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")] + ])) +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, "أرسل مصدر خاص واحد أو عدة مصادر خاصة.\nكل رابط/يوزر/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"• {entity_name(ch)}\n ID: `{ch['id']}`\n المنشورات: **{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_timeout(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, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else 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_timeout(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, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else 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_timeout(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, "انتهت المهلة أو تعذر جلب المعلومات" if isinstance(e, asyncio.TimeoutError) else 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) + elif state == "waiting_source_cleanup_add": + source_id = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + terms = split_terms_lines(text) + result = db.add_source_remove_terms(source_id, terms) if hasattr(db, "add_source_remove_terms") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} عنصر للتنظيف الذكي.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع للتنظيف الذكي", callback_data=f"clean_src|{source_id}|{back}")], + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_source_cleanup_del": + source_id = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + terms = split_terms_lines(text) + result = db.remove_source_remove_terms(source_id, terms) if hasattr(db, "remove_source_remove_terms") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} عنصر من التنظيف الذكي.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع للتنظيف الذكي", callback_data=f"clean_src|{source_id}|{back}")], + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{source_id}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_global_cleanup_add": + terms = split_terms_lines(text) + result = db.add_global_remove_terms(terms) if hasattr(db, "add_global_remove_terms") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} عنصر لقائمة الحذف العامة.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الحذف العامة", callback_data="global_clean")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_global_cleanup_del": + terms = split_terms_lines(text) + result = db.remove_global_remove_terms(terms) if hasattr(db, "remove_global_remove_terms") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} عنصر من قائمة الحذف العامة.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🧹 رجوع لقائمة الحذف العامة", callback_data="global_clean")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_speed": + ch_id = user_states[uid]["ch_id"] + value = text.strip() + if value in {"0", "افتراضي", "default", "DEFAULT", ""}: + ok = db.set_channel_publish_delay(ch_id, None) if hasattr(db, "set_channel_publish_delay") else False + msg = "✅ تم إرجاع سرعة القناة للوضع الافتراضي." + else: + try: + delay = max(0.0, float(value)) + ok = db.set_channel_publish_delay(ch_id, delay) if hasattr(db, "set_channel_publish_delay") else False + msg = f"✅ تم حفظ سرعة القناة: {delay} ثانية." + except Exception: + ok = False + msg = "❌ أرسل رقم بالثواني، أو 0 للوضع الافتراضي." + await message.reply(msg, reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("⏱ رجوع لسرعة النشر", callback_data=f"speedmenu_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + elif state == "waiting_copy_source_settings": + from_source = user_states[uid]["source_id"] + back = user_states[uid].get("back", "menu_public_src") + targets = [] + failed = [] + for raw in split_bulk_lines(text): + try: + chat = await resolve_chat_info_timeout(raw, prefer_user=True) + meta = chat_meta(chat, raw) + db.update_source_meta(chat.id, **meta) if hasattr(db, "update_source_meta") else None + targets.append(int(chat.id)) + except Exception as e: + try: + targets.append(int(raw.strip())) + except Exception: + failed.append(f"{raw}: {e}") + copied = db.copy_source_settings(from_source, targets) if hasattr(db, "copy_source_settings") else 0 + msg = f"✅ تم نسخ إعدادات المصدر إلى {copied} مصدر." + if failed: + msg += "\n⚠️ فشل:\n" + "\n".join(failed[:10]) + await message.reply(msg, reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("⚙️ إعدادات المصدر", callback_data=f"srcset|{from_source}|{back}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ])) + + elif state == "waiting_channel_hashtags_add": + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.add_channel_hashtags(ch_id, terms) if hasattr(db, "add_channel_hashtags") else {"added": 0, "exists": 0} + await message.reply( + f"✅ تمت إضافة {result.get('added', 0)} هاشتاك.\n⚠️ موجود مسبقاً/فارغ: {result.get('exists', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🏷 رجوع للهاشتاكات", callback_data=f"hashtags_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_channel_hashtags_del": + ch_id = user_states[uid]["ch_id"] + terms = split_terms_lines(text) + result = db.remove_channel_hashtags(ch_id, terms) if hasattr(db, "remove_channel_hashtags") else {"removed": 0, "missing": 0} + await message.reply( + f"✅ تم حذف {result.get('removed', 0)} هاشتاك.\n⚠️ غير موجود: {result.get('missing', 0)}", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🏷 رجوع للهاشتاكات", callback_data=f"hashtags_{ch_id}")], + [InlineKeyboardButton("⚙️ إعدادات القناة", callback_data=f"ch_{ch_id}")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + elif state == "waiting_named_backup": + name = text.strip() + path = db.create_named_backup(name) if hasattr(db, "create_named_backup") else "" + await message.reply( + f"✅ تم إنشاء Backup باسم:\n`{name}`\n\nالملف:\n`{path}`", + reply_markup=InlineKeyboardMarkup([ + [InlineKeyboardButton("🛠 رجوع لإدارة التشغيل", callback_data="ops_menu")], + [InlineKeyboardButton("🏠 الرئيسية", callback_data="main_menu")], + ]) + ) + 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_special_source_map(): + """يرجع خريطة المصادر الخاصة: source_id -> set(channel_ids).""" + mapping = {} + for ch in db.get_all_channels(): + if ch.get("paused"): + continue + try: + ch_id = int(ch["id"]) + except Exception: + continue + for src in ch.get("special_sources") or []: + try: + src_id = int(src) + except Exception: + continue + mapping.setdefault(src_id, set()).add(ch_id) + return mapping + + +def get_polling_sources(): + """يجمع مصادر الفحص: المصادر العامة + المصادر الخاصة، بدون تكرار.""" + sources = set() + for src in db.get_public_sources() or []: + try: + sources.add(int(src)) + except Exception: + pass + for src in get_special_source_map().keys(): + sources.add(int(src)) + return sorted(sources) + + +def source_kind_label(source_id): + """نوع المصدر للّوج: خاص يغلب على العام إذا مضاف بالمكانين.""" + source_id = int(source_id) + if source_id in get_special_source_map(): + return "خاص" + if source_id in _to_int_set(db.get_public_sources()): + return "عام" + return "غير معروف" + + +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()) + special_map = get_special_source_map() + target_ids = set() + + # الخاص يغلب على العام + if source_id in special_map: + target_ids.update(special_map.get(source_id, set())) + logger.info(f"🟢 المصدر {source_id} خاص؛ القنوات المستهدفة: {sorted(target_ids)}") + return target_ids + + # مصدر عام: فقط القنوات التي لا تمتلك مصادر خاصة + if source_id in public_sources: + for ch in all_channels: + if ch.get("paused"): + continue + specials = ch.get("special_sources") or [] + if specials: + continue + try: + target_ids.add(int(ch["id"])) + except Exception as e: + logger.error(f"تعذر تحويل قناة النشر إلى رقم: {ch.get('id')} | {e}") + return 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) + content_type = content_type_for_message(message) + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info(f"🛠️ [{origin}] وضع الصيانة مفعل؛ تم تجاهل النشر وتحديث آخر رسالة للمصدر {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "maintenance mode", getattr(message, "id", None)) + return True + + if is_source_paused(source_id): + logger.info(f"⏸️ [{origin}] مصدر موقوف تم تجاهله: {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "source paused", getattr(message, "id", None)) + return True + + if not is_content_allowed_for_source(source_id, content_type): + logger.info(f"⛔ [{origin}] تم تجاهل منشور من {source_id} بسبب فلتر نوع المحتوى: {content_type}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", f"content type blocked: {content_type}", getattr(message, "id", None)) + return True + + raw_text = full_clean_text(raw_text, source_id=source_id) + + if raw_text and should_ignore_short_post(raw_text): + logger.info(f"⛔ [{origin}] تم تجاهل منشور قصير من {source_id}: {raw_text}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "short post", getattr(message, "id", None)) + return True + + logger.info(f"📨 [{origin}] رسالة من {source_id} | type={content_type} | message_id={message.id} | نص: {str(raw_text)[:80]}...") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "received", content_type, getattr(message, "id", None)) + + 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}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "rejected", f"blocked word: {bad_word}", getattr(message, "id", None)) + return True + + unsupported_reason = unsupported_media_reason(message) + if unsupported_reason: + logger.info(f"⛔ تم تجاهل المنشور لأنه يحتوي {unsupported_reason}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", f"unsupported: {unsupported_reason}", getattr(message, "id", None)) + return True + + if raw_text: + duplicated, ratio = is_smart_duplicate(raw_text, threshold=0.75) + if duplicated: + logger.info(f"🔁 منشور متشابه بنسبة {ratio:.0%}، تم تجاهله.") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", f"similarity {ratio:.0%}", getattr(message, "id", None)) + 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_for_source(raw_text, source_id) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, content_type) if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type=content_type, caption_entities=caption_entities) + if ok: + db.increment_post_count(target) + record_channel_success(target) + any_success = True + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل النشر إلى {target}: {e}") + + if any_success and raw_text: + remember_published_text(raw_text) + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "error", "media" if any_success else "media publish failed", getattr(message, "id", None), len(target_ids)) + 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_for_source(raw_text, source_id) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + + if final: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل النص: {e}") + formatted, parse_mode, entities = format_outgoing_payload_for_channel(final, target, "text") + sent_msg = await safe_send_channel_message(target, formatted, parse_mode=parse_mode, entities=entities) + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, "text") + else: + logger.info("🟡 منشور نصي فارغ بعد التنظيف؛ لن يتم إرساله.") + continue + + db.increment_post_count(target) + record_channel_success(target) + any_success = True + logger.info(f"✅ نُشر نص إلى {target}") + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"إرسال فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل الإرسال إلى {target}: {e}") + + if any_success and raw_text: + remember_published_text(raw_text) + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "error", "text" if any_success else "text publish failed", getattr(message, "id", None), len(target_ids)) + 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) + content_type = "album" + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info(f"🛠️ [{origin}] وضع الصيانة مفعل؛ تم تجاهل الألبوم وتحديث آخر رسالة للمصدر {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "maintenance mode", getattr(first, "id", None)) + return True + + if is_source_paused(source_id): + logger.info(f"⏸️ [{origin}] مصدر موقوف تم تجاهله: {source_id}") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "source paused", ids[-1] if 'ids' in locals() and ids else None) + return True + + if not is_content_allowed_for_source(source_id, content_type): + logger.info(f"⛔ [{origin}] تم تجاهل ألبوم من {source_id} بسبب فلتر نوع المحتوى") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "ignored", "content type blocked: album", ids[-1] if 'ids' in locals() and ids else None) + return True + + raw_text = full_clean_text(raw_text, source_id=source_id) + ids = [m.id for m in messages] + + logger.info(f"📨 [{origin}] ألبوم من {source_id} | message_ids={ids} | نص: {str(raw_text)[:80]}...") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "received", "album", ids[-1] if ids else None) + + 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 + + if raw_text: + duplicated, ratio = is_smart_duplicate(raw_text, threshold=0.75) + if duplicated: + logger.info(f"🔁 ألبوم متشابه بنسبة {ratio:.0%}، تم تجاهله.") + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "duplicate", f"similarity {ratio:.0%}", ids[-1] if ids else None) + 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_for_source(raw_text, source_id) + if cleaned is None: + logger.info("⛔ النص بعد التنظيف مرفوض لكلمة محظورة") + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, "album") if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type=content_type, caption_entities=caption_entities) + if ok: + db.increment_post_count(target) + record_channel_success(target) + any_success = True + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر الألبوم فاشل إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل نشر ألبوم إلى {target}: {e}") + + if any_success and raw_text: + remember_published_text(raw_text) + if hasattr(db, "record_source_event"): + db.record_source_event(source_id, "published" if any_success else "error", "album" if any_success else "album publish failed", ids[-1] if ids else None, len(target_ids)) + if not any_success: + logger.warning(f"⚠️ تم تمرير الألبوم للوسيطة لكن فشل نشره للقنوات. سيتم تحديث last_seen حتى لا يتكرر بالوسيطة: {getattr(first, 'media_group_id', '')}") + return True + + +async def user_message_handler(client, message): + pass # log muted: user update received + + 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: + poll_sources = get_polling_sources() + if not poll_sources: + await asyncio.sleep(25) + continue + + for source in poll_sources: + try: + source_id = int(source) + except Exception: + logger.warning(f"مصدر غير رقمي تم تجاهله: {source}") + continue + + kind = source_kind_label(source_id) + + if is_source_paused(source_id): + 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: + 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"🔁 [{kind}] المصدر {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: + continue + + logger.info(f"🔁 [{kind}] المصدر {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) + origin = f"polling][{kind}" + + 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=origin) + 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=origin) + 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"خطأ أثناء فحص المصدر [{kind}] {source}: {e}") + await notify_admins(f"فشل فحص المصدر [{kind}] {source}: {e}") + + await asyncio.sleep(25) + + except Exception as e: + logger.exception(f"خطأ عام في حلقة Polling: {e}") + await asyncio.sleep(30) + + +async def publish_middle_messages_to_all(middle_messages): + """ينشر منشوراً أو ألبوماً منشوراً يدوياً في الوسيطة إلى كل قنوات النشر.""" + if not isinstance(middle_messages, (list, tuple)): + middle_messages = [middle_messages] + middle_messages = sorted([m for m in middle_messages if m], key=lambda m: m.id) + if not middle_messages: + return + + first = middle_messages[0] + raw_text = full_clean_text(first.text or first.caption or "") + + if raw_text and should_ignore_short_post(raw_text): + logger.info(f"⛔ تم تجاهل منشور وسيطة قصير: {raw_text}") + return + + if hasattr(db, "is_maintenance_mode") and db.is_maintenance_mode(): + logger.info("🛠️ وضع الصيانة مفعل؛ تم تجاهل النشر اليدوي من الوسيطة.") + return + + for item in middle_messages: + unsupported_reason = unsupported_media_reason(item) + 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 + + all_channels = db.get_all_channels() + is_album = len(middle_messages) > 1 + + for ch in all_channels: + if ch.get("paused"): + continue + + target = int(ch["id"]) + + try: + cleaned = clean_text_for_source(raw_text, source_id) if raw_text else "" + if cleaned is None: + continue + + final = compose_channel_post_text(cleaned, target, ch.get("tail", "")) + + if is_album: + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, "album") if final else (None, None, None) + ok = await copy_middle_messages_to_target(target, middle_messages, formatted_caption, parse_mode=parse_mode, content_type="album", caption_entities=caption_entities) + if not ok: + continue + elif first.media: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل نسخة الوسيطة: {e}") + middle_ctype = published_content_type_for_message(first, False) + formatted_caption, parse_mode, caption_entities = format_outgoing_payload_for_channel(final, target, middle_ctype) if final else (None, None, None) + copy_kwargs = dict( + chat_id=target, + from_chat_id=config.MIDDLE_CHANNEL, + message_id=first.id, + caption=formatted_caption if formatted_caption else None, + parse_mode=None if caption_entities else parse_mode + ) + if caption_entities: + copy_kwargs["caption_entities"] = caption_entities + try: + sent_msg = await bot_client.copy_message(**copy_kwargs) + except TypeError: + copy_kwargs.pop("caption_entities", None) + copy_kwargs["parse_mode"] = parse_mode + sent_msg = await bot_client.copy_message(**copy_kwargs) + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, published_content_type_for_message(first, False)) + else: + try: + await hydrate_publish_channel(target) + except Exception as e: + logger.warning(f"⚠️ فشل تهيئة قناة النشر {target} قبل نص الوسيطة: {e}") + formatted, parse_mode, entities = format_outgoing_payload_for_channel(final if final else ".", target, "text") + sent_msg = await safe_send_channel_message(target, formatted, parse_mode=parse_mode, entities=entities) + if hasattr(db, "record_published_message") and getattr(sent_msg, "id", None): + db.record_published_message(target, sent_msg.id, "text") + + db.increment_post_count(target) + record_channel_success(target) + logger.info(f"✅ نُشر من الوسيطة إلى {target}") + await asyncio.sleep(get_publish_delay_for_channel(target)) + + except Exception as e: + logger.error(f"نشر فاشل من الوسيطة إلى {target}: {e}") + await record_channel_failure_and_maybe_alert(target, e) + await notify_admins(f"فشل النشر من الوسيطة إلى {target}: {e}") + + +async def flush_middle_album(media_group_id): + """يجمع ألبوم الوسيطة اليدوي ثم ينشره كألبوم واحد.""" + await asyncio.sleep(2.0) + messages = _middle_album_buffers.pop(media_group_id, []) + _middle_album_tasks.pop(media_group_id, None) + if not messages: + return + logger.info(f"📥 ألبوم في الوسيطة، جارٍ النشر كألبوم واحد | count={len(messages)}") + await publish_middle_messages_to_all(messages) + + +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 + + media_group_id = getattr(message, "media_group_id", None) + if media_group_id: + key = str(media_group_id) + _middle_album_buffers.setdefault(key, []).append(message) + if key not in _middle_album_tasks: + _middle_album_tasks[key] = asyncio.create_task(flush_middle_album(key)) + return + + logger.info("📥 رسالة في الوسيطة، جارٍ النشر...") + await publish_middle_messages_to_all([message]) + +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("togglebold_"): + await toggle_channel_bold(client, callback) + elif data.startswith("quotemenu_"): + await channel_quote_menu(client, callback) + elif data.startswith("toggleqtype|"): + await toggle_channel_quote_type(client, callback) + elif data.startswith("togglequote_"): + await toggle_channel_quote(client, callback) + elif data.startswith("hashtags_"): + await channel_hashtags_menu(client, callback) + elif data.startswith("addhashtags_"): + await add_channel_hashtags_prompt(client, callback) + elif data.startswith("delhashtags_"): + await del_channel_hashtags_prompt(client, callback) + elif data.startswith("testpub_"): + await test_publish_channel(client, callback) + elif data.startswith("purgepub|"): + await purge_published_prompt(client, callback) + elif data.startswith("confirmpurge|"): + await confirm_purge_published(client, callback) + elif data == "toggle_maintenance": + await toggle_maintenance_mode(client, callback) + elif data == "toggle_short_posts": + await toggle_short_posts_filter(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.startswith("srcset|"): + await source_settings_menu(client, callback) + elif data.startswith("togglesource|"): + await toggle_source_enabled(client, callback) + elif data.startswith("toggleemoji|"): + await toggle_source_emoji(client, callback) + elif data.startswith("contentmenu|"): + await source_content_menu(client, callback) + elif data.startswith("togglectype|"): + await toggle_content_type(client, callback) + elif data.startswith("clean_src|"): + await source_cleanup_menu(client, callback) + elif data.startswith("addclean|"): + await add_source_cleanup_prompt(client, callback) + elif data.startswith("delclean|"): + await del_source_cleanup_prompt(client, callback) + elif data == "global_clean": + await global_cleanup_menu(client, callback) + elif data == "addglobalclean": + await add_global_cleanup_prompt(client, callback) + elif data == "delglobalclean": + await del_global_cleanup_prompt(client, callback) + elif data.startswith("speedmenu_"): + await channel_speed_menu(client, callback) + elif data.startswith("setspeed|"): + await set_channel_speed(client, callback) + elif data.startswith("customspeed_"): + await custom_channel_speed_prompt(client, callback) + elif data.startswith("srcstats|"): + await source_stats_menu(client, callback) + elif data.startswith("srclog|"): + await source_log_menu(client, callback) + elif data.startswith("testsrc|"): + await test_source(client, callback) + elif data.startswith("copysrc|"): + await copy_source_settings_prompt(client, callback) + elif data.startswith("pastesrc|"): + await paste_source_settings(client, callback) + elif data == "system_status": + await system_status_menu(client, callback) + elif data == "full_check": + await full_check_menu(client, callback) + elif data == "ops_menu": + await operations_menu(client, callback) + elif data == "errors_menu": + await errors_menu(client, callback) + elif data == "clear_errors": + await clear_errors(client, callback) + elif data == "named_backup_prompt": + await named_backup_prompt(client, callback) + elif data == "test_all_channels": + await test_all_channels(client, callback) + elif data == "stats": + await show_stats(client, callback) + elif data == "backup_menu": + await backup_menu(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() + + try: + if hasattr(db, "cleanup_old_runtime_data"): + db.cleanup_old_runtime_data(days=3) + except Exception as e: + logger.warning(f"تعذر تنظيف بيانات التشغيل القديمة: {e}") + + await warm_middle_peer() + try: + await warm_all_peers_after_import() + except Exception as e: + logger.warning(f"فشل تهيئة القنوات/المصادر عند التشغيل: {e}") + + 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()