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
 
 
 
 
 
 
 
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
"""أوامر الإدارة: رتب، كتم، حظر، طرد، تثبيت، قوائم، اطردني، حظر عام (للمطور)."""
import time
from telegram import ChatPermissions, InlineKeyboardMarkup
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 stats, ranks_db, settings
from modules.toggles import tg_on
from strings_ar import S, RANK_NAMES, FUN_RANKS
import config

FULL = ChatPermissions(can_send_messages=True, can_send_other_messages=True,
                       can_send_polls=True, can_add_web_page_previews=True)
NONE = ChatPermissions(can_send_messages=False)
_votes = {}


def _target(update):
    m = update.message.reply_to_message
    return m.from_user if m else None


async def _need(update, lvl_name):
    lv = await R.effective_level(update)
    if lv < R.level(lvl_name):
        await update.message.reply_text(S["need_rank"])
        return False
    return True


async def _need_target(update):
    t = _target(update)
    if not t:
        await update.message.reply_text(S["need_reply"])
    return t


def _fun_set(chat, uid, rank, on):
    d = ranks_db.get(chat, "f", {})
    if on:
        d[str(uid)] = rank
    else:
        d.pop(str(uid), None)
    ranks_db.set(chat, "f", d)


@prefix("رفع")
async def promote(update, ctx, arg):
    if not tg_on(update.effective_chat.id, "promote"):
        await update.message.reply_text(S["feature_off"])
        return
    if not await _need(update, "مدير"):
        return
    t = await _need_target(update)
    if not t:
        return
    rank = norm(arg.strip())
    if rank in FUN_RANKS:
        _fun_set(update.effective_chat.id, t.id, rank, True)
    elif rank in RANK_NAMES:
        if R.level(rank) >= await R.effective_level(update):
            await update.message.reply_text(S["need_rank"])
            return
        R.set_rank(update.effective_chat.id, t.id, rank)
    else:
        await update.message.reply_text(S["rank_unknown"])
        return
    await update.message.reply_text(S["rank_up"].format(name=t.first_name, rank=rank))


@prefix("تنزيل")
async def demote(update, ctx, arg):
    if not await _need(update, "مدير"):
        return
    t = await _need_target(update)
    if not t:
        return
    rank = norm(arg.strip())
    chat = update.effective_chat.id
    if rank in FUN_RANKS:
        _fun_set(chat, t.id, rank, False)
    elif rank in RANK_NAMES:
        if R.get_rank(chat, t.id) == rank:
            R.set_rank(chat, t.id, "عضو")
    else:
        await update.message.reply_text(S["rank_unknown"])
        return
    await update.message.reply_text(S["rank_down"].format(name=t.first_name, rank=rank))


async def _names(chat, ids):
    out = []
    for i in ids:
        try:
            m = await chat.get_member(i)
            out.append(m.user.first_name)
        except Exception:
            out.append(str(i))
    return out


@exact("الرتب", "قائمه الرتب")
async def ranks_list(update, ctx, arg=""):
    chat = update.effective_chat
    out = [S["ranks_title"]]
    for rk in reversed(RANK_NAMES):
        ids = R.list_rank(chat.id, rk)
        if ids:
            out.append(f"• {rk}: " + "، ".join(await _names(chat, ids)))
    fun = ranks_db.get(chat.id, "f", {})
    if fun:
        out.append("• ألقاب: " + "، ".join(f"{r}" for r in fun.values()))
    await update.message.reply_text("\n".join(out) if len(out) > 1 else S["rank_list_empty"].format(rank="رتب"))


def _mk_rank_list(rank, *cmds):
    async def h(update, ctx, arg=""):
        ids = R.list_rank(update.effective_chat.id, rank)
        if not ids:
            await update.message.reply_text(S["rank_list_empty"].format(rank=rank))
            return
        names = await _names(update.effective_chat, ids)
        await update.message.reply_text(f"✧︙{rank}:\n" + "\n".join("• " + n for n in names))
    for c in cmds:
        exact(c)(h)
    return h


