File size: 14,293 Bytes
3a3b605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""الخدمات: ايدي، معلوماتي، المجموعه، المطور، السورس، عدادات، الساعه، احسب."""
import random, ast, operator
from datetime import datetime
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler
from core.router import exact, prefix, norm
from core import ranks as R
from core import content
from core.store import settings, stats, bump, get_counter, clear_counter, total_msgs, activity_label
from modules.toggles import tg_on
from strings_ar import S
import config


def _user_id_text(update, ctx, t, rank, msgs, pts, dl, edits, bio):
    tpl = settings.get(update.effective_chat.id, "id_tpl", "")
    if tpl:
        out = tpl
        for k, v in {
            "{الاسم}": t.full_name, "{الايدي}": str(t.id),
            "{المعرف}": ("@" + t.username) if t.username else "لا يوجد",
            "{الرتبه}": rank, "{الرسائل}": str(msgs), "{التفاعل}": activity_label(msgs),
            "{البايو}": bio, "{النقاط}": str(pts), "{السحكات}": str(dl), "{التعديلات}": str(edits),
        }.items():
            out = out.replace(k, v)
        return out
    vals = {"id": t.id, "user": ("@" + t.username) if t.username else "-",
            "rank": rank, "msgs": msgs, "pts": pts, "edits": edits,
            "act": activity_label(msgs), "bio": bio}
    vals["del"] = dl
    return S["id_fmt"].format(**vals)


@exact("ايدي")
async def my_id(update, ctx, arg=""):
    chat = update.effective_chat.id
    if not tg_on(chat, "id"):
        await update.message.reply_text(S["feature_off"])
        return
    m = update.message
    t = m.reply_to_message.from_user if m.reply_to_message else update.effective_user
    rank = R.get_rank(chat, t.id)
    if t.id == config.OWNER_ID and t.id:
        rank = "Dev"
    msgs = get_counter(chat, t.id, "msgs")
    pts = get_counter(chat, t.id, "pts")
    dl = get_counter(chat, t.id, "del")
    edits = get_counter(chat, t.id, "edits")
    try:
        c = await ctx.bot.get_chat(t.id)
        bio = c.bio or "لا يوجد"
    except Exception:
        bio = "لا يوجد"
    text = _user_id_text(update, ctx, t, rank, msgs, pts, dl, edits, bio)
    likes = settings.get(chat, "likes", {}).get(str(t.id), 0)
    kb = InlineKeyboardMarkup([[InlineKeyboardButton(f"👍 {likes}", callback_data=f"like:{t.id}", style="primary")]])
    if tg_on(chat, "idphoto"):
        try:
            ph = await ctx.bot.get_user_profile_photos(t.id, limit=1)
            if ph.total_count:
                await m.reply_photo(ph.photos[0][-1].file_id,
                                    caption=S["id_caption"] + "\n" + text, reply_markup=kb)
                return
        except Exception:
            pass
    await m.reply_text(text, reply_markup=kb)


async def like_cb(update, ctx):
    q = update.callback_query
    uid = q.data.split(":")[1]
    chat = q.message.chat.id
    d = settings.get(chat, "likes", {})
    d[uid] = d.get(uid, 0) + 1
    settings.set(chat, "likes", d)
    await q.answer("❤️")
    try:
        await q.edit_message_reply_markup(InlineKeyboardMarkup(
            [[InlineKeyboardButton(f"👍 {d[uid]}", callback_data=f"like:{uid}", style="primary")]]))
    except Exception:
        pass


@prefix("تعيين الايدي", "تعين الايدي")
async def set_id_tpl(update, ctx, arg):
    if await R.effective_level(update) < R.level("مدير"):
        await update.message.reply_text(S["need_rank"])
        return
    m = update.message
    tpl = arg
    if not tpl and m.reply_to_message:
        tpl = m.reply_to_message.text or ""
    if not tpl:
        await update.message.reply_text(
            "✧︙اكتب: تعيين الايدي + الشكل اللي عايزه\n✧︙الدوال المتاحة:\n"
            "{الاسم} {الايدي} {المعرف} {الرتبه} {الرسائل} {التفاعل} {البايو} {النقاط} {السحكات} {التعديلات}")
        return
    settings.set(update.effective_chat.id, "id_tpl", tpl)
    await update.message.reply_text(S["done"])


@exact("تعيين الايدي", "تعين الايدي")
async def set_id_tpl2(update, ctx, arg=""):
    await set_id_tpl(update, ctx, "")


@exact("مسح الايدي")
async def del_id_tpl(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, "id_tpl", "")
    await update.message.reply_text(S["done"])


@exact("معلوماتي")
async def me(update, ctx, arg=""):
    u = update.effective_user
    chat = update.effective_chat.id
    n = get_counter(chat, u.id, "msgs")
    rank = R.get_rank(chat, u.id)
    if u.id == config.OWNER_ID and u.id:
        rank = "Dev"
    await update.message.reply_text(S["me_fmt"].format(name=u.full_name, id=u.id, rank=rank,
                                                       msgs=n, pts=get_counter(chat, u.id, "pts")))


@exact("البايو", "بايو")
async def bio(update, ctx, arg=""):
    t = update.message.reply_to_message.from_user if update.message.reply_to_message else update.effective_user
    try:
        c = await ctx.bot.get_chat(t.id)
        await update.message.reply_text(S["bio_fmt"].format(bio=c.bio or "لا يوجد"))
    except Exception:
        await update.message.reply_text(S["bio_none"])


@exact("افتاري", "صورتي")
async def avatar(update, ctx, arg=""):
    t = update.message.reply_to_message.from_user if update.message.reply_to_message else update.effective_user
    ph = await ctx.bot.get_user_profile_photos(t.id, limit=1)
    if ph.total_count:
        await update.message.reply_photo(ph.photos[0][-1].file_id)


@exact("المجموعه")
async def group_info(update, ctx, arg=""):
    chat = update.effective_chat
    admins = 0
    try:
        admins = len(await chat.get_administrators())
    except Exception:
        pass
    try:
        members = await chat.get_member_count()
    except Exception:
        members = 0
    await update.message.reply_text(S["group_info"].format(
        name=chat.title or "", admins=admins, members=members,
        msgs=total_msgs(chat.id), id=chat.id))


@exact("الاعدادت", "الاعدادات")
async def settings_info(update, ctx, arg=""):
    chat = update.effective_chat.id
    onoff = lambda b: "شغالة ✅" if b else "مقفولة ❌"
    await update.message.reply_text(S["settings_info"].format(
        welcome=onoff(settings.get(chat, "welcome_on", True) and tg_on(chat, "welcome")),
        games=onoff(tg_on(chat, "games")),
        replies=onoff(tg_on(chat, "replies")),
        night=onoff(tg_on(chat, "night")),
        force=settings.get(chat, "force_ch", "") or "مش مفعل"))


@exact("المطور", "مطور")
async def dev(update, ctx, arg=""):
    custom_dev = settings.get("global", "dev_tpl", "")
    if custom_dev:
        await update.message.reply_text(custom_dev)
        return
    if not (config.DEV_NAME or config.DEV_USER):
        await update.message.reply_text(S["dev_none"])
        return
    btns = []
    if config.DEV_USER:
        btns.append([InlineKeyboardButton(config.DEV_NAME or "@" + config.DEV_USER,
                                          url=f"https://t.me/{config.DEV_USER}")])
    await update.message.reply_text(S["dev_info"].format(
        name=config.DEV_NAME or "-", user=("@" + config.DEV_USER) if config.DEV_USER else "-",
        id=config.OWNER_ID or "-"), reply_markup=InlineKeyboardMarkup(btns) if btns else None)


@exact("السورس", "سورس")
async def source(update, ctx, arg=""):
    btns = []
    if config.DEV_USER:
        btns.append([InlineKeyboardButton("• المطور •", url=f"https://t.me/{config.DEV_USER}", style="primary")])
    me = await ctx.bot.get_me()
    btns.append([InlineKeyboardButton("➕ اضفني لمجموعتك", url=f"https://t.me/{me.username}?startgroup=true")])
    await update.message.reply_text(S["source_info"].format(bot=config.BOT_NAME),
                                    reply_markup=InlineKeyboardMarkup(btns))


@exact("المتفاعلين", "التفاعل")
async def top(update, ctx, arg=""):
    d = stats.get(update.effective_chat.id, "msgs", {})
    if not d:
        await update.message.reply_text(S["top_empty"])
        return
    best = sorted(d.items(), key=lambda x: -x[1])[:10]
    lines = [S["top_title"]]
    for i, (u, n) in enumerate(best, 1):
        try:
            m = await update.effective_chat.get_member(int(u))
            nm = m.user.first_name
        except Exception:
            nm = u
        lines.append(f"{i}. {nm} — {n}")
    await update.message.reply_text("\n".join(lines))


def _mk_counter(field, fmt):
    async def h(update, ctx, arg=""):
        n = get_counter(update.effective_chat.id, update.effective_user.id, field)
        await update.message.reply_text(S[fmt].format(n=n))
    return h


def _mk_clear(field):
    async def h(update, ctx, arg=""):
        clear_counter(update.effective_chat.id, update.effective_user.id, field)
        await update.message.reply_text(S["counter_cleared"])
    return h


exact("رسائلي", "رسايلي")(_mk_counter("msgs", "msgs_fmt"))
exact("سحكاتي")(_mk_counter("del", "del_fmt"))
exact("تعديلاتي")(_mk_counter("edits", "edits_fmt"))
exact("مسح رسائلي")(_mk_clear("msgs"))
exact("مسح سحكاتي")(_mk_clear("del"))
exact("مسح تعديلاتي")(_mk_clear("edits"))


@exact("الساعه")
async def clock(update, ctx, arg=""):
    await update.message.reply_text("✧︙الساعه الآن: " + datetime.now().strftime("%I:%M %p"))


@exact("التاريخ")
async def date(update, ctx, arg=""):
    await update.message.reply_text("✧︙تاريخ النهارده: " + datetime.now().strftime("%Y/%m/%d"))


_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
        ast.Div: operator.truediv, ast.Mod: operator.mod, ast.Pow: operator.pow,
        ast.USub: operator.neg, ast.UAdd: operator.pos}


def _safe_eval(node):
    if isinstance(node, ast.Expression):
        return _safe_eval(node.body)
    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
        return node.value
    if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
        return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
    if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
        return _OPS[type(node.op)](_safe_eval(node.operand))
    raise ValueError("bad")


@prefix("احسب")
async def calc(update, ctx, arg):
    try:
        r = _safe_eval(ast.parse(arg, mode="eval"))
        await update.message.reply_text(S["calc_result"].format(r=round(r, 6) if isinstance(r, float) else r))
    except Exception:
        await update.message.reply_text(S["calc_bad"])


# ---------- استفتاء وتصويت (استفتاء تليجرام أصلي) ----------
@prefix("استفتاء سري")
async def secret_poll(update, ctx, arg):
    """استفتاء سري: نفس استفتاء بس التصويت مجهول."""
    parts = [p.strip() for p in (arg or "").split("|")]
    q = parts[0] if parts else ""
    opts = [p for p in parts[1:] if p][:10]
    if "؟" in q:
        head, _, tail = q.partition("؟")
        if tail.strip():
            q = head.strip() + "؟"
            opts = [tail.strip()] + opts
    if not q or len(opts) < 2:
        await update.message.reply_text(S["poll_usage"])
        return
    await update.message.reply_poll(question=q[:300], options=[o[:100] for o in opts],
                                    is_anonymous=True)


@prefix("استفتاء")
async def poll(update, ctx, arg):
    """الصيغة: استفتاء السؤال؟ خيار1|خيار2|خيار3"""
    parts = [p.strip() for p in (arg or "").split("|")]
    q = parts[0] if parts else ""
    opts = [p for p in parts[1:] if p][:10]
    # لو السؤال وأول خيار متلزقين قبل أول | (مثال: نلعب كورة؟ اه) افصلهم عند علامة الاستفهام
    if "؟" in q:
        head, _, tail = q.partition("؟")
        if tail.strip():
            q = head.strip() + "؟"
            opts = [tail.strip()] + opts
    if not q or len(opts) < 2:
        await update.message.reply_text(S["poll_usage"])
        return
    await update.message.reply_poll(question=q[:300], options=[o[:100] for o in opts],
                                    is_anonymous=False)


@prefix("تصويت")
async def vote(update, ctx, arg):
    """تصويت سريع نعم/لا: تصويت السؤال؟"""
    q = arg or (update.message.reply_to_message.text if update.message.reply_to_message else "")
    if not q:
        await update.message.reply_text(S["poll_usage"])
        return
    await update.message.reply_poll(question=q[:300], options=["نعم ✅", "لا ❌"],
                                    is_anonymous=False)


@prefix("اعكس")
async def reverse_text(update, ctx, arg):
    """اعكس + نص ← يكتبه بالمقلوب (هزار)."""
    text = arg or (update.message.reply_to_message.text if update.message.reply_to_message else "")
    if not text:
        await update.message.reply_text("✧︙اكتب: اعكس + النص (أو رد على رسالة)")
        return
    await update.message.reply_text(text[::-1])


@exact("منشن")
async def mention(update, ctx, arg=""):
    t = update.message.reply_to_message.from_user if update.message.reply_to_message else None
    if not t:
        await update.message.reply_text(S["need_reply"])
        return
    await update.message.reply_text("✧︙" + t.mention_html(), parse_mode="HTML")


async def count_msg(update, ctx):
    if update.effective_chat.type == "private" or not update.effective_user:
        return
    bump(update.effective_chat.id, update.effective_user.id, "msgs")


async def count_edit(update, ctx):
    if update.effective_chat and update.effective_chat.type != "private" and update.effective_user:
        bump(update.effective_chat.id, update.effective_user.id, "edits")


HANDLERS = [CallbackQueryHandler(like_cb, pattern=r"^like:")]