df / modules /special_replies.py
ABO3MR's picture
Update settings and special replies modules
50bc1db verified
Raw History Blame Contribute Delete
13.9 kB
"""نظام الردود المميزة والمتعددة والعامة (يدعم حتى 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 = []