_mk_rank_list("مالك اساسي", "المالكين الاساسين", "المالكين الاساسيين")
_mk_rank_list("مالك", "المالكين")
_mk_rank_list("منشئ", "المنشئين", "المنشئيين")
_mk_rank_list("مدير", "المدراء")
_mk_rank_list("ادمن", "الادمنيه")
_mk_rank_list("مميز", "المميزين")


@exact("المحظورين")
async def banned_list(update, ctx, arg=""):
    d = settings.get(update.effective_chat.id, "banned", {})
    if not d:
        await update.message.reply_text(S["rank_list_empty"].format(rank="محظورين"))
        return
    await update.message.reply_text("✧︙المحظورين:\n" + "\n".join("• " + n for n in d.values()))


@exact("المكتومين")
async def muted_list(update, ctx, arg=""):
    d = settings.get(update.effective_chat.id, "muted", {})
    if not d:
        await update.message.reply_text(S["rank_list_empty"].format(rank="مكتومين"))
        return
    await update.message.reply_text("✧︙المكتومين:\n" + "\n".join("• " + n for n in d.values()))


@exact("رتبتي")
async def my_rank(update, ctx, arg=""):
    u = update.effective_user
    r = R.get_rank(update.effective_chat.id, u.id)
    if u.id == config.OWNER_ID and u.id:
        r = "Dev"
    else:
        lv = await R.effective_level(update)
        r = R.ORDER[lv] if lv else r
    await update.message.reply_text(S["your_rank"].format(rank=r))


@exact("الرتبه")
async def his_rank(update, ctx, arg=""):
    t = _target(update)
    if not t:
        await update.message.reply_text(S["need_reply"])
        return
    await update.message.reply_text(S["rank_is"].format(name=t.first_name, rank=R.get_rank(update.effective_chat.id, t.id)))


@exact("لقبي")
async def my_title(update, ctx, arg=""):
    fun = ranks_db.get(update.effective_chat.id, "f", {}).get(str(update.effective_user.id))
    await update.message.reply_text(S["rank_is"].format(name=update.effective_user.first_name, rank=fun or "مفيش لقب"))


@exact("كشف")
async def kashf(update, ctx, arg=""):
    t = _target(update)
    if not t:
        await update.message.reply_text(S["need_reply"])
        return
    n = stats.get(update.effective_chat.id, "msgs", {}).get(str(t.id), 0)
    await update.message.reply_text(S["kashf_fmt"].format(
        name=t.full_name, id=t.id, user=("@" + t.username) if t.username else "-",
        rank=R.get_rank(update.effective_chat.id, t.id), msgs=n))


def _track(chat, key, uid, name, on):
    d = settings.get(chat, key, {})
    if on:
        d[str(uid)] = name
    else:
        d.pop(str(uid), None)
    settings.set(chat, key, d)


