File size: 25,526 Bytes
3a3b605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50bc1db
3a3b605
50bc1db
 
 
 
 
 
 
 
 
 
3a3b605
50bc1db
3a3b605
 
50bc1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a3b605
 
 
 
 
 
 
 
 
50bc1db
 
 
 
 
 
 
 
3a3b605
50bc1db
 
 
 
 
 
 
 
 
 
 
 
 
3a3b605
 
 
 
50bc1db
3a3b605
 
 
 
 
 
50bc1db
 
3a3b605
 
 
 
 
 
50bc1db
 
 
 
 
 
 
 
3a3b605
50bc1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a3b605
 
 
 
 
 
50bc1db
3a3b605
50bc1db
3a3b605
50bc1db
 
 
3a3b605
 
 
 
 
50bc1db
 
 
 
3a3b605
 
50bc1db
3a3b605
 
 
 
 
 
 
 
 
 
 
50bc1db
 
3a3b605
 
50bc1db
3a3b605
 
50bc1db
 
 
 
 
 
 
 
3a3b605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50bc1db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
"""الترحيب، القوانين، الكيبورد المخصص، الردود، الأوامر البديلة، المنع، الاشتراك الاجباري (اختياري)."""
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:")]