File size: 13,896 Bytes
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
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
"""نظام الردود المميزة والمتعددة والعامة (يدعم حتى 40 رد لكل كلمة: نص، ستيكر، صورة، فيديو، متحركة، بصمة، أغنية، ملف):
- اضف رد / اضف رد [الكلمة] (بالرد على ميديا/ستيكر أو بالخطوات)
- اضف رد عام / اضف رد عام [الكلمة] (لكل الجروبات)
- اضف رد مميز / اضف رد عام مميز
- الردود العامه / الردود المميزه / مسح رد عام / مسح رد مميز
- المتغيرات: #الاسم #يوزره #اليوزر #الرسائل #الايدي #الرتبه #التعديل #النقاط"""
import random
from core.router import exact, prefix, norm
from core import ranks as R
from core.store import settings, get_counter
from modules.toggles import tg_on
from strings_ar import S

MAX_REPLIES_PER_WORD = 40

PROMPT_MEDIA = (
    "- ابعت دلوقتي الرد اللي عايزه (نص، ستيكر، صورة، فيديو، متحركة، بصمة، أغنية، ملف)\n"
    "- تقدر تبعت لحد 40 رد لنفس الكلمة ورا بعض، ولما تخلص اكتب: تم\n"
    "المتغيرات المتاحة في النص:\n"
    "▹ #الاسم · #يوزره · #اليوزر · #الرسائل · #الايدي · #الرتبه · #التعديل · #النقاط"
)

# جلسات الإضافة المعلقة: (chat_id, user_id) -> {step, scope, trigger, raw_trigger}
_PENDING = {}


def _format_vars(text, update):
    if not text:
        return ""
    m = update.message
    u = update.effective_user
    chat_id = update.effective_chat.id
    ru = m.reply_to_message.from_user if (m and m.reply_to_message) else u
    my_user = ("@" + u.username) if u.username else u.first_name
    rep_user = ("@" + ru.username) if (ru and ru.username) else (ru.first_name if ru else my_user)
    rep = {
        "#الاسم": u.full_name or u.first_name,
        "#يوزره": rep_user,
        "#اليوزر": my_user,
        "#الرسائل": str(get_counter(chat_id, u.id, "msgs")),
        "#الايدي": str(u.id),
        "#الرتبه": R.get_custom_rank_label(chat_id, u.id),
        "#التعديل": str(get_counter(chat_id, u.id, "edits")),
        "#النقاط": str(get_counter(chat_id, u.id, "pts")),
    }
    out = text
    for k, v in rep.items():
        out = out.replace(k, v)
    return out


def extract_entry(m):
    """يستخرج عنصر رد (نص أو أي نوع ميديا/ستيكر) من رسالة."""
    if not m:
        return None
    if getattr(m, "photo", None):
        return {"type": "photo", "file_id": m.photo[-1].file_id, "caption": m.caption or ""}
    if getattr(m, "video", None):
        return {"type": "video", "file_id": m.video.file_id, "caption": m.caption or ""}
    if getattr(m, "animation", None):
        return {"type": "animation", "file_id": m.animation.file_id, "caption": m.caption or ""}
    if getattr(m, "voice", None):
        return {"type": "voice", "file_id": m.voice.file_id, "caption": m.caption or ""}
    if getattr(m, "audio", None):
        return {"type": "audio", "file_id": m.audio.file_id, "caption": m.caption or ""}
    if getattr(m, "document", None):
        return {"type": "document", "file_id": m.document.file_id, "caption": m.caption or ""}
    if getattr(m, "sticker", None):
        return {"type": "sticker", "file_id": m.sticker.file_id, "caption": ""}
    if getattr(m, "text", None):
        return {"type": "text", "text": m.text}
    return None


def _as_list(val):
    if isinstance(val, list):
        return val
    if isinstance(val, dict):
        return [val]
    return []


def append_special_entry(scope_chat, trigger_text, entry):
    """يضيف رداً جديداً لقائمة ردود الكلمة بحد أقصى 40 رداً."""
    k = norm(trigger_text)
    d = settings.get(scope_chat, "special_replies", {})
    items = _as_list(d.get(k))
    if len(items) >= MAX_REPLIES_PER_WORD:
        return False, len(items)
    items.append(entry)
    d[k] = items
    settings.set(scope_chat, "special_replies", d)
    return True, len(items)


def start_session(chat_id, user_id, scope="group", trigger_text=None):
    if trigger_text:
        _PENDING[(chat_id, user_id)] = {
            "step": "content",
            "scope": scope,
            "trigger": norm(trigger_text),
            "raw_trigger": trigger_text.strip(),
        }
    else:
        _PENDING[(chat_id, user_id)] = {"step": "trigger", "scope": scope}


