"""الترحيب، القوانين، الكيبورد المخصص، الردود، الأوامر البديلة، المنع، الاشتراك الاجباري (اختياري).""" from telegram import ChatPermissions, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove from core.kb import btn from telegram.ext import CallbackQueryHandler from core.router import exact, prefix, norm from core import ranks as R from core.store import settings from modules.toggles import tg_on from strings_ar import S, SIGA import config # أوضاع انتظار الإدخال (لكل جروب + مشرف): rules / welcome / kb_add / amr_old / amr_new _pending = {} def _key(update): return (update.effective_chat.id, update.effective_user.id) async def _admin(update): if await R.effective_level(update) < R.level("ادمن"): await update.message.reply_text(S["need_rank"]) return False return True def _fill(tpl, user, chat, members=None): """يدعم الدوال العربية والانجليزية في الترحيب.""" out = tpl vals = { "{الاسم}": user.first_name, "{المعرف}": ("@" + user.username) if user.username else user.first_name, "{المجموعه}": chat.title or "", "{الاعضاء}": str(members or ""), "{name}": user.first_name, "{group}": chat.title or "", } for k, v in vals.items(): out = out.replace(k, v) return out # ---------- الترحيب ---------- @prefix("ضع الترحيب") async def set_welcome(update, ctx, arg): if not await _admin(update): return text = arg if not text and update.message.reply_to_message: text = update.message.reply_to_message.text or "" if text: settings.set(update.effective_chat.id, "welcome", text) settings.set(update.effective_chat.id, "welcome_on", True) await update.message.reply_text(S["welcome_set"]) else: _pending[_key(update)] = "welcome" await update.message.reply_text(S["welcome_ask"]) @exact("ضع الترحيب") async def set_welcome2(update, ctx, arg=""): await set_welcome(update, ctx, "") @exact("تفعيل الترحيب") async def welcome_on(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "welcome_on", True) await update.message.reply_text(S["welcome_on"]) @exact("تعطيل الترحيب") async def welcome_off(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "welcome_on", False) await update.message.reply_text(S["welcome_off"]) @exact("تفعيل المغادره") async def leave_on(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "leave_on", True) await update.message.reply_text(S["done"]) @exact("تعطيل المغادره") async def leave_off(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "leave_on", False) await update.message.reply_text(S["done"]) async def on_join(update, ctx): """ترحيب بالأعضاء الجداد (رسالة في الجروب نفسه فقط).""" m = update.message if not m or not m.new_chat_members: return chat = update.effective_chat # حظر عام: أي محظور عام يدخل يتطرد على طول from modules import admin as _admin_mod for u in m.new_chat_members: if not u.is_bot and _admin_mod.is_gbanned(u.id): try: await chat.ban_member(u.id) except Exception: pass # قفل البوتات: طرد أي بوت يتضاف (مش بتاعنا) me = await ctx.bot.get_me() for u in m.new_chat_members: if u.is_bot and u.id != me.id and settings.get(chat.id, "lock_البوتات", False): try: await chat.ban_member(u.id) await chat.unban_member(u.id) except Exception: pass # قفل الاضافه: طرد العضو المضاف لو اللي ضافه مش أدمن if settings.get(chat.id, "lock_الاضافه", False): adder = m.from_user is_adm = adder and await R.effective_level(update, adder) >= R.level("ادمن") if not is_adm: for u in m.new_chat_members: if u.id == (adder.id if adder else 0) or u.is_bot: continue try: await chat.ban_member(u.id) await chat.unban_member(u.id) await m.reply_text(S["lock_deleted"].format(what="اضافة الأعضاء")) except Exception: pass return await _captcha_join(update, ctx, m.new_chat_members) if not settings.get(chat.id, "welcome_on", True) or not tg_on(chat.id, "welcome"): return tpl = settings.get(chat.id, "welcome", S["welcome_default"]) try: members = await chat.get_member_count() except Exception: members = None for u in m.new_chat_members: if u.is_bot: continue try: await m.reply_text(_fill(tpl, u, chat, members)) except Exception: await m.reply_text(_fill(S["welcome_default"], u, chat, members)) async def on_leave(update, ctx): """رسالة وداع لو المغادره مفعلة.""" m = update.message if not m or not m.left_chat_member: return chat = update.effective_chat if not settings.get(chat.id, "leave_on", False) or not tg_on(chat.id, "leave"): return u = m.left_chat_member try: await m.reply_text(_fill(S["bye_default"], u, chat)) except Exception: pass # ---------- المصادقه (زر تأكيد للأعضاء الجداد) ---------- @exact("تفعيل المصادقه") async def captcha_on(update, ctx, arg=""): if not await _admin(update): return settings.set(update.effective_chat.id, "captcha_on", True) await update.message.reply_text("✧︙اتفعلت المصادقه ✅ أي عضو جديد لازم يدوس زر التأكيد قبل ما يكتب.") @exact("تعطيل المصادقه") async def captcha_off(update, ctx, arg=""): if not await _admin(update): return settings.set(update.effective_chat.id, "captcha_on", False) await update.message.reply_text("✧︙اتعطلت المصادقه.") async def _captcha_join(update, ctx, users): chat = update.effective_chat if not settings.get(chat.id, "captcha_on", False): return for u in users: if u.is_bot: continue try: await chat.restrict_member(u.id, ChatPermissions(can_send_messages=False)) kb = InlineKeyboardMarkup([[btn("✅ اضغط هنا للتأكيد", f"cap:{u.id}", style="success")]]) msg = "✧︙أهلا " + u.first_name + " 👋\n✧︙دوس على الزر تحت عشان نتأكد انك مش بوت وتفتح الكتابة." await ctx.bot.send_message(chat.id, msg, reply_markup=kb) except Exception: pass async def captcha_cb(update, ctx): q = update.callback_query uid = int(q.data.split(":")[1]) if q.from_user.id != uid: await q.answer("✧︙الزر ده مش ليك 😅", show_alert=True) return try: await q.message.chat.restrict_member( uid, ChatPermissions(can_send_messages=True, can_send_audios=True, can_send_documents=True, can_send_photos=True, can_send_videos=True, can_send_video_notes=True, can_send_voice_notes=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True)) except Exception: pass await q.answer("✅ اتأكدت، أهلًا بيك!") try: await q.edit_message_text(f"✧︙{q.from_user.first_name} عدّى المصادقه ✅ أهلا بيك في الجروب 🌹") except Exception: pass # ---------- القوانين ---------- @prefix("ضع قوانين") async def set_rules(update, ctx, arg): if not await _admin(update): return if arg: settings.set(update.effective_chat.id, "rules", arg) await update.message.reply_text(S["rules_set"]) else: _pending[_key(update)] = "rules" await update.message.reply_text(S["rules_ask"]) @exact("ضع قوانين") async def set_rules2(update, ctx, arg=""): await set_rules(update, ctx, "") @exact("القوانين") async def rules(update, ctx, arg=""): await update.message.reply_text(settings.get(update.effective_chat.id, "rules", S["rules_none"])) @exact("مسح القوانين") async def clear_rules(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "rules", "") await update.message.reply_text(S["rules_cleared"]) # ---------- الكيبورد المخصص ---------- def kb_markup(chat_id): """كيبورد الأدمن المخصص (بيرجع ReplyKeyboardMarkup أو None).""" btns = settings.get(chat_id, "kb_buttons", []) if not btns: return None rows = [btns[i:i + 2] for i in range(0, len(btns), 2)] return ReplyKeyboardMarkup(rows, resize_keyboard=True) _KB_KB = ReplyKeyboardMarkup([["Add"], ["تم", "مسح الكيبورد"]], resize_keyboard=True) @exact("كيبورد") async def kb_start(update, ctx, arg=""): if not await _admin(update): return ctx.chat_data["kb_mode"] = True await update.message.reply_text(S["kb_start"], reply_markup=_KB_KB) @exact("Add") async def kb_add(update, ctx, arg=""): if not ctx.chat_data.get("kb_mode"): return if not await _admin(update): return _pending[_key(update)] = "kb_add" await update.message.reply_text(S["kb_ask_name"], reply_markup=_KB_KB) @exact("تم") async def kb_done(update, ctx, arg=""): if not ctx.chat_data.pop("kb_mode", None): return _pending.pop(_key(update), None) mk = kb_markup(update.effective_chat.id) await update.message.reply_text(S["kb_saved"], reply_markup=mk or ReplyKeyboardRemove()) @exact("مسح الكيبورد") async def kb_clear(update, ctx, arg=""): if not await _admin(update): return ctx.chat_data.pop("kb_mode", None) _pending.pop(_key(update), None) settings.set(update.effective_chat.id, "kb_buttons", []) await update.message.reply_text(S["kb_cleared"], reply_markup=ReplyKeyboardRemove()) # ---------- ردود مخصصة ---------- def _add_reply(chat_id, key, val, scope="replies"): from modules.special_replies import MAX_REPLIES_PER_WORD d = settings.get(chat_id, scope, {}) k = norm(key) cur = d.get(k) items = list(cur) if isinstance(cur, list) else ([x for x in cur.split("|") if x.strip()] if isinstance(cur, str) else []) new_vals = [x.strip() for x in val.split("|") if x.strip()] added = 0 for nv in new_vals: if len(items) < MAX_REPLIES_PER_WORD: items.append(nv) added += 1 d[k] = items settings.set(chat_id, scope, d) return added, len(items) @exact("اضف رد") async def add_reply_interactive(update, ctx, arg=""): if not await _admin(update): return from modules import special_replies as sr sr.start_session(update.effective_chat.id, update.effective_user.id, "group") await update.message.reply_text("✧︙ابعت الكلمة اللي عايز تضيف ليها رد (تقدر تضيف لحد 40 رد نص أو ستيكر أو ميديا):") @exact("اضف رد عام") async def add_greply_interactive(update, ctx, arg=""): if await R.effective_level(update) < R.level("مالك"): await update.message.reply_text(S["need_rank"]) return from modules import special_replies as sr sr.start_session(update.effective_chat.id, update.effective_user.id, "global") await update.message.reply_text("✧︙ابعت الكلمة اللي عايز تضيف ليها رد عام لكل الجروبات (لحد 40 رد نص أو ستيكر أو ميديا):") @exact("اضف رد عشوائي") async def reply_usage(update, ctx, arg=""): await update.message.reply_text(S["reply_format"]) @prefix("اضف رد عام") async def add_greply(update, ctx, arg): if await R.effective_level(update) < R.level("مالك"): await update.message.reply_text(S["need_rank"]) return from modules import special_replies as sr if "=" in arg: k, v = arg.split("=", 1) added, total = _add_reply("global", k.strip(), v.strip(), "greplies") if added == 0: await update.message.reply_text(f"✧︙وصلت للحد الأقصى ({sr.MAX_REPLIES_PER_WORD} رد) لهذه الكلمة.") else: await update.message.reply_text(f"✧︙تم حفظ الرد العام ({total}/{sr.MAX_REPLIES_PER_WORD}) وهيشتغل في كل الجروبات ✅") return # بالرد على ستيكر / صورة / فيديو / نص مباشرة r = update.message.reply_to_message if r: entry = sr.extract_entry(r) if entry: ok, total = sr.append_special_entry("global", arg.strip(), entry) if not ok: await update.message.reply_text(f"✧︙وصلت للحد الأقصى ({sr.MAX_REPLIES_PER_WORD} رد) لهذه الكلمة.") else: await update.message.reply_text(f"✧︙تم حفظ الرد العام رقم {total}/{sr.MAX_REPLIES_PER_WORD} لكلمة ({arg.strip()}) لكل الجروبات ✅") return sr.start_session(update.effective_chat.id, update.effective_user.id, "global", trigger_text=arg.strip()) await update.message.reply_text(sr.PROMPT_MEDIA) @prefix("اضف رد عشوائي") async def add_rreply(update, ctx, arg): """رد عشوائي: اضف رد عشوائي الكلمة=رد1|رد2|رد3 (حتى 40 رد)""" if not await _admin(update): return if "=" not in arg: await update.message.reply_text(S["reply_format"]) return k, v = arg.split("=", 1) added, total = _add_reply(update.effective_chat.id, k.strip(), v.strip(), "replies") await update.message.reply_text(f"✧︙تم حفظ الرد ({total}/40) ✅") @prefix("اضف رد") async def add_reply(update, ctx, arg): if not await _admin(update): return from modules import special_replies as sr if "=" in arg: k, v = arg.split("=", 1) added, total = _add_reply(update.effective_chat.id, k.strip(), v.strip()) if added == 0: await update.message.reply_text(f"✧︙وصلت للحد الأقصى ({sr.MAX_REPLIES_PER_WORD} رد) لهذه الكلمة.") else: await update.message.reply_text(f"✧︙تم حفظ الرد ({total}/{sr.MAX_REPLIES_PER_WORD}) ✅") return # بالرد على ستيكر / صورة / فيديو / نص مباشرة r = update.message.reply_to_message if r: entry = sr.extract_entry(r) if entry: ok, total = sr.append_special_entry(update.effective_chat.id, arg.strip(), entry) if not ok: await update.message.reply_text(f"✧︙وصلت للحد الأقصى ({sr.MAX_REPLIES_PER_WORD} رد) لهذه الكلمة.") else: await update.message.reply_text(f"✧︙تم حفظ الرد رقم {total}/{sr.MAX_REPLIES_PER_WORD} لكلمة ({arg.strip()}) ✅") return sr.start_session(update.effective_chat.id, update.effective_user.id, "group", trigger_text=arg.strip()) await update.message.reply_text(sr.PROMPT_MEDIA) @prefix("مسح رد عام") async def del_greply(update, ctx, arg): if await R.effective_level(update) < R.level("مالك"): await update.message.reply_text(S["need_rank"]) return k = norm(arg) g1 = settings.get("global", "greplies", {}) g1.pop(k, None) settings.set("global", "greplies", g1) g2 = settings.get("global", "special_replies", {}) g2.pop(k, None) settings.set("global", "special_replies", g2) await update.message.reply_text(S["reply_removed"]) @prefix("مسح رد") async def del_reply(update, ctx, arg): if not await _admin(update): return k = norm(arg) d = settings.get(update.effective_chat.id, "replies", {}) d.pop(k, None) settings.set(update.effective_chat.id, "replies", d) sp = settings.get(update.effective_chat.id, "special_replies", {}) sp.pop(k, None) settings.set(update.effective_chat.id, "special_replies", sp) await update.message.reply_text(S["reply_removed"]) @exact("الردود") async def list_replies(update, ctx, arg=""): d1 = settings.get(update.effective_chat.id, "replies", {}) d2 = settings.get(update.effective_chat.id, "special_replies", {}) keys = sorted(set(list(d1.keys()) + list(d2.keys()))) if not keys: await update.message.reply_text(S["replies_empty"]) return lines = [S["replies_title"]] + [f"✧︙{k}" for k in keys[:50]] await update.message.reply_text("\n".join(lines)) async def custom_reply(update, ctx): import random chat = update.effective_chat.id t = norm(update.message.text or "") if tg_on(chat, "replies"): d = settings.get(chat, "replies", {}) if t in d: v = d[t] choice = random.choice(v) if isinstance(v, list) else (random.choice(v.split("|")) if "|" in v else v) await update.message.reply_text(choice) return True if tg_on(chat, "greplies"): g = settings.get("global", "greplies", {}) if t in g: v = g[t] choice = random.choice(v) if isinstance(v, list) else (random.choice(v.split("|")) if "|" in v else v) await update.message.reply_text(choice) return True g_local = settings.get(chat, "greplies", {}) if t in g_local: v = g_local[t] choice = random.choice(v) if isinstance(v, list) else (random.choice(v.split("|")) if "|" in v else v) await update.message.reply_text(choice) return True if tg_on(chat, "siga"): for k, v in SIGA.items(): if norm(k) == t: await update.message.reply_text(v) return True return False # ---------- اضف امر / مسح امر (أسماء بديلة للأوامر) ---------- @exact("اضف امر") async def amr_start(update, ctx, arg=""): if not await _admin(update): return _pending[_key(update)] = "amr_old" kb = InlineKeyboardMarkup([[btn("- الغاء الامر", "amr:cancel", style="danger")]]) await update.message.reply_text(S["amr_ask_old"], reply_markup=kb) @prefix("مسح امر") async def amr_del(update, ctx, arg): if not await _admin(update): return d = settings.get(update.effective_chat.id, "aliases", {}) if norm(arg) in d: d.pop(norm(arg)) settings.set(update.effective_chat.id, "aliases", d) await update.message.reply_text(S["amr_deleted"].format(name=arg)) else: await update.message.reply_text(S["amr_not_found"]) async def amr_cancel_cb(update, ctx): q = update.callback_query _pending.pop((q.message.chat.id, q.from_user.id), None) await q.answer() await q.edit_message_text(S["amr_cancelled"]) # ---------- منع الكلمات ---------- @prefix("منع") async def block_word(update, ctx, arg): if not await _admin(update) or not arg: return d = settings.get(update.effective_chat.id, "blocked", []) w = norm(arg) if w not in d: d.append(w) settings.set(update.effective_chat.id, "blocked", d) await update.message.reply_text(S["blocked_word_on"].format(w=arg)) @prefix("الغاء منع") async def unblock_word(update, ctx, arg): if not await _admin(update): return d = settings.get(update.effective_chat.id, "blocked", []) w = norm(arg) if w in d: d.remove(w) settings.set(update.effective_chat.id, "blocked", d) await update.message.reply_text(S["blocked_word_off"].format(w=arg)) @exact("قائمه المنع") async def blocked_list(update, ctx, arg=""): d = settings.get(update.effective_chat.id, "blocked", []) if not d: await update.message.reply_text(S["blocked_none"]) return await update.message.reply_text(S["blocked_title"] + "\n" + "\n".join("✧︙" + w for w in d[:50])) # ---------- الرابط ---------- @exact("الرابط") async def link(update, ctx, arg=""): if not tg_on(update.effective_chat.id, "link"): await update.message.reply_text(S["feature_off"]) return l = settings.get(update.effective_chat.id, "link", "") await update.message.reply_text(S["link_fmt"].format(link=l) if l else S["link_none"]) @exact("انشاء رابط") async def make_link(update, ctx, arg=""): if not await _admin(update): return try: l = await update.effective_chat.export_invite_link() settings.set(update.effective_chat.id, "link", l) await update.message.reply_text(S["link_fmt"].format(link=l)) except Exception: await update.message.reply_text(S["link_fail"]) @exact("مسح الرابط") async def del_link(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "link", "") await update.message.reply_text(S["done"]) # ---------- اشتراك اجباري: اختياري ومقفول افتراضيا ---------- @prefix("اضف قناه") async def force_add(update, ctx, arg): if await _admin(update) and arg.strip().startswith("@"): settings.set(update.effective_chat.id, "force_ch", arg.strip()) await update.message.reply_text(S["force_set"].format(ch=arg.strip())) @exact("مسح القناه", "تعطيل الاشتراك الاجباري") async def force_del(update, ctx, arg=""): if await _admin(update): settings.set(update.effective_chat.id, "force_ch", "") await update.message.reply_text(S["force_off"]) async def force_gate(update, ctx): """True لو الرسالة اتحذفت لأن العضو مش مشترك. مقفول لو مفيش قناة.""" ch = settings.get(update.effective_chat.id, "force_ch", "") or config.FORCE_SUB_CHANNEL if not ch or not update.message or not update.effective_user: return False if await R.effective_level(update) >= R.level("ادمن"): return False try: m = await ctx.bot.get_chat_member(ch, update.effective_user.id) if m.status in ("left", "kicked"): await update.message.delete() await ctx.bot.send_message(update.effective_chat.id, S["force_sub"].format(ch=ch)) return True except Exception: pass return False # ---------- معالج أوضاع الانتظار (خطوات الأدمن) ---------- async def pending_flow(update, ctx): """بيمسك رسايل الأدمن اللي جوه خطوة (ترحيب/قوانين/كيبورد/اضف امر). True لو الرسالة اتعاملت.""" k = _key(update) mode = _pending.get(k) if not mode or not update.message or not update.message.text: return False text = update.message.text.strip() chat = update.effective_chat.id if norm(text) == "الغاء": _pending.pop(k, None) await update.message.reply_text(S["amr_cancelled"]) return True if mode == "welcome": _pending.pop(k, None) settings.set(chat, "welcome", text) settings.set(chat, "welcome_on", True) await update.message.reply_text(S["welcome_set"]) return True if mode == "rules": _pending.pop(k, None) settings.set(chat, "rules", text) await update.message.reply_text(S["rules_set"]) return True if mode == "kb_add": if norm(text) in ("تم", "مسح الكيبورد"): return False _pending.pop(k, None) btns = settings.get(chat, "kb_buttons", []) btns.append(text[:40]) settings.set(chat, "kb_buttons", btns) await update.message.reply_text(S["kb_added_wait"], reply_markup=_KB_KB) return True if mode == "amr_old": from core import router f, _ = router.find(text, None) # الأمر القديم لازم يكون أمر حقيقي (مش alias) if not f: await update.message.reply_text(S["amr_not_found"]) return True _pending[k] = ("amr_new", norm(text)) await update.message.reply_text(S["amr_ask_new"]) return True if isinstance(mode, tuple) and mode[0] == "amr_new": _pending.pop(k, None) d = settings.get(chat, "aliases", {}) d[norm(text)] = mode[1] settings.set(chat, "aliases", d) await update.message.reply_text(S["amr_saved"].format(new=text)) return True return False HANDLERS = [CallbackQueryHandler(amr_cancel_cb, pattern=r"^amr:cancel$"), CallbackQueryHandler(captcha_cb, pattern=r"^cap:")]