@exact("كتم")
async def mute(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    t = await _need_target(update)
    if t:
        await update.effective_chat.restrict_member(t.id, NONE)
        _track(update.effective_chat.id, "muted", t.id, t.first_name, True)
        await update.message.reply_text(S["muted"].format(name=t.first_name))


@exact("الغاء كتم")
async def unmute(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    t = await _need_target(update)
    if t:
        await update.effective_chat.restrict_member(t.id, FULL)
        _track(update.effective_chat.id, "muted", t.id, t.first_name, False)
        await update.message.reply_text(S["unmuted"].format(name=t.first_name))


@exact("حظر")
async def ban(update, ctx, arg=""):
    if not tg_on(update.effective_chat.id, "kick"):
        await update.message.reply_text(S["feature_off"])
        return
    if not await _need(update, "مدير"):
        return
    t = await _need_target(update)
    if t:
        await update.effective_chat.ban_member(t.id)
        _track(update.effective_chat.id, "banned", t.id, t.first_name, True)
        await update.message.reply_text(S["done"])


@exact("الغاء حظر")
async def unban(update, ctx, arg=""):
    if not await _need(update, "مدير"):
        return
    t = await _need_target(update)
    if t:
        await update.effective_chat.unban_member(t.id, only_if_banned=True)
        _track(update.effective_chat.id, "banned", t.id, t.first_name, False)
        await update.message.reply_text(S["done"])


@exact("طرد")
async def kick(update, ctx, arg=""):
    if not tg_on(update.effective_chat.id, "kick"):
        await update.message.reply_text(S["feature_off"])
        return
    if not await _need(update, "مدير"):
        return
    t = await _need_target(update)
    if t:
        try:
            await update.effective_chat.ban_member(t.id)
            await update.effective_chat.unban_member(t.id)
            await update.message.reply_text(S["kicked"].format(name=t.first_name))
        except Exception:
            await update.message.reply_text(S["need_admin"])


@exact("حظر عام")
async def gban(update, ctx, arg=""):
    if update.effective_user.id != config.OWNER_ID or not config.OWNER_ID:
        await update.message.reply_text(S["need_rank"])
        return
    t = await _need_target(update)
    if not t:
        return
    g = settings.get("global", "gbanned", {})
    g[str(t.id)] = t.first_name
    settings.set("global", "gbanned", g)
    try:
        await update.effective_chat.ban_member(t.id)
    except Exception:
        pass
    await update.message.reply_text(S["global_ban_done"].format(name=t.first_name))


@exact("الغاء حظر عام")
async def ungban(update, ctx, arg=""):
    if update.effective_user.id != config.OWNER_ID or not config.OWNER_ID:
        await update.message.reply_text(S["need_rank"])
        return
    t = await _need_target(update)
    if not t:
        return
    g = settings.get("global", "gbanned", {})
    g.pop(str(t.id), None)
    settings.set("global", "gbanned", g)
    try:
        await update.effective_chat.unban_member(t.id, only_if_banned=True)
    except Exception:
        pass
    await update.message.reply_text(S["done"])


def is_gbanned(user_id):
    return str(user_id) in settings.get("global", "gbanned", {})


@exact("تثبيت")
async def pin(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    m = update.message.reply_to_message
    if m:
        await m.pin()


@exact("الغاء التثبيت", "الغاء تثبيت")
async def unpin(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    m = update.message.reply_to_message
    try:
        if m:
            await m.unpin()
        else:
            await update.effective_chat.unpin_message()
        await update.message.reply_text(S["done"])
    except Exception:
        pass


@exact("مسح")
async def delete(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    m = update.message.reply_to_message
    if m:
        await m.delete()
        await update.message.delete()


@exact("اكتموه")
async def votemute(update, ctx, arg=""):
    t = _target(update)
    if not t:
        await update.message.reply_text(S["need_reply"])
        return
    need = 5
    key = (update.effective_chat.id, t.id)
    v = _votes.setdefault(key, set())
    v.add(update.effective_user.id)
    if len(v) >= need:
        _votes.pop(key, None)
        await update.effective_chat.restrict_member(t.id, NONE, until_date=int(time.time()) + 3600)
        _track(update.effective_chat.id, "muted", t.id, t.first_name, True)
        await update.message.reply_text(S["muted"].format(name=t.first_name) + " (ساعة)")
    else:
        await update.message.reply_text(S["vote_mute"].format(name=t.first_name, need=need, cur=len(v)))


# ---------- اطردني ----------
@exact("اطردني", "احظرني")
async def kickme(update, ctx, arg=""):
    if not tg_on(update.effective_chat.id, "kickme"):
        await update.message.reply_text(S["kickme_off"])
        return
    kb = InlineKeyboardMarkup([[
        btn("نعم اطردني 😂", f"km:yes:{update.effective_user.id}", style="danger"),
        btn("لا غلطة", "km:no", style="success")]])
    await update.message.reply_text(S["kickme_ask"], reply_markup=kb)


async def km_cb(update, ctx):
    q = update.callback_query
    _, action, *rest = q.data.split(":")
    if action == "yes":
        uid = int(rest[0])
        if q.from_user.id != uid:
            await q.answer("الزر ده مش ليك 😅", show_alert=True)
            return
        await q.answer()
        try:
            await q.message.chat.ban_member(uid)
            await q.message.chat.unban_member(uid)
            await q.edit_message_text(S["kickme_done"])
        except Exception:
            await q.edit_message_text("✧︙معرفتش اطردك، لازم أكون أدمن بصلاحية الحظر.")
    else:
        await q.answer()
        await q.edit_message_text(S["kickme_no"])


# ---------- التحذيرات (3 تحذيرات = كتم ساعة) ----------
@exact("تحذير", "انذار")
async def warn(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    t = await _need_target(update)
    if not t:
        return
    chat = update.effective_chat.id
    d = settings.get(chat, "warns", {})
    k = str(t.id)
    d[k] = d.get(k, 0) + 1
    settings.set(chat, "warns", d)
    if d[k] >= 3:
        d[k] = 0
        settings.set(chat, "warns", d)
        try:
            await update.effective_chat.restrict_member(t.id, NONE, until_date=int(time.time()) + 3600)
            _track(chat, "muted", t.id, t.first_name, True)
        except Exception:
            pass
        await update.message.reply_text(S["warn_muted"].format(name=t.first_name))
    else:
        await update.message.reply_text(S["warn_got"].format(name=t.first_name, n=d[k]))


@exact("التحذيرات")
async def warns_show(update, ctx, arg=""):
    t = _target(update) or update.effective_user
    n = settings.get(update.effective_chat.id, "warns", {}).get(str(t.id), 0)
    await update.message.reply_text(S["warn_count"].format(name=t.first_name, n=n))


@exact("مسح التحذيرات")
async def warns_clear(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    t = await _need_target(update)
    if not t:
        return
    d = settings.get(update.effective_chat.id, "warns", {})
    d.pop(str(t.id), None)
    settings.set(update.effective_chat.id, "warns", d)
    await update.message.reply_text(S["warn_cleared"].format(name=t.first_name))


# ---------- إعدادات الجروب (اسم/وصف/صوره) ----------
@prefix("ضع اسم الجروب")
async def set_gtitle(update, ctx, arg):
    if not await _need(update, "ادمن"):
        return
    if not arg:
        await update.message.reply_text(S["gtitle_usage"])
        return
    try:
        await update.effective_chat.set_title(arg[:255])
        await update.message.reply_text(S["done"])
    except Exception:
        await update.message.reply_text(S["need_admin"])


@prefix("ضع وصف الجروب")
async def set_gdesc(update, ctx, arg):
    if not await _need(update, "ادمن"):
        return
    if not arg and update.message.reply_to_message:
        arg = update.message.reply_to_message.text or ""
    if not arg:
        await update.message.reply_text(S["gdesc_usage"])
        return
    try:
        await update.effective_chat.set_description(arg[:255])
        await update.message.reply_text(S["done"])
    except Exception:
        await update.message.reply_text(S["need_admin"])


@prefix("ضع لقب")
async def set_laqab(update, ctx, arg):
    """ضع لقب + النص (بالرد على أدمن) ← لقب الأدمن الرسمي في تليجرام."""
    if not await _need(update, "ادمن"):
        return
    t = await _need_target(update)
    if not t:
        return
    if not arg:
        await update.message.reply_text(S["laqab_usage"])
        return
    try:
        await update.effective_chat.set_administrator_custom_title(t.id, arg[:16])
        await update.message.reply_text(S["done"])
    except Exception:
        await update.message.reply_text(S["laqab_fail"])


@exact("ضع صوره الجروب")
async def set_gphoto(update, ctx, arg=""):
    if not await _need(update, "ادمن"):
        return
    m = update.message.reply_to_message
    if not m or not m.photo:
        await update.message.reply_text(S["gphoto_usage"])
        return
    try:
        await update.effective_chat.set_photo(m.photo[-1].file_id)
        await update.message.reply_text(S["done"])
    except Exception:
        await update.message.reply_text(S["need_admin"])


@exact("غادر")
async def leave_chat(update, ctx, arg=""):
    if not await _need(update, "مالك"):
        return
    await update.message.reply_text(S["left_group"])
    await update.effective_chat.leave()


HANDLERS = [CallbackQueryHandler(km_cb, pattern=r"^km:")]