@exact("اضف رد مميز")
async def start_special_reply(update, ctx, arg=""):
    if await R.effective_level(update) < R.level("ادمن"):
        await update.message.reply_text(S["need_rank"])
        return
    start_session(update.effective_chat.id, update.effective_user.id, "group")
    await update.message.reply_text("✧︙أرسل الآن الكلمة التي تريد إضافة رد لها (تقدر تضيف لحد 40 رد نص أو ستيكر أو ميديا):")


@exact("اضف رد عام مميز")
async def start_global_special_reply(update, ctx, arg=""):
    if await R.effective_level(update) < R.level("مالك"):
        await update.message.reply_text(S["need_rank"])
        return
    start_session(update.effective_chat.id, update.effective_user.id, "global")
    await update.message.reply_text("✧︙أرسل الآن الكلمة التي تريد إضافة رد عام لها (لكل الجروبات — لحد 40 رد نص أو ستيكر أو ميديا):")


@exact("الردود المميزه")
async def list_special(update, ctx, arg=""):
    d = settings.get(update.effective_chat.id, "special_replies", {})
    if not d:
        await update.message.reply_text("✧︙لا توجد ردود مميزة حالياً — أضف واحداً بأمر: اضف رد")
        return
    lines = ["⌯ ═══ ❨ الردود المميزة ❩ ═══ ⌯"]
    for k, v in list(d.items())[:50]:
        items = _as_list(v)
        lines.append(f"• {k}  ({len(items)} رد)")
    await update.message.reply_text("\n".join(lines))


@exact("الردود العامه")
async def list_global_replies(update, ctx, arg=""):
    g1 = settings.get("global", "greplies", {})
    g2 = settings.get("global", "special_replies", {})
    keys = sorted(set(list(g1.keys()) + list(g2.keys())))
    if not keys:
        await update.message.reply_text("✧︙لا توجد ردود عامة حالياً.")
        return
    lines = ["⌯ ═══ ❨ الردود العامة ❩ ═══ ⌯"]
    for k in keys[:50]:
        c1 = len(g1[k].split("|")) if k in g1 and isinstance(g1[k], str) else (len(g1[k]) if k in g1 and isinstance(g1[k], list) else 0)
        c2 = len(_as_list(g2.get(k)))
        total = c1 + c2
        lines.append(f"• {k}  ({total} رد)")
    await update.message.reply_text("\n".join(lines))


@prefix("مسح رد مميز")
async def del_special(update, ctx, arg):
    if await R.effective_level(update) < R.level("ادمن"):
        await update.message.reply_text(S["need_rank"])
        return
    k = norm(arg.strip())
    d = settings.get(update.effective_chat.id, "special_replies", {})
    if k in d:
        d.pop(k)
        settings.set(update.effective_chat.id, "special_replies", d)
        await update.message.reply_text("✧︙تم مسح الرد المميز ✅")
    else:
        await update.message.reply_text("✧︙لا يوجد رد مميز بهذا الاسم.")


@exact("مسح الردود", "مسح الردود المتعدده")
async def clear_all_replies(update, ctx, arg=""):
    if await R.effective_level(update) < R.level("مدير"):
        await update.message.reply_text(S["need_rank"])
        return
    chat = update.effective_chat.id
    settings.set(chat, "replies", {})
    settings.set(chat, "rand_replies", {})
    settings.set(chat, "special_replies", {})
    await update.message.reply_text("✧︙تم مسح جميع ردود المجموعه ✅")


@prefix("اضف رد متعدد")
async def add_multi_reply(update, ctx, arg):
    if await R.effective_level(update) < R.level("مدير"):
        await update.message.reply_text(S["need_rank"])
        return
    if "=" not in arg:
        await update.message.reply_text("✧︙الصيغة: اضف رد متعدد الكلمة=رد1|رد2|رد3")
        return
    k, v = arg.split("=", 1)
    choices = [x.strip() for x in v.split("|") if x.strip()][:MAX_REPLIES_PER_WORD]
    if not choices:
        await update.message.reply_text("✧︙اكتب ردود مفصولة بـ |")
        return
    d = settings.get(update.effective_chat.id, "rand_replies", {})
    cur = list(d.get(norm(k), []))
    for ch in choices:
        if len(cur) < MAX_REPLIES_PER_WORD:
            cur.append(ch)
    d[norm(k)] = cur
    settings.set(update.effective_chat.id, "rand_replies", d)
    await update.message.reply_text(f"✧︙تم حفظ الرد المتعدد لـ ({k.strip()}) — الإجمالي: {len(cur)}/{MAX_REPLIES_PER_WORD} ✅")


