df / modules /locks.py
ABO3MR's picture
Upload folder using huggingface_hub
3a3b605 verified
Raw History Blame Contribute Delete
22.1 kB
"""نظام الحماية الشامل (40 قفل) + أوضاع {بالتقييد، بالطرد، بالكتم} + التوحيد + المضاد + لوحة أزرار حية (✓ أخضر / ✗ أحمر)."""
import re
import time
from collections import defaultdict, deque
from telegram import ChatPermissions, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler
from core.kb import btn
from core.router import exact, prefix, norm
from core import ranks as R
from core.store import settings, bump
from modules.toggles import tg_on
from strings_ar import S, LOCKS, BAD_WORDS, KUFR_WORDS, PORN_HINTS
LINK = re.compile(r"(https?://|t\.me/|www\.|telegram\.me/)", re.I)
CHANNEL_LINK = re.compile(r"(t\.me/\+|t\.me/joinchat/|t\.me/[a-zA-Z0-9_]{4,})", re.I)
PERSIAN = re.compile(r"[پچژگڭڪ]")
ENGLISH = re.compile(r"[A-Za-z]{3,}")
MENTION = re.compile(r"@\w{4,}")
HASHTAG = re.compile(r"#\S")
USERBOT_CMD = re.compile(r"^[\.!؟](\w+|جمثون|تليثون|سورس)", re.I)
KEYS = {norm(k): k for k in LOCKS}
KEYS.update({
norm("الفشار"): "السب",
norm("المعرف"): "المعرفات",
norm("الاستيكر"): "الملصقات",
norm("الملصق"): "الملصقات",
norm("الكتابه"): "الدردشه",
norm("الكتابة"): "الدردشه",
norm("البصمات"): "الصوت",
norm("الفيديوهات"): "الفيديو",
norm("المتحركات"): "المتحركه",
norm("الصوتيات"): "الاغاني",
norm("الانكليزيه"): "الانجليزيه",
norm("الانكليزية"): "الانجليزيه",
norm("الإنكليزيه"): "الانجليزيه",
norm("الايرانيه"): "الفارسيه",
norm("الإيرانيه"): "الفارسيه",
norm("الاباحيه"): "الاباحي",
norm("الماركدوان"): "الماركداون",
norm("توجيه الستوري"): "الستوري",
norm("توجية الستوري"): "الستوري",
norm("الاضافه"): "الدخول",
norm("الويب"): "الروابط",
})
PANEL_HEADER = "⌁︙اوامر القفل والفتح ↫ ‡\n⌁︙( ( ✓ ) مقفول ) | ( ( ✗ ) مفتوح )"
_flood = defaultdict(lambda: deque(maxlen=20))
_raid = defaultdict(lambda: deque(maxlen=30))
MUTE_PERMS = ChatPermissions(can_send_messages=False)
def _on(chat, k):
return settings.get(chat, "lock_" + k, False)
def _mode(chat, k):
"""'delete' (مسح) أو 'restrict' (تقييد) أو 'mute' (كتم) أو 'kick' (طرد)."""
return settings.get(chat, "lmode_" + k, "delete")
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 _parse_lock_arg(arg):
n = norm(arg)
mode = "delete"
for suffix, m in (
(" بالتقييد", "restrict"),
(" بالكتم", "mute"),
(" بالطرد", "kick"),
):
if n.endswith(norm(suffix)):
n = n[:-len(norm(suffix))].strip()
mode = m
break
return n, mode
@prefix("قفل")
async def lock(update, ctx, arg):
if not await _admin(update):
return
chat = update.effective_chat.id
by = update.effective_user.first_name
n, mode = _parse_lock_arg(arg)
if n == norm("الكل"):
for k in LOCKS:
if k not in ("الدردشه", "وسائط المميزين"):
settings.set(chat, "lock_" + k, True)
settings.set(chat, "lmode_" + k, mode)
await update.message.reply_text(S["lock_on"].format(what="الكل (جميع أقفال الحماية)", by=by))
return
if n in (norm("الالعاب"), norm("اللعبه"), norm("اللعبة")):
settings.set(chat, "tg_games", False)
await update.message.reply_text(S["lock_on"].format(what="الألعاب", by=by))
return
k = KEYS.get(n)
if not k:
await update.message.reply_text(S["lock_unknown"])
return
settings.set(chat, "lock_" + k, True)
settings.set(chat, "lmode_" + k, mode)
msg_key = {"restrict": "lock_on_restrict", "mute": "lock_on_mute", "kick": "lock_on_kick"}.get(mode, "lock_on")
await update.message.reply_text(S[msg_key].format(what=LOCKS[k], by=by))
@prefix("فتح")
async def unlock(update, ctx, arg):
if not await _admin(update):
return
chat = update.effective_chat.id
by = update.effective_user.first_name
n, _ = _parse_lock_arg(arg)
if n == norm("الكل"):
for k in LOCKS:
settings.set(chat, "lock_" + k, False)
settings.set(chat, "lmode_" + k, "delete")
await update.message.reply_text(S["lock_off"].format(what="الكل", by=by))
return
if n in (norm("الالعاب"), norm("اللعبه"), norm("اللعبة")):
settings.set(chat, "tg_games", True)
await update.message.reply_text(S["lock_off"].format(what="الألعاب", by=by))
return
k = KEYS.get(n)
if not k:
await update.message.reply_text(S["lock_unknown"])
return
settings.set(chat, "lock_" + k, False)
settings.set(chat, "lmode_" + k, "delete")
await update.message.reply_text(S["lock_off"].format(what=LOCKS[k], by=by))
@prefix("ضع تكرار", "ضع التكرار")
async def set_flood_limit(update, ctx, arg):
if not await _admin(update):
return
try:
n = int(arg.strip())
assert 2 <= n <= 20
except Exception:
await update.message.reply_text("✧︙اكتب رقم بين 2 و 20، مثال: ضع التكرار 4")
return
settings.set(update.effective_chat.id, "flood_limit", n)
settings.set(update.effective_chat.id, "lock_التكرار", True)
await update.message.reply_text(f"✧︙تم تعيين حد التكرار إلى {n} رسايل وتفعيل قفل التكرار ✅")
# ---------- نظام التوحيد (رمز موحّد في الاسم) ----------
@prefix("ضع التوحيد")
async def set_unity(update, ctx, arg):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
sym = arg.strip()
if not sym:
await update.message.reply_text("✧︙اكتب: ضع التوحيد + الرمز (مثال: ضع التوحيد 🦅)")
return
settings.set(update.effective_chat.id, "unity_symbol", sym)
settings.set(update.effective_chat.id, "unity_on", True)
await update.message.reply_text(f"✧︙تم تعيين رمز التوحيد: {sym} وتفعيل التوحيد ✅")
@exact("تفعيل التوحيد")
async def unity_on(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "unity_on", True)
await update.message.reply_text("✧︙تم تفعيل التوحيد ✅")
@exact("تعطيل التوحيد")
async def unity_off(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "unity_on", False)
await update.message.reply_text("✧︙تم تعطيل التوحيد ❌")
@exact("تفعيل التوحيد بالكتم")
async def unity_mute_on(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "unity_mute", True)
await update.message.reply_text("✧︙تم تفعيل التوحيد بالكتم ✅")
@exact("تعطيل التوحيد بالكتم")
async def unity_mute_off(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "unity_mute", False)
await update.message.reply_text("✧︙تم تعطيل التوحيد بالكتم ❌")
@prefix("ضع عدد الكتم")
async def set_mute_count(update, ctx, arg):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
try:
n = int(arg.strip())
assert 1 <= n <= 20
except Exception:
await update.message.reply_text("✧︙اكتب رقم صحيح، مثال: ضع عدد الكتم 3")
return
settings.set(update.effective_chat.id, "unity_mute_count", n)
await update.message.reply_text(f"✧︙تم تعيين عدد رسايل الكتم إلى {n} ✅")
# ---------- نظام المضاد (مضاد التفليش والسبام الجماعي) ----------
@exact("تفعيل المضاد")
async def anti_on(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "lock_التفليش", True)
settings.set(update.effective_chat.id, "lock_البوتات", True)
settings.set(update.effective_chat.id, "lmode_البوتات", "kick")
await update.message.reply_text("🛡️ تم تفعيل نظام المضاد (حماية من التفليش ودخول البوتات) ✅")
@exact("تعطيل المضاد")
async def anti_off(update, ctx, arg=""):
if await R.effective_level(update) < R.level("منشئ"):
await update.message.reply_text(S["need_rank"])
return
settings.set(update.effective_chat.id, "lock_التفليش", False)
await update.message.reply_text("🛡️ تم تعطيل نظام المضاد ❌")
@exact("اعدادات المضاد")
async def anti_settings(update, ctx, arg=""):
chat = update.effective_chat.id
st = lambda b: "مفعل ✓" if b else "معطل ✗"
await update.message.reply_text(
f"🛡️ إعدادات المضاد:\n"
f"✧︙مضاد التفليش: {st(_on(chat, 'التفليش'))}\n"
f"✧︙قفل البوتات: {st(_on(chat, 'البوتات'))} ({_mode(chat, 'البوتات')})\n"
f"✧︙قفل التكرار: {st(_on(chat, 'التكرار'))} (الحد: {settings.get(chat, 'flood_limit', 3)})\n"
f"✧︙التوحيد: {st(settings.get(chat, 'unity_on', False))} (الرمز: {settings.get(chat, 'unity_symbol', 'غير محدد')})"
)
@exact("تفعيل الحمايه")
async def protect_on(update, ctx, arg=""):
if not await _admin(update):
return
for k in ("الروابط", "السب", "الاباحي", "الكفر", "التوجيه", "المعرفات", "البوتات", "التكرار", "ارسال القناة", "التفليش"):
settings.set(update.effective_chat.id, "lock_" + k, True)
await update.message.reply_text("🛡️ تم تفعيل الحماية الشاملة للمجموعه ✅")
@exact("تعطيل الحمايه")
async def protect_off(update, ctx, arg=""):
if not await _admin(update):
return
for k in LOCKS:
settings.set(update.effective_chat.id, "lock_" + k, False)
settings.set(update.effective_chat.id, "lmode_" + k, "delete")
await update.message.reply_text("🔓 تم تعطيل جميع أقفال الحماية ✅")
# ---------- لوحة القفل والفتح الحية (✓ أخضر / ✗ أحمر — زرين في الصف) ----------
LOCK_LIST = list(LOCKS.keys())
PAGE_SIZE = 16
def panel_kb(chat_id=0, page=0):
start = page * PAGE_SIZE
chunk = LOCK_LIST[start:start + PAGE_SIZE]
rows = []
for i in range(0, len(chunk), 2):
row = []
for k in chunk[i:i + 2]:
locked = _on(chat_id, k) if chat_id else False
icon = "✓" if locked else "✗"
st = "success" if locked else "danger"
row.append(btn(f"{k} : {icon}", f"lk:tog:{k}:{page}", style=st))
rows.append(row)
nav = []
if page > 0:
nav.append(btn("• السابق •", f"lk:page:{page - 1}", style="primary"))
if start + PAGE_SIZE < len(LOCK_LIST):
nav.append(btn("• التالي •", f"lk:page:{page + 1}", style="primary"))
if nav:
rows.append(nav)
rows.append([btn("التفعيل و التعطيل", "mn:tg", style="primary"), btn("- اخفاء -", "lk:hide", style="danger")])
return InlineKeyboardMarkup(rows)
@exact("القفل والفتح", "الفتح والقفل")
async def panel(update, ctx, arg=""):
if not await _admin(update):
return
await update.message.reply_text(PANEL_HEADER, reply_markup=panel_kb(update.effective_chat.id, 0))
async def cb(update, ctx):
q = update.callback_query
parts = q.data.split(":")
if parts[1] == "hide":
await q.answer()
try:
await q.delete_message()
except Exception:
pass
return
chat_id = q.message.chat.id
if parts[1] == "page":
await q.answer()
p = int(parts[2])
try:
await q.edit_message_reply_markup(reply_markup=panel_kb(chat_id, p))
except Exception:
pass
return
lv = await R.effective_level(update, q.from_user)
if lv < R.level("ادمن"):
await q.answer(S["need_admin"], show_alert=True)
return
if parts[1] == "tog":
k, p = parts[2], int(parts[3])
if k not in LOCKS:
await q.answer()
return
new_val = not _on(chat_id, k)
settings.set(chat_id, "lock_" + k, new_val)
if not new_val:
settings.set(chat_id, "lmode_" + k, "delete")
await q.answer(f"{'تم قفل' if new_val else 'تم فتح'} {LOCKS[k]} {'🔒' if new_val else '🔓'}")
try:
await q.edit_message_reply_markup(reply_markup=panel_kb(chat_id, p))
except Exception:
pass
async def enforce(update, ctx, edited=False):
"""فحص وحذف فوري للمخالفات حسب الرتبة (الأدمنية معفيون دائماً، والمميزون معفيون إلا مع قفل وسائط المميزين)."""
m = update.effective_message
if not m or update.effective_chat.type == "private":
return False
chat = update.effective_chat.id
user = update.effective_user
# قفل الإرسال باسم قناة (sender_chat)
if _on(chat, "ارسال القناة") and getattr(m, "sender_chat", None) and m.sender_chat.id != chat:
try:
await m.delete()
except Exception:
pass
return True
if not user:
return False
lv = await R.effective_level(update)
if lv >= R.level("ادمن"):
return False
# قفل وسائط المميزين
is_media = bool(m.photo or m.video or m.animation or m.sticker or m.document or m.voice or m.video_note or m.audio)
if lv == R.level("مميز"):
if _on(chat, "وسائط المميزين") and is_media:
try:
await m.delete()
except Exception:
pass
return True
return False
# الوضع الليلي
if tg_on(chat, "night"):
try:
await m.delete()
except Exception:
pass
return True
# فحص التوحيد
if settings.get(chat, "unity_on", False):
sym = settings.get(chat, "unity_symbol", "")
full = (user.full_name or "")
if sym and sym not in full:
try:
await m.delete()
if settings.get(chat, "unity_mute", False):
await update.effective_chat.restrict_member(user.id, MUTE_PERMS, until_date=int(time.time()) + 3600)
await ctx.bot.send_message(chat, f"✧︙يا {user.first_name} ضيف رمز التوحيد ({sym}) في اسمك عشان تقدر تتكلم!")
except Exception:
pass
return True
text = (m.text or m.caption or "")
ntext = norm(text)
entities = (m.entities or ()) + (m.caption_entities or ())
why = None
hit_lock = None
blocked = settings.get(chat, "blocked", [])
if blocked and any(w in ntext for w in blocked):
why = "الكلمة الممنوعة"
elif edited and _on(chat, "التعديل"):
why, hit_lock = "تعديل الرسايل", "التعديل"
elif edited and _on(chat, "تعديل الميديا") and is_media:
why, hit_lock = "تعديل الميديا", "تعديل الميديا"
elif _on(chat, "الوسائط") and is_media:
why, hit_lock = "الوسائط", "الوسائط"
elif _on(chat, "الستوري") and getattr(m, "story", None):
why, hit_lock = "توجيه الستوري", "الستوري"
elif _on(chat, "القنوات") and CHANNEL_LINK.search(text):
why, hit_lock = "روابط القنوات", "القنوات"
elif _on(chat, "الروابط") and (LINK.search(text) or any(e.type in ("url", "text_link") for e in entities)):
why, hit_lock = "الروابط", "الروابط"
elif _on(chat, "الشارحه") and (text.startswith("/") or any(e.type == "bot_command" for e in entities)):
why, hit_lock = "الشارحة والأوامر", "الشارحه"
elif _on(chat, "الماركداون") and any(e.type in ("text_link", "bold", "italic", "code", "pre") for e in entities):
why, hit_lock = "الماركداون", "الماركداون"
elif _on(chat, "التاك") and (MENTION.search(text) or HASHTAG.search(text)):
why, hit_lock = "التاك", "التاك"
elif _on(chat, "المعرفات") and MENTION.search(text):
why, hit_lock = "المعرفات", "المعرفات"
elif _on(chat, "الهاشتاج") and HASHTAG.search(text):
why, hit_lock = "الهاشتاج", "الهاشتاج"
elif _on(chat, "الملصقات") and m.sticker:
why, hit_lock = "الملصقات", "الملصقات"
elif _on(chat, "الصور") and m.photo:
why, hit_lock = "الصور", "الصور"
elif _on(chat, "الفيديو") and m.video:
why, hit_lock = "الفيديو", "الفيديو"
elif _on(chat, "السيلفي") and m.video_note:
why, hit_lock = "السيلفي", "السيلفي"
elif _on(chat, "المتحركه") and m.animation:
why, hit_lock = "المتحركة", "المتحركه"
elif _on(chat, "الصوت") and m.voice:
why, hit_lock = "البصمات", "الصوت"
elif _on(chat, "الاغاني") and m.audio:
why, hit_lock = "الأغاني", "الاغاني"
elif _on(chat, "الملفات") and m.document:
why, hit_lock = "الملفات", "الملفات"
elif _on(chat, "الجهات") and m.contact:
why, hit_lock = "جهات الاتصال", "الجهات"
elif _on(chat, "الموقع") and (m.location or m.venue):
why, hit_lock = "المواقع", "الموقع"
elif _on(chat, "الكيبورد") and m.reply_markup:
why, hit_lock = "الكيبورد", "الكيبورد"
elif _on(chat, "التوجيه") and (m.forward_origin is not None):
why, hit_lock = "التوجيه", "التوجيه"
elif _on(chat, "الانلاين") and getattr(m, "via_bot", None):
why, hit_lock = "رسائل الإنلاين", "الانلاين"
elif _on(chat, "جمثون") and USERBOT_CMD.search(text):
why, hit_lock = "أوامر اليوزربوت", "جمثون"
elif _on(chat, "الفارسيه") and PERSIAN.search(text):
why, hit_lock = "الفارسية", "الفارسيه"
elif _on(chat, "الانجليزيه") and ENGLISH.search(text):
why, hit_lock = "الإنجليزية", "الانجليزيه"
elif _on(chat, "الكلايش") and len(text) > 350:
why, hit_lock = "الكلايش", "الكلايش"
elif _on(chat, "الكفر") and any(w in ntext for w in KUFR_WORDS):
why, hit_lock = "الألفاظ الخارجة", "الكفر"
elif _on(chat, "السب") and any(w in ntext for w in BAD_WORDS):
why, hit_lock = "السب", "السب"
elif _on(chat, "الاباحي") and any(w in text.lower() for w in PORN_HINTS):
why, hit_lock = "المحتوى الإباحي", "الاباحي"
elif _on(chat, "الدردشه") and text:
why, hit_lock = "الدردشة", "الدردشه"
elif _on(chat, "التفليش"):
now = time.time()
rq = _raid[(chat, user.id)]
rq.append(now)
recent = [ts for ts in rq if now - ts < 6]
if len(recent) >= 6:
why, hit_lock = "التفليش والسبام السريع", "التفليش"
elif _on(chat, "التكرار") and text and len(text) > 2:
limit = settings.get(chat, "flood_limit", 3)
q = _flood[(chat, user.id)]
now = time.time()
q.append((ntext, now))
same = [t for t, ts in q if t == ntext and now - ts < 120]
if len(same) >= limit:
why, hit_lock = "التكرار", "التكرار"
if why:
try:
await m.delete()
bump(chat, user.id, "del")
mode = _mode(chat, hit_lock) if hit_lock else "delete"
if mode in ("restrict", "mute"):
await update.effective_chat.restrict_member(
user.id, MUTE_PERMS, until_date=int(time.time()) + 3600
)
await ctx.bot.send_message(chat, S["lock_restricted"].format(what=why))
elif mode == "kick":
await update.effective_chat.ban_member(user.id)
await update.effective_chat.unban_member(user.id)
await ctx.bot.send_message(chat, S["lock_kicked"].format(what=why))
except Exception:
pass
return True
return False
HANDLERS = [CallbackQueryHandler(cb, pattern=r"^lk:")]