@exact("الردود المتعدده")
async def list_multi(update, ctx, arg=""):
    d = settings.get(update.effective_chat.id, "rand_replies", {})
    if not d:
        await update.message.reply_text("✧︙لا توجد ردود متعددة حالياً.")
        return
    lines = ["⌯ ═══ ❨ الردود المتعددة ❩ ═══ ⌯"]
    for k, vals in d.items():
        lines.append(f"• {k} ({len(vals)} ردود)")
    await update.message.reply_text("\n".join(lines))


async def handle_pending(update, ctx):
    """يتعامل مع خطوات إضافة الردود (كلمة ثم حتى 40 رد نص أو ستيكر أو ميديا)."""
    m = update.message
    if not m or not update.effective_user:
        return False
    key = (update.effective_chat.id, update.effective_user.id)
    sess = _PENDING.get(key)
    if not sess:
        return False

    txt = (m.text or "").strip()
    if txt in ("الغاء", "إلغاء"):
        _PENDING.pop(key, None)
        await m.reply_text("✧︙تم إلغاء إضافة الرد.")
        return True

    if sess["step"] == "trigger":
        if not m.text:
            await m.reply_text("✧︙أرسل الكلمة كنص:")
            return True
        sess["trigger"] = norm(m.text)
        sess["raw_trigger"] = txt
        sess["step"] = "content"
        await m.reply_text(PROMPT_MEDIA)
        return True

    if sess["step"] == "content":
        if txt in ("تم", "انتهاء", "خلاص", "حفظ"):
            _PENDING.pop(key, None)
            await m.reply_text(f"✧︙تم إنهاء إضافة الردود لكلمة ({sess['raw_trigger']}) ✅")
            return True

        entry = extract_entry(m)
        if not entry:
            await m.reply_text("✧︙نوع غير مدعوم، أرسل نص أو ستيكر أو صورة/فيديو/متحركة/بصمة/أغنية/ملف (أو اكتب تم للإنهاء).")
            return True

        scope_chat = "global" if sess["scope"] == "global" else update.effective_chat.id
        ok, count = append_special_entry(scope_chat, sess["raw_trigger"], entry)
        if not ok:
            _PENDING.pop(key, None)
            await m.reply_text(f"✧︙وصلت للحد الأقصى ({MAX_REPLIES_PER_WORD} رد) لكلمة ({sess['raw_trigger']}) ✅")
            return True

        if count >= MAX_REPLIES_PER_WORD:
            _PENDING.pop(key, None)
            await m.reply_text(f"✧︙تم حفظ الرد رقم {count}/{MAX_REPLIES_PER_WORD} لكلمة ({sess['raw_trigger']}) واكتمل الحد الأقصى ✅")
        else:
            await m.reply_text(
                f"✧︙تم حفظ الرد رقم {count}/{MAX_REPLIES_PER_WORD} لكلمة ({sess['raw_trigger']}) ✅\n"
                f"✧︙ابعت رد تاني (نص أو ستيكر أو ميديا) أو اكتب (تم) للإنهاء."
            )
        return True
    return False


async def try_special_reply(update, ctx):
    """تنفيذ الردود المميزة والمتعددة (الجروب ثم العام) مع اختيار عشوائي حتى 40 رد واستبدال المتغيرات."""
    m = update.message
    if not m or not m.text:
        return False
    chat_id = update.effective_chat.id
    t = norm(m.text)

    entries = []
    if tg_on(chat_id, "replies"):
        entries = _as_list(settings.get(chat_id, "special_replies", {}).get(t))
        if not entries:
            rr = settings.get(chat_id, "rand_replies", {}).get(t)
            if rr:
                entries = [{"type": "text", "text": x} for x in rr]
    if not entries and tg_on(chat_id, "greplies"):
        entries = _as_list(settings.get("global", "special_replies", {}).get(t))
    if not entries:
        return False

    entry = random.choice(entries)
    tp = entry.get("type")
    cap = _format_vars(entry.get("caption", ""), update)
    try:
        if tp == "text":
            await m.reply_text(_format_vars(entry.get("text", ""), update))
        elif tp == "photo":
            await m.reply_photo(entry["file_id"], caption=cap or None)
        elif tp == "video":
            await m.reply_video(entry["file_id"], caption=cap or None)
        elif tp == "animation":
            await m.reply_animation(entry["file_id"], caption=cap or None)
        elif tp == "voice":
            await m.reply_voice(entry["file_id"], caption=cap or None)
        elif tp == "audio":
            await m.reply_audio(entry["file_id"], caption=cap or None)
        elif tp == "document":
            await m.reply_document(entry["file_id"], caption=cap or None)
        elif tp == "sticker":
            await m.reply_sticker(entry["file_id"])
        return True
    except Exception:
        return False


HANDLERS = []