import requests
import time as timer
import sqlite3
import re
import re as regex
import json
import threading
import random
from datetime import datetime
import jdatetime
import pymysql
from config import *
import bot_modules
from bot_modules import *

message_cache = {}
user_name_cache = {}      
conn = pymysql.connect(
    host=DB_HOST,
    user=DB_USER,
    password=DB_PASS,
    database=DB_NAME,
    charset=DB_CHARSET
)
c = conn.cursor()

try:
    c.execute("ALTER TABLE message_log ADD COLUMN sender_guid VARCHAR(64)")
    conn.commit()
except:
    pass
try:
    c.execute("ALTER TABLE user_stats ADD COLUMN medal_score INTEGER DEFAULT 0")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE allowed_groups ADD COLUMN expires_at INTEGER")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE user_stats ADD COLUMN asl TEXT")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE locks ADD COLUMN repetition INTEGER DEFAULT 0")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE user_stats ADD COLUMN lagab TEXT")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE mutes ADD COLUMN until_time INTEGER")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE user_stats ADD COLUMN last_date TEXT")
    conn.commit()
except: pass
try:
    c.execute("ALTER TABLE allowed_groups ADD COLUMN expires_at INTEGER")
    conn.commit()
except:
    pass

c.execute("""CREATE TABLE IF NOT EXISTS groups (
    guid VARCHAR(64) PRIMARY KEY,
    active INTEGER DEFAULT 0,
    owner TEXT,
    admin1 TEXT, admin2 TEXT, admin3 TEXT
)""")
c.execute("CREATE TABLE IF NOT EXISTS bot_state (`key` VARCHAR(64) PRIMARY KEY, value TEXT)")
conn.commit()

def init_group(g):
    c.execute("INSERT IGNORE INTO groups (guid) VALUES (%s)", (g,))
    conn.commit()

def send_banner_to_all_groups():

    banner_info = bot_modules.get_banner(c)
    if not banner_info or banner_info[3] != 1:
        return
    
    c.execute("SELECT value FROM bot_state WHERE `key`='banner_last_sent'")
    row = c.fetchone()
    last_sent = int(row[0]) if row and row[0] else 0
    now = int(timer.time())
    
    source_chat, source_msg_id, interval_hours, _ = banner_info
    interval_seconds = interval_hours * 3600
    if interval_seconds < 60:
        interval_seconds = 60
    
    if now - last_sent < interval_seconds:
        return
    
    c.execute("SELECT guid FROM groups WHERE active=1 AND guid LIKE 'g0%'")
    active_groups = [row[0] for row in c.fetchall()]
    exceptions = bot_modules.get_banner_exceptions(c)
    
    for group in active_groups:
        if group in exceptions:
            continue
        forward_payload = {
            "from_chat_id": source_chat,
            "message_id": source_msg_id,
            "to_chat_id": group
        }
        result = api_call("forwardMessage", forward_payload)
        if result and result.get("status") != "OK" and result.get('status') == 'INVALID_ACCESS':
            c.execute("UPDATE banner SET active = 0 WHERE id = 1")
            conn.commit()
            return
        time.sleep(0.5)
    
    c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", ('banner_last_sent', str(now)))
    conn.commit()


def log_message(message, level="INFO"):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("/home/rezair/public_html/rub/bot_log.txt", "a", encoding="utf-8") as log_file:
        log_file.write(f"[{timestamp}] [{level}] {message}\n")
        
def get_group(g):
    c.execute("SELECT active, owner, admin1, admin2, admin3 FROM groups WHERE guid=%s", (g,))
    row = c.fetchone()
    if row:
        return {"active": row[0], "owner": row[1], "admin1": row[2], "admin2": row[3], "admin3": row[4]}
    return None



def set_group_active(g, active):
    c.execute("UPDATE groups SET active=%s WHERE guid=%s", (active, g))
    conn.commit()

def update_group_field(g, field, value):
    c.execute(f"UPDATE groups SET {field}=%s WHERE guid=%s", (value, g))
    conn.commit()

def is_group_owner(g, u):
    gr = get_group(g)
    return gr and u == gr["owner"]

def is_admin(g, u):
    if u == OWNER_ID:
        return True
    gr = get_group(g)
    if not gr:
        return False
    if u == gr["owner"]:
        return True
    return u in (gr["admin1"], gr["admin2"], gr["admin3"])

def is_simple_admin(g, u):
    if u == OWNER_ID:
        return True
    gr = get_group(g)
    if not gr:
        return False
    if u == gr["owner"]:
        return False
    return u in (gr["admin1"], gr["admin2"], gr["admin3"])

def persian_to_english(s):
    mapping = str.maketrans('۰۱۲۳۴۵۶۷۸۹', '0123456789')
    return s.translate(mapping)

def schedule_auto_delete(chat_id, message_id):
    try:
        c.execute("SELECT auto_delete, auto_delete_time FROM group_settings WHERE group_guid=%s", (chat_id,))
        row = c.fetchone()
        if row and row[0] == 1 and row[1] > 0:
            threading.Timer(row[1], api_call, args=("deleteMessage", {"chat_id": chat_id, "message_id": message_id})).start()
    except Exception:
        pass

def api_call(method, data=None):
    url = BASE_URL + method
    try:
        if data:
            r = requests.post(url, json=data, timeout=15)
        else:
            r = requests.get(url, timeout=15)
        if r.status_code == 200:
            return r.json()
        else:
            log_message(f" API error {method}: {r.status_code}")
    except Exception as e:
        log_message(f" API exception {method}: {e}")
    return None

bot_modules.set_api_call_func(api_call)



def is_bot_command(cmd_text):
    cmd_clean = cmd_text.strip().lower()
    
    for bot_cmd in ALL_BOT_COMMANDS:
        if cmd_clean == bot_cmd.lower():
            return True
        if cmd_clean.startswith(bot_cmd.lower() + " "):
            return True
    
    
    if re.match(r'^\d+\s*(باز|قفل)$', cmd_clean):
        return True
    
    if cmd_clean in ["همه باز", "همه قفل"]:
        return True
    
    return False

def extract_sender(msg):
    if "sender_id" in msg:
        return msg["sender_id"]
    if "from" in msg and isinstance(msg["from"], dict):
        return msg["from"].get("id") or msg["from"].get("user_id")
    if "sender" in msg and isinstance(msg["sender"], dict):
        return msg["sender"].get("id") or msg["sender"].get("user_id")
    ff = msg.get("forwarded_from")
    if ff:
        if "sender_id" in ff:
            return ff["sender_id"]
        if "from" in ff and isinstance(ff["from"], dict):
            return ff["from"].get("id")
    return None
    
def send_formatted_message(chat_id, text, reply_id=None, mentions=None, mono_parts=None, bold_text=None):
    meta_parts = []
    if bold_text:
        idx = text.find(bold_text)
        if idx == -1:
            normalized_text = re.sub(r'\s+', ' ', text).strip()
            normalized_bold = re.sub(r'\s+', ' ', bold_text).strip()
            idx = normalized_text.find(normalized_bold)
            if idx != -1:
                orig_idx = text.find(normalized_text[idx:idx+len(normalized_bold)])
                if orig_idx != -1:
                    idx = orig_idx
                else:
                    idx = text.find(normalized_bold)
        if idx != -1:
            start_utf16 = get_utf16_index(text, idx)
            length_utf16 = get_utf16_length(bold_text)
            meta_parts.append({"type": "Bold", "from_index": start_utf16, "length": length_utf16})
    if mentions:
        for mention in mentions:
            mention_text = mention['mention_text']
            user_guid = mention['user_guid']
            char_idx = text.find(mention_text)
            if char_idx == -1:
                norm_text = re.sub(r'\s+', ' ', text).strip()
                norm_mention = re.sub(r'\s+', ' ', mention_text).strip()
                char_idx = norm_text.find(norm_mention)
                if char_idx != -1:
                    char_idx = text.find(norm_mention)
            if char_idx != -1:
                start_utf16 = get_utf16_index(text, char_idx)
                length_utf16 = get_utf16_length(mention_text)
                meta_parts.append({"type": "MentionText", "from_index": start_utf16, "length": length_utf16, "mention_text_user_id": user_guid})
    if mono_parts:
        for mono in mono_parts:
            mono_text = mono['text']
            char_idx = text.find(mono_text)
            if char_idx != -1:
                start_utf16 = get_utf16_index(text, char_idx)
                length_utf16 = get_utf16_length(mono_text)
                meta_parts.append({"type": "Mono", "from_index": start_utf16, "length": length_utf16})
    payload = {"chat_id": chat_id, "text": text, "metadata": {"meta_data_parts": meta_parts}}
    if reply_id:
        payload["reply_to_message_id"] = reply_id
    result = api_call("sendMessage", payload)
    if result and result.get("status") == "OK":
        msg_id_sent = result.get("data", {}).get("message_id")
        if msg_id_sent:
            schedule_auto_delete(chat_id, msg_id_sent)
            # ذخیره پیام ربات در message_log (فقط در گروه‌های فعال)
            if chat_id.startswith('g0'):
                grp = get_group(chat_id)
                if grp and grp["active"] == 1:
                    try:
                        c.execute("REPLACE INTO message_log (message_id, group_guid, received_at, sender_guid) VALUES (%s, %s, %s, %s)",
                                  (msg_id_sent, chat_id, int(timer.time()), None))
                        conn.commit()
                    except Exception as e:
                        log_message(f"خطا در ذخیره پیام ربات {msg_id_sent} در {chat_id}: {e}")
    return result


def send_short_message(chat_id, text, reply_id=None, mentions=None):
    prefix = "[ ♕/> "
    suffix = " ]"
    final_text = f"{prefix}{text}{suffix}"
    text_start = len(prefix)
    text_length = len(text)
    meta_parts = [{"type": "Underline", "from_index": text_start, "length": text_length}]
    if mentions:
        for mention in mentions:
            mention_text = mention['mention_text']
            user_guid = mention['user_guid']
            char_idx = final_text.find(mention_text)
            if char_idx != -1:
                start_utf16 = get_utf16_index(final_text, char_idx)
                length_utf16 = get_utf16_length(mention_text)
                meta_parts.append({
                    "type": "MentionText",
                    "from_index": start_utf16,
                    "length": length_utf16,
                    "mention_text_user_id": user_guid
                })
    payload = {"chat_id": chat_id, "text": final_text, "metadata": {"meta_data_parts": meta_parts}}
    if reply_id:
        payload["reply_to_message_id"] = reply_id
    result = api_call("sendMessage", payload)
    if result and result.get("status") == "OK":
        msg_id_sent = result.get("data", {}).get("message_id")
        if msg_id_sent:
            schedule_auto_delete(chat_id, msg_id_sent)
            # ذخیره پیام ربات در message_log (فقط در گروه‌های فعال)
            if chat_id.startswith('g0'):
                grp = get_group(chat_id)
                if grp and grp["active"] == 1:
                    try:
                        c.execute("REPLACE INTO message_log (message_id, group_guid, received_at, sender_guid) VALUES (%s, %s, %s, %s)",
                                  (msg_id_sent, chat_id, int(timer.time()), None))
                        conn.commit()
                    except Exception as e:
                        log_message(f"خطا در ذخیره پیام ربات {msg_id_sent} در {chat_id}: {e}")
    return result


def send_normal_message(chat_id, text, reply_id=None, mentions=None):
    final_text = text
    meta_parts = []
    if mentions:
        for mention in mentions:
            mention_text = mention['mention_text']
            user_guid = mention['user_guid']
            char_idx = final_text.find(mention_text)
            if char_idx != -1:
                start_utf16 = get_utf16_index(final_text, char_idx)
                length_utf16 = get_utf16_length(mention_text)
                meta_parts.append({
                    "type": "MentionText",
                    "from_index": start_utf16,
                    "length": length_utf16,
                    "mention_text_user_id": user_guid
                })
    payload = {"chat_id": chat_id, "text": final_text}
    if meta_parts:
        payload["metadata"] = {"meta_data_parts": meta_parts}
    if reply_id:
        payload["reply_to_message_id"] = reply_id
    result = api_call("sendMessage", payload)
    if result and result.get("status") == "OK":
        msg_id_sent = result.get("data", {}).get("message_id")
        if msg_id_sent:
            schedule_auto_delete(chat_id, msg_id_sent)
            # ذخیره پیام ربات در message_log (فقط در گروه‌های فعال)
            if chat_id.startswith('g0'):
                grp = get_group(chat_id)
                if grp and grp["active"] == 1:
                    try:
                        c.execute("REPLACE INTO message_log (message_id, group_guid, received_at, sender_guid) VALUES (%s, %s, %s, %s)",
                                  (msg_id_sent, chat_id, int(timer.time()), None))
                        conn.commit()
                    except Exception as e:
                        log_message(f"خطا در ذخیره پیام ربات {msg_id_sent} در {chat_id}: {e}")
    return result
def get_utf16_index(text, char_index):
    position = 0
    for i, ch in enumerate(text):
        if i == char_index:
            break
        if ord(ch) > 0xFFFF:
            position += 2
        else:
            position += 1
    return position

def get_utf16_length(text):
    length = 0
    for ch in text:
        if ord(ch) > 0xFFFF:
            length += 2
        else:
            length += 1
    return length

def set_chat_keypad(chat_id, keypad):
    payload = {"chat_id": chat_id, "chat_keypad_type": "New", "chat_keypad": keypad}
    return api_call("editChatKeypad", payload)

def remove_chat_keypad(chat_id):
    payload = {"chat_id": chat_id, "chat_keypad_type": "Remove"}
    return api_call("editChatKeypad", payload)

def get_user_info(guid):
    if not guid:
        return guid
    now = timer.time()
    if guid in user_name_cache:
        name, expiry = user_name_cache[guid]
        if now < expiry:
            return name
    try:
        res = api_call("getUserInfo", {"user_guid": guid})
        if res and res.get("status") == "OK":
            data = res.get("data", {})
            first_name = data.get("first_name", "")
            last_name = data.get("last_name", "")
            name = f"{first_name} {last_name}".strip()
            if not name:
                name = data.get("username", guid)
            user_name_cache[guid] = (name, now + CACHE_TTL)
            return name
    except:
        pass
    return "مشاهده"

def get_chat_info(guid):
    if not guid:
        return None
    try:
        res = api_call("getChat", {"chat_id": guid})
        if res and res.get("status") == "OK":
            data = res.get("data", {})
            chat_data = data.get("chat", {})
            name = chat_data.get("title") or chat_data.get("first_name") or chat_data.get("username") or guid
            return name
    except:
        pass
    return guid



def extract_target_from_cache(reply_id, chat_id):
    sender = message_cache.get(reply_id)
    if sender:
        return sender
    c.execute("SELECT sender_guid FROM message_log WHERE message_id=%s AND group_guid=%s", (reply_id, chat_id))
    row = c.fetchone()
    if row and row[0]:
        message_cache[reply_id] = row[0]
        return row[0]
    with open("/home/rezair/public_html/rub/debug_reply.txt", "a") as f:
        f.write(f"reply_id={reply_id} not found in message_log (group={chat_id})\n")
    return None
    
def extract_target(cmd, reply_id, chat_id):
    if reply_id:
        sender = extract_target_from_cache(reply_id, chat_id)
        if sender:
            return sender
    parts = cmd.split()
    for part in parts:
        if part.startswith('u0') and len(part) > 10:
            return part
    return None

def get_groups_chat_keyboard(cursor, page=0, items_per_page=8):
    cursor.execute("SELECT guid, active, owner FROM groups WHERE guid LIKE 'g0%' ORDER BY active DESC, guid")
    all_groups = cursor.fetchall()
    if not all_groups:
        return None, 0, 0, "📭 هیچ گروهی یافت نشد."

    total_pages = (len(all_groups) + items_per_page - 1) // items_per_page
    if page < 0:
        page = 0
    if page >= total_pages:
        page = total_pages - 1 if total_pages > 0 else 0

    start = page * items_per_page
    end = min(start + items_per_page, len(all_groups))
    page_groups = all_groups[start:end]

    rows = []
    for guid, active, owner_guid in page_groups:
        group_name = get_chat_info(guid) or guid
        status_icon = "✅" if active else "❌"
        button_text = f"{status_icon} {group_name}"
        rows.append({"buttons": [{"id": f"group_{guid}", "type": "Simple", "button_text": button_text}]})

    nav_buttons = []
    if page > 0:
        nav_buttons.append({"id": "prev_page", "type": "Simple", "button_text": f"▶️ قبلی (صفحه {page})"})
    if page < total_pages - 1:
        nav_buttons.append({"id": "next_page", "type": "Simple", "button_text": f"بعدی ◀️ (صفحه {page+2})"})
    if nav_buttons:
        rows.append({"buttons": nav_buttons})

    rows.append({"buttons": [{"id": "start_panel", "type": "Simple", "button_text": "⚙️ پنل مدیریت"}]})
    rows.append({"buttons": [{"id": "tabl_pan", "type": "Simple", "button_text": "⚙️ پنل تبلیغات"}]})

    keypad = {"rows": rows, "resize_keyboard": True, "one_time_keyboard": False}
    header = f"📋 لیست گروه‌ها (صفحه {page+1} از {total_pages})"
    return keypad, page, total_pages, header

    
def process_updates(updates):
    global message_cache
    for upd in updates:
        
        upd_type = upd.get("type")
        if upd_type not in ["NewMessage", "UpdatedMessage"]:
            continue
         
        chat_id = upd.get("chat_id")
        if not chat_id:
            continue
        
        if upd_type == "UpdatedMessage":
            msg = upd.get("updated_message", {})
        else:
            msg = upd.get("new_message", {})
        
        msg_id = msg.get("message_id")
        text = msg.get("text", "").strip()
        sender = msg.get("sender_id")
        reply_id = msg.get("reply_to_message_id")

        
        if not sender:
            continue
        is_private = chat_id.startswith("b0")
        

        if not text:
            text = ""
        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"add_group_{chat_id}",))
        add_state = c.fetchone()
        if add_state and add_state[0] == "waiting" and sender == OWNER_ID:
            group_guid = text.strip()
            if group_guid.startswith("g0") and len(group_guid) > 10:
                c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                        (f"add_group_{chat_id}_guid", group_guid))
                c.execute("UPDATE bot_state SET value = 'waiting_days' WHERE `key` = %s", (f"add_group_{chat_id}",))
                conn.commit()
                send_normal_message(chat_id, "📅 لطفاً تعداد روزهایی که گروه باید فعال باشد را وارد کنید (فقط عدد).", msg_id)
            else:
                send_normal_message(chat_id, "GUID نامعتبر. لطفاً یک GUID معتبر با پیشوند g0 وارد کنید.", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"add_group_{chat_id}",))
                conn.commit()
            continue
        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"banner_waiting_{chat_id}",))
        banner_state = c.fetchone()
        if banner_state and banner_state[0] == "waiting_forward" and sender == OWNER_ID:
            forwarded_from = msg.get("forwarded_from")
            if not forwarded_from:
                send_normal_message(chat_id, "❌ لطفاً یک پیام را **فوروارد** کنید (نه کپی کنید).", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"banner_waiting_{chat_id}",))
                conn.commit()
                continue
            
            original_chat_id = forwarded_from.get("from_chat_id") or forwarded_from.get("chat_id")
            original_msg_id = forwarded_from.get("message_id")
            
            if not original_chat_id or not original_msg_id:
                send_normal_message(chat_id, "❌ خطا در دریافت اطلاعات پیام فوروارد شده.\nلطفاً از یک پیام معتبر فوروارد کنید.", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"banner_waiting_{chat_id}",))
                conn.commit()
                continue
            
            c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                    (f"banner_source_chat_{chat_id}", original_chat_id))
            c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                    (f"banner_source_msg_{chat_id}", original_msg_id))
            c.execute("UPDATE bot_state SET value='waiting_interval' WHERE `key`=%s", (f"banner_waiting_{chat_id}",))
            conn.commit()
            
            send_normal_message(chat_id, "✅ پیام بنر با موفقیت دریافت شد.\n⏱ لطفاً **فاصله زمانی** بین هر بار ارسال بنر را به **ساعت** وارد کنید (مثال: 1 , 2 , 0.5).", msg_id)
            continue

        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"banner_waiting_{chat_id}",))
        banner_state = c.fetchone()
        if banner_state and banner_state[0] == "waiting_interval" and sender == OWNER_ID:
        
            interval_str = persian_to_english(text.strip())
            try:
                interval_hours = float(interval_str)
                if interval_hours <= 0:
                    raise ValueError
            except:
                send_normal_message(chat_id, "❌ لطفاً یک عدد مثبت (ساعت) وارد کنید.", msg_id)
                continue
        
            c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"banner_source_chat_{chat_id}",))
            source_chat_row = c.fetchone()
            c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"banner_source_msg_{chat_id}",))
            source_msg_row = c.fetchone()
            if not source_chat_row or not source_msg_row:
                send_normal_message(chat_id, "❌ خطا: اطلاعات بنر یافت نشد. دوباره تلاش کنید.", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key` LIKE %s", (f"banner_waiting_{chat_id}%",))
                conn.commit()
                continue
        
            source_chat = source_chat_row[0]
            source_msg_id = source_msg_row[0]
            bot_modules.set_banner(c, source_chat, source_msg_id, interval_hours)
            conn.commit()
        
            # پاک کردن وضعیت‌های موقت
            c.execute("DELETE FROM bot_state WHERE `key` LIKE %s", (f"banner_waiting_{chat_id}%",))
            c.execute("DELETE FROM bot_state WHERE `key` LIKE %s", (f"banner_source_%",))
            conn.commit()
        
            # دیگر خبری از تایمر نیست. فقط پیام بفرست:
            send_normal_message(chat_id, f"✅ بنر با موفقیت ثبت شد. هر {interval_hours} ساعت یکبار در تمام گروه‌های فعال (به جز استثناها) ارسال خواهد شد.", msg_id)
            continue

        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"exception_waiting_{chat_id}",))
        exc_state = c.fetchone()
        if exc_state and exc_state[0] == "waiting" and sender == OWNER_ID:
            group_guid = text.strip()
            if not group_guid.startswith("g0") or len(group_guid) < 10:
                send_normal_message(chat_id, "❌ GUID گروه نامعتبر. باید با g0 شروع شود.\n(وضعیت انتظار لغو شد)", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"exception_waiting_{chat_id}",))
                conn.commit()
                continue 
            
            bot_modules.add_banner_exception(c, group_guid)
            conn.commit()
            send_normal_message(chat_id, f"✅ گروه {group_guid} به لیست استثناهای بنر اضافه شد.", msg_id)
            c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"exception_waiting_{chat_id}",))
            conn.commit()
            continue

        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"add_group_{chat_id}",))
        add_state = c.fetchone()
        if add_state and add_state[0] == "waiting_days" and sender == OWNER_ID:
            c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"add_group_{chat_id}_guid",))
            row = c.fetchone()
            if not row:
                send_normal_message(chat_id, "خطا: گروه یافت نشد. لطفاً دوباره تلاش کنید.", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key` LIKE %s", (f"add_group_{chat_id}%",))
                conn.commit()
                continue
            group_guid = row[0]
            days_str = persian_to_english(text.strip())
            if not days_str.isdigit():
                send_normal_message(chat_id, "لطفاً یک عدد معتبر وارد کنید.", msg_id)
                continue
            days = int(days_str)
            if days <= 0:
                send_normal_message(chat_id, "تعداد روز باید مثبت باشد.", msg_id)
                continue
            bot_modules.add_allowed_group(c, group_guid, OWNER_ID, days)
            c.execute("INSERT IGNORE INTO groups (guid, active) VALUES (%s, %s)", (group_guid, 0))
            c.execute("UPDATE groups SET active = 0 WHERE guid = %s", (group_guid,))
            conn.commit()
            send_normal_message(chat_id, f"گروه {group_guid} به مدت {days} روز فعال گردید.", msg_id)
            c.execute("DELETE FROM bot_state WHERE `key` LIKE %s", (f"add_group_{chat_id}%",))
            conn.commit()
            continue
        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"remove_group_{chat_id}",))
        remove_state = c.fetchone()
        if remove_state and remove_state[0] == "waiting" and sender == OWNER_ID:
            group_guid = text.strip()
            if group_guid.startswith("g0") and len(group_guid) > 10:
                c.execute("SELECT guid FROM groups WHERE guid=%s", (group_guid,))
                if c.fetchone():
                    bot_modules.delete_group_completely(c, group_guid)
                    conn.commit()
                    send_normal_message(chat_id, f" گروه {group_guid} حذف شد.", msg_id)
                else:
                    send_normal_message(chat_id, f"گروه {group_guid} در دیتابیس یافت نشد.", msg_id)
            else:
                send_normal_message(chat_id, "GUID نامعتبر. لطفاً یک GUID معتبر با پیشوند g0 وارد کنید.", msg_id)
            c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"remove_group_{chat_id}",))
            conn.commit()
            continue
        c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"broadcast_{chat_id}",))
        broadcast_state = c.fetchone()
        if broadcast_state and broadcast_state[0] == "waiting" and sender == OWNER_ID:
            broadcast_text = text.strip()
            if not broadcast_text:
                send_normal_message(chat_id, "متن نمی‌تواند خالی باشد. لطفاً دوباره تلاش کنید.", msg_id)
                c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"broadcast_{chat_id}",))
                conn.commit()
                continue
            
            c.execute("SELECT chat_id FROM bot_chats")
            users = [row[0] for row in c.fetchall()]
            success = 0
            fail = 0
            for user_chat in users:
                try:
                    send_normal_message(user_chat, broadcast_text)
                    success += 1
                except:
                    fail += 1
                timer.sleep(0.3)
            send_normal_message(chat_id, f"ارسال همگانی به پایان رسید.\nموفق: {success}\nناموفق: {fail}", msg_id)
            c.execute("DELETE FROM bot_state WHERE `key`=%s", (f"broadcast_{chat_id}",))
            conn.commit()
            continue
        
        cmd = text[1:] if text.startswith("/") else text
        if cmd.startswith("◀️ قبلی") or cmd.startswith("بعدی ▶️"):
            match = re.search(r'صفحه (\d+)', cmd)
            if match:
                new_page = int(match.group(1)) - 1  
                keypad, current_page, total_pages, header = get_groups_chat_keyboard(c, new_page)
                if keypad:
                    send_normal_message(chat_id, header, msg_id)
                    set_chat_keypad(chat_id, keypad)
                    c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", (f"groups_page_{chat_id}", str(current_page)))
                    conn.commit()
            continue

        if cmd.startswith("✅ ") or cmd.startswith("❌ "):
            group_name_display = cmd[2:].strip()
            c.execute("SELECT guid, active, owner FROM groups WHERE guid LIKE 'g0%'")
            all_groups = c.fetchall()
            target_guid = None
            for guid, active, owner in all_groups:
                name = get_chat_info(guid) or guid
                if name == group_name_display:
                    target_guid = guid
                    break
            if target_guid:
                c.execute("SELECT active, owner, admin1, admin2, admin3 FROM groups WHERE guid=%s", (target_guid,))
                grp = c.fetchone()
                if grp:
                    active, owner, admin1, admin2, admin3 = grp
                    status_text = "فعال" if active else "غیرفعال"
                    group_name = get_chat_info(target_guid) or target_guid
                    c.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (target_guid,))
                    exp_row = c.fetchone()
                    if exp_row and exp_row[0]:
                        remaining = exp_row[0] - int(time.time())
                        if remaining > 0:
                            days = remaining // 86400
                            hours = (remaining % 86400) // 3600
                            expiry_str = f"{days} روز و {hours} ساعت" if days > 0 else f"{hours} ساعت"
                        else:
                            expiry_str = "منقضی شده"
                    else:
                        expiry_str = "نامشخص"
                    
                    owner_display = owner if owner else "ندارد"
                    
                    info_text = f"""━━━━━━━━━━━━━━━━━━━━
📌 اطلاعات گروه
━━━━━━━━━━━━━━━━━━━━
👥 نام: {group_name}
🆔 گوید: {target_guid}
🔰 وضعیت: {status_text}
👑 مالک: {owner_display}
📅 انقضا: {expiry_str}
━━━━━━━━━━━━━━━━━━━━"""
                    
                    mono_parts = [{"text": target_guid}]
                    if owner and owner != "ندارد":
                        mono_parts.append({"text": owner})
                    
                    send_formatted_message(chat_id, info_text, msg_id, mono_parts=mono_parts)
                else:
                    send_normal_message(chat_id, "❌ گروه یافت نشد.", msg_id)
            else:
                send_normal_message(chat_id, "❌ گروه یافت نشد.", msg_id)
            continue

        
        if cmd in ["/start", "start"] and is_private:
            welcome_text = bot_modules.get_welcome_text(c, chat_id, sender, OWNER_ID)
            keypad = bot_modules.get_start_keypad(sender)
            set_chat_keypad(chat_id, keypad)
            send_normal_message(chat_id, welcome_text, msg_id)
            try:
                c.execute("INSERT IGNORE INTO bot_chats (chat_id, user_guid, user_name, start_date) VALUES (%s, %s, %s, %s)",
                        (chat_id, sender, get_user_info(sender), int(timer.time())))
                conn.commit()
            except Exception as e:
                log_message(f"Error saving chat: {e}")
            continue


        if cmd.startswith("rem") and sender == OWNER_ID:
            parts = cmd.split()
            if len(parts) < 2:
                send_normal_message(chat_id, "❌ مثال: rem g0xxxxx", msg_id)
                continue
            group_guid = parts[1]
            if not group_guid.startswith("g0") or len(group_guid) < 10:
                send_normal_message(chat_id, "❌ GUID نامعتبر. باید با g0 شروع شود.", msg_id)
                continue
            bot_modules.remove_banner_exception(c, group_guid)
            conn.commit()
            send_normal_message(chat_id, f"✅ گروه {group_guid} از لیست استثنا حذف شد.", msg_id)
            continue
        if cmd in ["⚙️ راهنما",  "help"] and sender == OWNER_ID:
            help_txt = bot_modules.get_helpp_text()
            send_normal_message(chat_id, help_txt, msg_id)
            continue

        
        if cmd in ["📖 راهنما",  "helpo"] and is_private:
            help_txt = bot_modules.get_help_text()
            send_normal_message(chat_id, help_txt, msg_id)
            continue

        if cmd == "📞 پشتیبانی" and is_private:
            support_text = bot_modules.get_support_text()
            send_normal_message(chat_id, support_text, msg_id)
            continue
        if cmd == "📅 مدت اشتراک" and is_private:
            text = bot_modules.get_user_subscription_info(c, sender)
            send_normal_message(chat_id, text, msg_id)
            continue
        
        if cmd == "📋 گروه‌های فعال" and is_private:
            text = bot_modules.get_user_managed_groups(c, sender)
            send_normal_message(chat_id, text, msg_id)
            continue
        
        
        if cmd == "💰 قیمت اشتراک" and is_private:
            text = bot_modules.get_help_text()
            send_normal_message(chat_id, text, msg_id)
            continue
        
        if cmd in ["🔙 بازگشت", "🏠 بازگشت به صفحه اصلی"]:
            keypad = bot_modules.get_start_keypad(sender)
            set_chat_keypad(chat_id, keypad)
            send_normal_message(chat_id, "🔙 به صفحه اصلی بازگشتید.", msg_id)
            continue
        
        if cmd == "📊 آمار من" and is_private:
            user_name = get_user_info(sender) or sender
            text, mono_parts = bot_modules.get_user_stats(c, sender, chat_id, user_name)
            bold_text = "آمار شما"
            send_formatted_message(chat_id, text, msg_id, mentions=[], mono_parts=mono_parts, bold_text=bold_text)
            continue
        if cmd == "📣 ثبت بنر" and sender == OWNER_ID:
            c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                    (f"banner_waiting_{chat_id}", "waiting_forward"))
            conn.commit()
            send_normal_message(chat_id, "📣 لطفاً پیام مورد نظر برای بنر را **فوروارد** کنید.", msg_id)
            continue

        if cmd == "🚫 مدیریت استثنا" and sender == OWNER_ID:
            c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                    (f"exception_waiting_{chat_id}", "waiting"))
            conn.commit()
            send_normal_message(chat_id, "🚫 لطفاً GUID گروهی که می‌خواهید از دریافت بنر استثنا شود را وارد کنید.\n(برای حذف استثنا: rem گوید)", msg_id)
            continue
        if cmd == "📋 لیست استثنا" and sender == OWNER_ID:
            text, mono_parts = bot_modules.get_banner_exceptions_list(c)
            send_formatted_message(chat_id, text, msg_id, mono_parts=mono_parts)
            continue
        if cmd == "⏹ توقف بنر" and sender == OWNER_ID:
            log_message("🔴 وارد دستور توقف بنر شدیم")
            c.execute("UPDATE banner SET active = 0 WHERE id = 1")
            conn.commit()
            send_normal_message(chat_id, "⏹ بنر متوقف و غیرفعال شد.", msg_id)
            log_message("✅ توقف بنر کامل شد")
            continue
                                        
        if cmd == "🆔 گوید من" and is_private:
            user_name = get_user_info(sender) or sender
            text_msg = f"""━━━━━━━━━━━━━━━
🆔 گوید شما
━━━━━━━━━━━━━━━
👤 کاربر: {user_name}
🆔 گوید: {sender}
━━━━━━━━━━━━━━━
💡 می‌توانید این آیدی را برای تنظیمات مدیریتی کپی کنید."""
            bold_text = "گوید شما"
            mono_parts = [{"text": sender}]
            send_formatted_message(chat_id, text_msg, msg_id, mentions=[], mono_parts=mono_parts, bold_text=bold_text)
            continue
        
        if sender == OWNER_ID:
            if cmd == "➕ افزودن گروه" and sender == OWNER_ID:
                c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                        (f"add_group_{chat_id}", "waiting"))
                conn.commit()
                send_normal_message(chat_id, "➕ لطفاً GUID گروه را وارد کنید (مثال: g0xxxxxx).", msg_id)
                continue

            if cmd == "➖ حذف گروه" and sender == OWNER_ID:
                c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                        (f"remove_group_{chat_id}", "waiting"))
                conn.commit()
                send_normal_message(chat_id, "➖ لطفاً GUID گروه را برای حذف وارد کنید.", msg_id)
                continue

            if cmd == "🔄 حالت ربات" and sender == OWNER_ID:
                current_mode = "اشتراکی" if bot_modules.is_subscription_mode(c) else "دستی"
                new_mode = "subscription" if current_mode == "دستی" else "manual"
                bot_modules.set_bot_mode(c, new_mode)
                
                if new_mode == "subscription":
                    c.execute("SELECT guid FROM groups WHERE active = 1 AND guid LIKE 'g0%'")
                    active_groups = c.fetchall()
                    for (group_guid,) in active_groups:
                        if not bot_modules.is_group_allowed(c, group_guid):
                            set_group_active(group_guid, 0)
                    conn.commit()
                
                mode_name = "اشتراکی" if new_mode == "subscription" else "دستی"
                send_normal_message(chat_id, f"🔄 حالت ربات به {mode_name} تغییر یافت.\n"
                                    f"در حالت اشتراکی، فقط گروه‌های مجاز می‌توانند ربات را فعال کنند.\n"
                                    f"در حالت دستی، هر کاربر با دستور «فعال» می‌تواند ربات را فعال کند.", msg_id)
                continue
            if cmd == "⚙️ پنل مدیریت" and is_private:
                keypad = bot_modules.get_owner_panel_keypad()
                set_chat_keypad(chat_id, keypad)
                send_normal_message(chat_id, "⚙️ از دکمه‌های زیر استفاده کنید:", msg_id)
                continue
            if cmd == "⚙️ پنل تبلیغات" and is_private:
                keypad = bot_modules.get_owner_panelt_keypad()
                set_chat_keypad(chat_id, keypad)
                send_normal_message(chat_id, "⚙️ از دکمه‌های زیر استفاده کنید:", msg_id)
                continue
            
            
            if cmd == "📊 آمار کلی" and is_private:
                stats = bot_modules.get_bot_stats(c)
                send_normal_message(chat_id, stats, msg_id)
                continue
            
            
            if cmd == "📋 لیست گروه‌ها" and is_private:
                page = 0
                c.execute("SELECT value FROM bot_state WHERE `key`=%s", (f"groups_page_{chat_id}",))
                row = c.fetchone()
                if row:
                    page = int(row[0])
                keypad, current_page, total_pages, header = get_groups_chat_keyboard(c, page)
                if keypad is None:
                    send_normal_message(chat_id, header, msg_id)
                else:
                    send_normal_message(chat_id, header, msg_id)
                    set_chat_keypad(chat_id, keypad)   
                    c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", (f"groups_page_{chat_id}", str(current_page)))
                    conn.commit()
                continue

            
            if cmd == "📢 ارسال همگانی" and sender == OWNER_ID:
                c.execute("REPLACE INTO bot_state (`key`, value) VALUES (%s, %s)", 
                          (f"broadcast_{chat_id}", "waiting"))
                conn.commit()
                send_normal_message(chat_id, "📢 لطفاً پیام همگانی خود را وارد کنید (فقط متن).", msg_id)
                continue
            
        if bot_modules.is_muted(c, sender, chat_id):
            api_call("deleteMessage", {"chat_id": chat_id, "message_id": msg_id})
            continue
        if msg_id and sender:
            message_cache[msg_id] = sender
            if len(message_cache) > MAX_CACHE_SIZE:
                oldest_key = next(iter(message_cache))
                del message_cache[oldest_key]

        bot_modules.update_user_message_count(c, sender, chat_id)
        conn.commit()


        grp = None
        if chat_id.startswith('g0'):
            grp = get_group(chat_id)
            if not grp:
                init_group(chat_id)
                grp = get_group(chat_id)
        else:
            grp = {"active": 0, "owner": None, "admin1": None, "admin2": None, "admin3": None}
        
        if grp["active"] == 1 and msg_id and sender:
            try:
                c.execute("REPLACE INTO message_log (message_id, group_guid, received_at, sender_guid) VALUES (%s, %s, %s, %s)",
                          (msg_id, chat_id, int(timer.time()), sender))
                conn.commit()
            except Exception as e:
                with open("/home/rezair/public_html/rub/message_log_error.txt", "a", encoding="utf-8") as log_file:
                    log_file.write(f"خطا در ذخیره پیام {msg_id} در گروه {chat_id}: {str(e)}\n")

        c.execute("SELECT auto_delete, auto_delete_time FROM group_settings WHERE group_guid=%s", (chat_id,))
        auto_settings = c.fetchone()
        if auto_settings and auto_settings[0] == 1 and auto_settings[1] > 0:
            if is_bot_command(cmd):
                threading.Timer(auto_settings[1], api_call, args=("deleteMessage", {"chat_id": chat_id, "message_id": msg_id})).start()
        cmd_lower = cmd.lower()

        always = (sender == OWNER_ID) or (cmd_lower in ["فعال", "غیرفعال", "راهنما", "help"])

        if sender == OWNER_ID:
            access_level = 3
        elif is_group_owner(chat_id, sender):
            access_level = 2
        elif is_admin(chat_id, sender):
            access_level = 1
        else:
            access_level = 0

        if access_level == 0:
            lock_type = None
            c.execute("SELECT group_status FROM group_settings WHERE group_guid=%s", (chat_id,))
            gs_row = c.fetchone()
            group_status = gs_row[0] if gs_row and gs_row[0] is not None else 1  

            if group_status == 0 and access_level < 2:  
                api_call("deleteMessage", {"chat_id": chat_id, "message_id": msg_id})
                send_short_message(chat_id, "⚠️ گروه در حالت بسته است. فقط مدیران می‌توانند پیام بفرستند.", msg_id)
                continue

            if LINK_PATTERN.search(text):
                lock_type = 'link'
            
            if not lock_type and msg.get("forwarded_from"):
                lock_type = 'forward'
            
            if not lock_type and upd_type == "UpdatedMessage":
                lock_type = 'edit'
            
            if not lock_type and text.strip().isdigit():
                lock_type = 'number'
            
            if not lock_type:
                meta_parts = msg.get("metadata", {}).get("meta_data_parts", [])
                has_mention = any(part.get("type") == "MentionText" for part in meta_parts)
                if has_mention or re.search(r'@\S+', text):
                    lock_type = 'mention'
                    log_message(f"🔍 منشن تشخیص داده شد (metadata یا text)")
            
            if not lock_type and re.search(r'#\w+', text):
                lock_type = 'hashtag'
            
            if not lock_type:
                if re.search(r'(`[^`]+`)|(```[\s\S]+%s```)', text):
                    lock_type = 'code'
                    log_message(f"🔍 کد تشخیص داده شد: بک‌تیک")
                elif re.search(r'\b(def|function|class|import|include|require|if|else|for|while|return|print|echo|var|let|const|public|private|protected|static|void|int|string|bool|array|object|null|true|false|namespace|use|extends|implements|new|try|catch|finally|throw)\b', text, re.I):
                    lock_type = 'code'
                    log_message(f"🔍 کد تشخیص داده شد: کلمه کلیدی")
                elif re.search(r'[{[()]|\b(if|for|while)\s*\(|->|=>|;\s*$', text, re.M):
                    lock_type = 'code'
                    log_message(f"🔍 کد تشخیص داده شد: ساختار کد")
                elif re.search(r'^\s{4,}', text, re.M):
                    lock_type = 'code'
                    log_message(f"🔍 کد تشخیص داده شد: تورفتگی")
            
            swear_words = [
    "کوسو", "کونی", "کیر",
    "کصکش", "کونکش", "کیرم", "کونده", "کصلیس",
    "پدرسگ", "مادرجنده", "مادرقحبه", "حرومزاده", "ناکس",
    "جاکش", "جنده", "هرزه", "لاتی", "کثافت",
    "کص", "خایمال", "کونی", "کیر تو",
    "تو کیری", "کون", "کون ننه", "کص ننش",
    "سگ‌زاده", "خوک‌زاده",
    "بنگاه", "ممه", "پستون", "سوراخ",
    "چوچوله", 
     "ملعون", "بی‌شرف", "بی‌غیرت",
    "بی‌عفت", "بی‌حیا", "بی‌ناموس", 
    
    "کونپشتی", "آب کیر", "کیرم دهنت", "کونم دهنت", "کیر تو کون"
]
            if not lock_type and any(word in text for word in swear_words):
                lock_type = 'swear'
            
            if not lock_type and msg.get("poll"):
                lock_type = 'poll'
            
            if not lock_type and msg.get("story"):
                lock_type = 'story'
            
            if not lock_type and msg.get("location"):
                lock_type = 'location'
            
            if not lock_type and msg.get("live"):
                lock_type = 'live'
            if not lock_type and text:
                clean_text = text.strip()
                compressed = re.sub(r'\s+', '', clean_text)
                
                if len(compressed) >= 50:
                    if re.search(r'(.)\1{15,}', compressed):
                        lock_type = 'repetition'
                        log_message(f"🔍 کد هنگی تشخیص داده شد: تکرار بیش از 15 بار یک کاراکتر")
                    elif re.search(r'(.{2,6})\1{5,}', compressed):
                        lock_type = 'repetition'
                        log_message(f"🔍 کد هنگی تشخیص داده شد: تکرار الگوی 2-6 کاراکتری")
                    elif re.search(r'(\d+\.)+\d+', compressed) and len(compressed) > 15:
                        lock_type = 'repetition'
                        log_message(f"🔍 کد هنگی تشخیص داده شد: الگوی نقطه‌دار طولانی")
                    elif re.search(r'(\d)\1{9,}', compressed):
                        lock_type = 'repetition'
                        log_message(f"🔍 کد هنگی تشخیص داده شد: اعداد تکراری طولانی")
                    else:
                        chars = list(compressed)
                        if chars:
                            most_freq = max(set(chars), key=chars.count)
                            percent = chars.count(most_freq) / len(chars) * 100
                            if percent > 70:
                                lock_type = 'repetition'
                                log_message(f"🔍 کد هنگی تشخیص داده شد: {percent:.1f}% متن یک کاراکتر است")
            if not lock_type and (msg.get("file") or msg.get("sticker") or msg.get("gif") or text):
                if msg.get("sticker"):
                    lock_type = 'sticker'
                elif msg.get("gif"):
                    lock_type = 'video'
                elif msg.get("file"):
                    file_obj = msg.get("file", {})
                    file_name = file_obj.get("file_name", "")
                    
                    # اولویت اول: تشخیص GIF به عنوان ویدیو
                    if re.search(r'\.(gif)$', file_name, re.I):
                        lock_type = 'video'
                    # بعد تشخیص تصاویر (به جز gif)
                    elif re.search(r'\.(jpg|jpeg|png|bmp|webp)$', file_name, re.I):
                        lock_type = 'photo'
                    elif re.search(r'\.(mp4|mkv|avi|mov|wmv|flv)$', file_name, re.I):
                        lock_type = 'video'
                    elif re.search(r'\.(ogg|m4a)$', file_name, re.I):
                        lock_type = 'voice'
                    elif re.search(r'\.(flac|wav|aac|mp3)$', file_name, re.I):
                        lock_type = 'music'
                    elif re.search(r'\.(zip|rar|7z|tar|gz)$', file_name, re.I):
                        lock_type = 'zip'
                    elif re.search(r'\.(txt|zip|rar|pdf|doc|docx|xls|xlsx|ppt|pptx)$', file_name, re.I):
                        lock_type = 'file'
                    elif "sticker" in file_name.lower():
                        lock_type = 'sticker'
                    else:
                        lock_type = 'file'
                elif text:
                    emoji_found = False
                    for ch in text:
                        code = ord(ch)
                        if (0x1F600 <= code <= 0x1F64F or
                            0x1F300 <= code <= 0x1F5FF or
                            0x1F680 <= code <= 0x1F6FF or
                            0x2600 <= code <= 0x27BF or
                            0xFE0F <= code <= 0xFE0F or
                            0x20E3 <= code <= 0x20E3):
                            emoji_found = True
                            break
                    if emoji_found:
                        lock_type = 'sticker'

            if lock_type:
                log_message(f"🔒 نوع قفل تشخیص داده شده: {lock_type}")
                status = bot_modules.get_lock_status(c, chat_id, lock_type)
                log_message(f"🔒 وضعیت قفل (status) = {status}, باینری: {bin(status)}")
                log_message(f"🔒 ENABLED_FLAG = {bot_modules.ENABLED_FLAG}, فعال%s {(status & bot_modules.ENABLED_FLAG) != 0}")

                if status & bot_modules.ENABLED_FLAG:
                    del_result = api_call("deleteMessage", {"chat_id": chat_id, "message_id": msg_id})
                    log_message(f"🗑️ نتیجه حذف پیام: {del_result}")

                    lock_name = LOCK_NAMES_FA.get(lock_type, lock_type)
                    log_message(f"📛 نام قفل: {lock_name}")

                    user_name = get_user_info(sender)
                    mentions = [{"mention_text": user_name, "user_guid": sender}]

                    if status & 2:
                        c.execute("SELECT default_warning_limit FROM group_settings WHERE group_guid=%s", (chat_id,))
                        row = c.fetchone()
                        limit = row[0] if row and row[0] is not None else 3
                        log_message(f"📊 حد مجاز اخطار: {limit}")

                        c.execute("SELECT warnings FROM user_stats WHERE user_guid=%s AND group_guid=%s", (sender, chat_id))
                        cur_row = c.fetchone()
                        current_warnings = cur_row[0] if cur_row else 0
                        log_message(f"📊 اخطار فعلی کاربر: {current_warnings}")

                        reached_limit = bot_modules.add_warning(c, sender, chat_id, limit)
                        conn.commit()
                        log_message(f"📈 پس از افزایش، reached_limit = {reached_limit}")

                        if not reached_limit:
                            new_count = current_warnings + 1
                            msg_text = f"ارسال {lock_name} ممنوع است!]\n[ ♕/> اخطار شما({new_count}/{limit})است."
                            log_message(f"📤 ارسال پیام هشدار: {msg_text}")
                            result_msg = send_short_message(chat_id, msg_text, reply_id=None, mentions=mentions)
                            log_message(f"📤 نتیجه ارسال پیام: {result_msg}")
                        else:
                            if status & 4:
                                c.execute("SELECT default_mute_time FROM group_settings WHERE group_guid=%s", (chat_id,))
                                row = c.fetchone()
                                mute_sec = row[0] if row and row[0] is not None else 3600
                            
                                if mute_sec >= 3600:
                                    mute_display = f"{mute_sec // 3600} ساعت"
                                elif mute_sec >= 60:
                                    mute_display = f"{mute_sec // 60} دقیقه"
                                else:
                                    mute_display = f"{mute_sec} ثانیه"
                            
                                bot_modules.add_mute(c, sender, chat_id, mute_sec)
                                conn.commit()
                                msg_text_silence = f"[ ♕/>این کاربر {user_name}]\n[ ♕/>مدت سکوت: {mute_display}]\n[ ♕/>دلیل ارسال {lock_name} سکوت شد.]"
                                msg_result = send_formatted_message(chat_id, msg_text_silence, reply_id=None, mentions=mentions)
                                log_message(f"📤 نتیجه ارسال پیام سکوت: {msg_result}")
                            if status & 1:
                                ban_result = bot_modules.add_ban(c, sender, chat_id)
                                conn.commit()
                                if ban_result:
                                    msg_text_ban = f"[ ♕/>این کاربر {user_name}]\n[ ♕/> دلیل ارسال {lock_name} بن شد.]"
                                    msg_result = send_formatted_message(chat_id, msg_text_ban, reply_id=None, mentions=mentions)
                                else:
                                    msg_result = send_short_message(chat_id, f"⚠️ ربات دسترسی کافی برای بن کاربر ندارد! لطفاً ربات را ادمین کنید.", reply_id=None, mentions=mentions)
                                log_message(f"📤 نتیجه ارسال پیام بن: {msg_result}")
                            if not (status & 4) and not (status & 1):
                                msg_result = send_short_message(chat_id, f"ارسال {lock_name} ممنوع است!]\n[ ♕/> اخطار شما({limit}/{limit})پراست.", reply_id=None, mentions=mentions)
                                log_message(f"📤 نتیجه ارسال پیام اخطار نهایی: {msg_result}")

                    elif status & 4:
                        c.execute("SELECT default_mute_time FROM group_settings WHERE group_guid=%s", (chat_id,))
                        row = c.fetchone()
                        mute_sec = row[0] if row and row[0] is not None else 3600
                        bot_modules.add_mute(c, sender, chat_id, mute_sec)
                        conn.commit()
                        msg_result = send_short_message(chat_id, f"🔇 شما به دلیل ارسال {lock_name} سکوت شدید.", reply_id=None, mentions=mentions)
                        log_message(f"📤 نتیجه ارسال پیام سکوت: {msg_result}")

                    elif status & 1:
                        ban_result = bot_modules.add_ban(c, sender, chat_id)
                        if ban_result:
                            msg_result = send_short_message(chat_id, f"🚫 شما به دلیل ارسال {lock_name} بن شدید.", reply_id=None, mentions=mentions)
                        else:
                            msg_result = send_short_message(chat_id, f"⚠️ ربات دسترسی کافی برای بن کاربر ندارد! لطفاً ربات را ادمین کنید.", reply_id=None, mentions=mentions)
                        log_message(f"📤 نتیجه ارسال پیام بن: {msg_result}")

                    else:
                        msg_result = send_short_message(chat_id, f"ارسال {lock_name} ممنوع است.", reply_id=None, mentions=mentions)
                        log_message(f"📤 نتیجه ارسال پیام قفل ساده: {msg_result}")

                    continue  

        if grp["active"] == 0 and not always:
            continue

        if cmd == "فعال" and not is_private:
            if bot_modules.is_subscription_mode(c):
                c.execute("SELECT expires_at FROM allowed_groups WHERE group_guid=%s", (chat_id,))
                row = c.fetchone()
                if not row:
                    error_text = f"""━━━━━━━━━━━━━━━
⚠️ گروه شما مجاز به استفاده از ربات نیست.
━━━━━━━━━━━━━━━
🆔 گوید گروه شما:
{chat_id}

🔰 در حالت اشتراکی، فقط گروه‌هایی که اشتراک معتبر دارند می‌توانند ربات را فعال کنند.

📢 برای دریافت اشتراک و آموزش فعال‌سازی، لطفاً به کانال پشتیبانی مراجعه کنید:
👑 @AmUzeEsh_LeGaNdR
━━━━━━━━━━━━━━━"""
                    send_formatted_message(chat_id, error_text, msg_id, mono_parts=[{"text": chat_id}])
                    continue
                expires_at = row[0]
                if expires_at < int(timer.time()):
                    error_text = f"""━━━━━━━━━━━━━━━
⚠️ اشتراک گروه شما منقضی شده است.
━━━━━━━━━━━━━━━
🆔 گوید گروه:
{chat_id}

📅 تاریخ انقضا: {datetime.fromtimestamp(expires_at).strftime('%Y-%m-%d')}

🔰 برای تمدید اشتراک و آموزش فعال‌سازی، لطفاً به کانال پشتیبانی مراجعه کنید:
👑 @AmUzeEsh_LeGaNdR
━━━━━━━━━━━━━━━"""
                    send_formatted_message(chat_id, error_text, msg_id, mono_parts=[{"text": chat_id}])
                    c.execute("DELETE FROM allowed_groups WHERE group_guid=%s", (chat_id,))
                    conn.commit()
                    continue

            if grp["owner"] is not None:
                if not is_group_owner(chat_id, sender):
                    send_short_message(chat_id, "شما مالک گروه نیستید.", msg_id)
                    continue
                if grp["active"] == 0:
                    set_group_active(chat_id, 1)
                    send_short_message(chat_id, "گروه فعال شد", msg_id)
                continue
            else:
                update_group_field(chat_id, "owner", sender)
                if grp["active"] == 0:
                    set_group_active(chat_id, 1)
                tname = get_user_info(sender)
                mentions = [{"mention_text": "مالک گروه", "user_guid": sender}]
                send_short_message(chat_id, f"شما مالک گروه شدید", msg_id, mentions=mentions)
            continue
        if access_level == 0:
            admin_cmds = ["لیست مقام", "لیست تنظیم", "لیست قفلی", "لیست سکوت","لیست بن" ,"آمار گروه"]
            if any(cmd.startswith(ac) for ac in admin_cmds) or re.match(r'^(\d+)\s*(باز|قفل)$', cmd) or re.match(r'^(بن|اخطار|سکوت)\s*(\d+)', cmd):
                send_normal_message(chat_id, "⚠️ این دستور فقط برای سازنده، مالک یا ادمین است.", msg_id)
                continue

        if cmd == "غیرفعال" and not is_private:
            if is_group_owner(chat_id, sender):
                if grp["active"] == 1:
                    try:
                        c.execute("DELETE FROM locks WHERE group_guid=%s", (chat_id,))
                        c.execute("DELETE FROM group_settings WHERE group_guid=%s", (chat_id,))
                        c.execute("DELETE FROM bans WHERE group_guid=%s", (chat_id,))
                        c.execute("DELETE FROM mutes WHERE group_guid=%s", (chat_id,))
                        c.execute("DELETE FROM user_stats WHERE group_guid=%s", (chat_id,))
                        c.execute("DELETE FROM message_log WHERE group_guid=%s", (chat_id,))
                        c.execute("UPDATE groups SET active=0, owner=NULL, admin1=NULL, admin2=NULL, admin3=NULL WHERE guid=%s", (chat_id,))
                        conn.commit()
                        send_short_message(chat_id, "ربات غیرفعال شد", msg_id)
                    except Exception as e:
                        conn.rollback()
                        send_short_message(chat_id, f"❌ خطا در پاکسازی داده‌ها: {str(e)}", msg_id)
                else:
                    send_short_message(chat_id, "⚠️ ربات از قبل غیرفعال است.", msg_id)

            continue
        cmd_eng = persian_to_english(cmd)
        match_num_cmd = re.match(r'^(\d+)\s*(باز|قفل)$', cmd)
        match_cmd_num = re.match(r'^(بن|اخطار|سکوت)\s+(\d+)\s+(فعال|غیرفعال)$', cmd_eng)
        
        if cmd in ["همه باز", "همه قفل"] and access_level >= 1:
            for i in range(1, len(bot_modules.LOCK_COLUMNS) + 1):
                col = bot_modules.LOCK_COLUMNS[i-1]
                current = bot_modules.get_lock_status(c, chat_id, col)   
                if cmd == "همه باز" and not is_private:
                    new_status = current & ~bot_modules.ENABLED_FLAG
                else:
                    new_status = current | bot_modules.ENABLED_FLAG
                bot_modules.set_lock(c, chat_id, col, new_status)
            conn.commit()
            send_short_message(chat_id, "همه قفل‌ها " + ("باز شدند" if cmd == "همه باز" else "قفل شدند"), msg_id)
            continue

        if (match_num_cmd or match_cmd_num) and access_level < 1:
            send_normal_message(chat_id, "⚠️این دستور سازنده.مالک.ادمین⚠️", msg_id)
            continue

        if match_num_cmd:
            lock_num = int(match_num_cmd.group(1))
            action = match_num_cmd.group(2)
            if lock_num < 1 or lock_num > len(bot_modules.LOCK_COLUMNS):
                send_short_message(chat_id, f"عدد قفل باید بین 1 تا {len(bot_modules.LOCK_COLUMNS)} باشد.", msg_id)
                continue
            col = bot_modules.LOCK_COLUMNS[lock_num - 1]
            current = bot_modules.get_lock_status(c, chat_id, col)
            if action == "باز" and not is_private:
                new_status = current & ~ENABLED_FLAG
            else:
                new_status = current | ENABLED_FLAG
            bot_modules.set_lock(c, chat_id, col, new_status)
            conn.commit()
            lock_name = bot_modules.LOCK_NAMES_PERSIAN[lock_num - 1]
            if (new_status & ENABLED_FLAG) == 0:
                send_short_message(chat_id, f"{lock_name} باز شد.", msg_id)
            else:
                active = []
                if new_status & 1: active.append("بن")
                if new_status & 2: active.append("اخطار")
                if new_status & 4: active.append("سکوت")
                if active:
                    send_short_message(chat_id, f"{lock_name} قفل شد]\n[ ♕/>با مجازات‌: {', '.join(active)}.", msg_id)
                else:
                    send_short_message(chat_id, f"{lock_name} قفل شد (بدون مجازات).", msg_id)
            continue

        elif match_cmd_num:
            action = match_cmd_num.group(1) 
            lock_num = int(match_cmd_num.group(2))
            modifier = match_cmd_num.group(3)  
            
            if lock_num < 1 or lock_num > len(bot_modules.LOCK_COLUMNS):
                send_short_message(chat_id, f"عدد قفل باید بین 1 تا {len(bot_modules.LOCK_COLUMNS)} باشد.", msg_id)
                continue
            
            col = bot_modules.LOCK_COLUMNS[lock_num - 1]
            current = bot_modules.get_lock_status(c, chat_id, col)
            bit = {'بن': 1, 'اخطار': 2, 'سکوت': 4}[action]
            
            if modifier == "غیرفعال" and not is_private:
                new_status = (current & ~bit) | ENABLED_FLAG
            else:  
                new_status = (current | bit) | ENABLED_FLAG
                
                if action == 'بن':
                    new_status = new_status & ~4
                elif action == 'سکوت':
                    new_status = new_status & ~1

            
            bot_modules.set_lock(c, chat_id, col, new_status)
            conn.commit()
            
            lock_name = bot_modules.LOCK_NAMES_PERSIAN[lock_num - 1]
            active = []
            if new_status & 1: active.append("بن")
            if new_status & 2: active.append("اخطار")
            if new_status & 4: active.append("سکوت")
            if active:
                send_short_message(chat_id, f"{lock_name} قفل شد]\n[ ♕/>با مجازات‌: {', '.join(active)}.", msg_id)
            else:
                send_short_message(chat_id, f"{lock_name} قفل شد (بدون مجازات).", msg_id)
            continue

        if access_level >= 3:
            
            if cmd == "تنظیم مالک گروه" and not is_private:
                target = extract_target(cmd, reply_id, chat_id)
                if target and target.startswith(('u0')):
                    removed_roles = []
                    
                    if grp["admin1"] == target:
                        update_group_field(chat_id, "admin1", None)
                        removed_roles.append("ادمین اول")
                    if grp["admin2"] == target:
                        update_group_field(chat_id, "admin2", None)
                        removed_roles.append("ادمین دوم")
                    if grp["admin3"] == target:
                        update_group_field(chat_id, "admin3", None)
                        removed_roles.append("ادمین سوم")
                    
                    update_group_field(chat_id, "owner", target)
                    tname = get_user_info(target)
                    
                    msg_text = f"مالک گروه تنظیم شد"
                    
                    mentions = [{"mention_text": "مالک گروه", "user_guid": target}]
                    send_short_message(chat_id, msg_text, msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                continue
            
            if cmd == "حذف مالک گروه" and not is_private:
                target = extract_target(cmd, reply_id, chat_id)
                if target:
                    if target == OWNER_ID:
                        send_short_message(chat_id, "نمی‌توان مالک ربات را حذف کرد", msg_id)
                    elif target == grp["owner"]:
                        update_group_field(chat_id, "owner", None)
                        tname = get_user_info(target)
                        mentions = [{"mention_text": "مالک گروه", "user_guid": target}]
                        send_short_message(chat_id, f"مالک گروه حذف شد", msg_id, mentions=mentions)
                    else:
                        send_short_message(chat_id, "کاربر مورد نظر مالک گروه نیست", msg_id)
                else:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                continue

        if access_level >= 2:
            
            def check_user_rank(chat_id, target):
                grp = get_group(chat_id)
                ranks = []
                if grp["owner"] == target:
                    ranks.append("مالک گروه")
                if grp["admin1"] == target:
                    ranks.append("ادمین اول")
                if grp["admin2"] == target:
                    ranks.append("ادمین دوم")
                if grp["admin3"] == target:
                    ranks.append("ادمین سوم")
                return ranks
            if cmd.startswith("تنظیم مدال"):
                target = None
                score = None

                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if not target:
                        continue
                    parts = cmd.split()
                    if len(parts) > 2:
                        try:
                            score = int(parts[2])
                        except ValueError:
                            continue
                    else:
                        send_short_message(chat_id, " مثال: تنظیم مدال 10", msg_id)
                        continue
                else:
                    parts = cmd.split(maxsplit=2)
                    if len(parts) < 2:
                        continue
                    try:
                        score = int(parts[1]) if len(parts) == 2 else int(parts[2])
                    except (ValueError, IndexError):
                        send_short_message(chat_id, " لطفاً یک عدد صحیح وارد کنید.", msg_id)
                        continue
                    target = sender  

                if score < 0:
                    send_short_message(chat_id, " مقدار مدال نباید منفی باشد.", msg_id)
                    continue

                final_score = score if score > 0 else None
                bot_modules.set_user_medal(c, target, chat_id, final_score)
                conn.commit()

                if final_score is None:
                    send_short_message(chat_id, f" مدال کاربر حذف شد .", msg_id)
                else:
                    send_short_message(chat_id, f" مدال کاربر تنظیم شد.", msg_id)
                continue
            if cmd == "تنظیم ادمین اول" and not is_private:
                target = extract_target(cmd, reply_id, chat_id)
                if target:
                    current_ranks = check_user_rank(chat_id, target)
                    
                    if "مالک گروه" in current_ranks:
                        send_short_message(chat_id, "کاربر مالک گروه است و نمی‌تواند ادمین شود", msg_id)
                    elif target == OWNER_ID:
                        send_short_message(chat_id, "نمی‌توانید سازنده ربات را ادمین کنید", msg_id)
                    elif "ادمین اول" in current_ranks:
                        send_short_message(chat_id, "کاربر قبلاً ادمین اول است", msg_id)
                    else:
                        removed = []
                        if "ادمین دوم" in current_ranks:
                            update_group_field(chat_id, "admin2", None)
                            removed.append("ادمین دوم")
                        if "ادمین سوم" in current_ranks:
                            update_group_field(chat_id, "admin3", None)
                            removed.append("ادمین سوم")
                        
                        update_group_field(chat_id, "admin1", target)
                        tname = get_user_info(target)
                        
                        msg_text = "ادمین اول تنظیم شد"
                        
                        mentions = [{"mention_text": "ادمین اول", "user_guid": target}]
                        send_short_message(chat_id, msg_text, msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                continue
            
            if cmd == "تنظیم ادمین دوم" and not is_private:
                target = extract_target(cmd, reply_id, chat_id)
                if target:
                    current_ranks = check_user_rank(chat_id, target)
                    
                    if "مالک گروه" in current_ranks:
                        send_short_message(chat_id, "کاربر مالک گروه است و نمی‌تواند ادمین شود", msg_id)
                    elif target == OWNER_ID:
                        send_short_message(chat_id, "نمی‌توانید سازنده ربات را ادمین کنید", msg_id)
                    elif "ادمین دوم" in current_ranks:
                        send_short_message(chat_id, "کاربر قبلاً ادمین دوم است", msg_id)
                    else:
                        removed = []
                        if "ادمین اول" in current_ranks:
                            update_group_field(chat_id, "admin1", None)
                            removed.append("ادمین اول")
                        if "ادمین سوم" in current_ranks:
                            update_group_field(chat_id, "admin3", None)
                            removed.append("ادمین سوم")
                        
                        update_group_field(chat_id, "admin2", target)
                        tname = get_user_info(target)
                        
                        msg_text = "ادمین دوم تنظیم شد"
                        
                        mentions = [{"mention_text": "ادمین دوم", "user_guid": target}]
                        send_short_message(chat_id, msg_text, msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                continue
            
            if cmd == "تنظیم ادمین سوم" and not is_private:
                target = extract_target(cmd, reply_id, chat_id)
                if target:
                    current_ranks = check_user_rank(chat_id, target)
                    
                    if "مالک گروه" in current_ranks:
                        send_short_message(chat_id, "کاربر مالک گروه است و نمی‌تواند ادمین شود", msg_id)
                    elif target == OWNER_ID:
                        send_short_message(chat_id, "نمی‌توانید سازنده ربات را ادمین کنید", msg_id)
                    elif "ادمین سوم" in current_ranks:
                        send_short_message(chat_id, "کاربر قبلاً ادمین سوم است", msg_id)
                    else:
                        removed = []
                        if "ادمین اول" in current_ranks:
                            update_group_field(chat_id, "admin1", None)
                            removed.append("ادمین اول")
                        if "ادمین دوم" in current_ranks:
                            update_group_field(chat_id, "admin2", None)
                            removed.append("ادمین دوم")
                        
                        update_group_field(chat_id, "admin3", target)
                        tname = get_user_info(target)
                        
                        msg_text = "ادمین سوم تنظیم شد"
                        
                        mentions = [{"mention_text": "ادمین سوم", "user_guid": target}]
                        send_short_message(chat_id, msg_text, msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                continue
            
            if cmd == "حذف ادمین اول" and not is_private:
                if grp["admin1"]:
                    tname = get_user_info(grp["admin1"])
                    update_group_field(chat_id, "admin1", None)
                    mentions = [{"mention_text": "ادمین اول", "user_guid": grp["admin1"]}]
                    send_short_message(chat_id, f"ادمین اول حذف شد", msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ادمین اول وجود ندارد", msg_id)
                continue
            
            if cmd == "حذف ادمین دوم" and not is_private:
                if grp["admin2"]:
                    tname = get_user_info(grp["admin2"])
                    update_group_field(chat_id, "admin2", None)
                    mentions = [{"mention_text": "ادمین دوم", "user_guid": grp["admin2"]}]
                    send_short_message(chat_id, f"ادمین دوم حذف شد", msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ادمین دوم وجود ندارد", msg_id)
                continue
            
            if cmd == "حذف ادمین سوم" and not is_private:
                if grp["admin3"]:
                    tname = get_user_info(grp["admin3"])
                    update_group_field(chat_id, "admin3", None)
                    mentions = [{"mention_text": "ادمین سوم", "user_guid": grp["admin3"]}]
                    send_short_message(chat_id, f"ادمین سوم حذف شد", msg_id, mentions=mentions)
                else:
                    send_short_message(chat_id, "ادمین سوم وجود ندارد", msg_id)
                continue
            if cmd == "انتقال مالکیت" and not is_private:
                if access_level < 2:
                    send_short_message(chat_id, "⚠️ فقط مالک گروه می‌تواند مالکیت را انتقال دهد.", msg_id)
                    continue
                
                if not reply_id:
                    send_short_message(chat_id, "❌ لطفاً روی پیام کاربر مورد نظر ریپلای کنید.", msg_id)
                    continue
                
                target = extract_target_from_cache(reply_id, chat_id)  
                
                if not target:
                    send_short_message(chat_id, "❌ کاربر مورد نظر یافت نشد. روی پیام خود کاربر ریپلای کنید.", msg_id)
                    continue
                
                if target == sender:
                    send_short_message(chat_id, "❌ نمی‌توانید مالکیت را به خودتان انتقال دهید.", msg_id)
                    continue
                
                if grp.get("admin1") == target:
                    update_group_field(chat_id, "admin1", None)
                if grp.get("admin2") == target:
                    update_group_field(chat_id, "admin2", None)
                if grp.get("admin3") == target:
                    update_group_field(chat_id, "admin3", None)
                
                update_group_field(chat_id, "owner", target)
                conn.commit()
                
                mentions = [{"mention_text": "مالک جدید", "user_guid": target}]
                send_short_message(chat_id, "مالکیت گروه منتقل شد", msg_id, mentions=mentions)
                
                continue
        if access_level >= 1:
            if cmd == "گروه باز" and access_level >= 1:
                c.execute("""
                    INSERT INTO group_settings (group_guid, group_status)
                    VALUES (%s, 1)
                    ON DUPLICATE KEY UPDATE group_status = 1
                """, (chat_id,))
                conn.commit()
                send_short_message(chat_id, "🔓 گروه باز شد.", msg_id)
                continue
            
            if cmd == "گروه بسته" and access_level >= 1:
                c.execute("""
                    INSERT INTO group_settings (group_guid, group_status)
                    VALUES (%s, 0)
                    ON DUPLICATE KEY UPDATE group_status = 0
                """, (chat_id,))
                conn.commit()
                send_short_message(chat_id, "🔒 گروه بسته شد.", msg_id)
                continue
            if cmd.startswith("بن"):
                target = None
                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                else:
                    for p in cmd.split()[1:]:
                        if p.startswith('u0') and len(p) > 10:
                            target = p
                            break
                if not target:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                    continue
                
                if target == OWNER_ID:
                    send_short_message(chat_id, "نمی‌توانید سازنده ربات را بن کنید.", msg_id)
                    continue
                if is_group_owner(chat_id, target):
                    send_short_message(chat_id, "نمی‌توانید مالک گروه را بن کنید.", msg_id)
                    continue
                if is_admin(chat_id, target):
                    send_short_message(chat_id, "نمی‌توانید ادمین را بن کنید.", msg_id)
                    continue
                
                result = bot_modules.add_ban(c, target, chat_id)
                conn.commit()
                if result:
                    send_short_message(chat_id, "کاربر با موفقیت بن شد.", msg_id)
                else:
                    send_short_message(chat_id, "خطا در بن کردن کاربر. مطمئن شوید ربات ادمین است.", msg_id)
                continue

            if cmd.startswith("آن بن") or cmd.startswith("ان بن"):
                target = None
                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                else:
                    for p in cmd.split()[1:]:
                        if p.startswith('u0') and len(p) > 10:
                            target = p
                            break
                if not target:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                    continue
                
                if not bot_modules.is_banned(c, target, chat_id):
                    send_short_message(chat_id, "این کاربر در لیست بن نیست.", msg_id)
                    continue
                
                result = bot_modules.remove_ban(c, target, chat_id)
                conn.commit()
                if result:
                    send_short_message(chat_id, "آن بن شد.", msg_id)
                else:
                    send_short_message(chat_id, "خطا در رفع بن. مطمئن شوید ربات ادمین است.", msg_id)
                continue

            if cmd == "لیست بن" and not is_private:
                banned_list = bot_modules.get_banned_users(c, chat_id)
                ZWSP = "\u200B"
                text_msg = """━━━━━━━━━━━━━━━
(🚫) -♡- >{{ لیست بن }} <¥>
━━━━━━━━━━━━━━━"""
                mentions = []
                mono_parts = []
                if not banned_list:
                    text_msg += "\n هیچ کاربری در لیست بن نیست."
                else:
                   
                    for i, (user_guid, banned_at) in enumerate(banned_list, 1):
                        user_name = get_user_info(user_guid)
                        if user_name == "مشاهده":
                            user_name = "مشاهده" + (ZWSP * i)
                        if banned_at and isinstance(banned_at, int) and banned_at > 0:
                            try:
                                gregorian_date = datetime.fromtimestamp(banned_at)
                                shamsi_date = jdatetime.date.fromgregorian(date=gregorian_date)
                                time_part = timer.strftime("%H:%M", timer.localtime(banned_at))
                                ban_date = f"{shamsi_date.strftime('%Y/%m/%d')} - {time_part}"
                            except Exception as e:
                                log_message(f"خطا در تبدیل تاریخ بن: {e}")
                                ban_date = "نامشخص"
                        else:
                            ban_date = "نامشخص (قدیمی)"
                        text_msg += f"\n👤کاربر {i}: {user_name}\n🆔 گوید: {user_guid}\n📅 زمان بن: {ban_date}\n━━━━━━━━━━━━━━━"
                        mentions.append({"mention_text": user_name, "user_guid": user_guid})
                        mono_parts.append({"text": user_guid})
                bold_text = "لیست بن"
                send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
                continue
            if cmd.startswith("اخطار"):
                parts = cmd.split()
                if len(parts) < 2:
                    send_short_message(chat_id, "مثال: اخطار 3", msg_id)
                    continue
                num_str = persian_to_english(parts[1])
                if not num_str.isdigit():
                    send_short_message(chat_id, "عدد نامعتبر.", msg_id)
                    continue
                count = int(num_str)
                if count <= 0:
                    send_short_message(chat_id, "عدد باید مثبت باشد.", msg_id)
                    continue
                target = None
                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                else:
                    for p in parts[2:]:
                        if p.startswith('u0') and len(p) > 10:
                            target = p
                            break
                if not target:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                    continue
                for _ in range(count):
                    bot_modules.add_warning(c, target, chat_id, 9999)
                conn.commit()
                c.execute("SELECT warnings FROM user_stats WHERE user_guid=%s AND group_guid=%s", (target, chat_id))
                row = c.fetchone()
                cur = row[0] if row else 0
                send_short_message(chat_id, f"{count} اخطار اضافه شد. (کل: {cur})", msg_id)
                continue

            if cmd.startswith("حذف اخطار"):
                parts = cmd.split()
                if len(parts) < 3:
                    send_short_message(chat_id, "مثال: حذف اخطار 2", msg_id)
                    continue
                num_str = persian_to_english(parts[2])
                if not num_str.isdigit():
                    send_short_message(chat_id, "عدد نامعتبر.", msg_id)
                    continue
                count = int(num_str)
                if count <= 0:
                    send_short_message(chat_id, "عدد باید مثبت باشد.", msg_id)
                    continue
                
                target = None
                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                else:
                    for p in parts[3:]:
                        if p.startswith('u0') and len(p) > 10:
                            target = p
                            break
                if not target:
                    send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                    continue
                
                for _ in range(count):
                    bot_modules.remove_warning(c, target, chat_id)
                conn.commit()
                
                c.execute("SELECT warnings FROM user_stats WHERE user_guid=%s AND group_guid=%s", (target, chat_id))
                row = c.fetchone()
                cur = row[0] if row else 0
                send_short_message(chat_id, f"{count} اخطار کم شد. (کل: {cur})", msg_id)
                continue
            if cmd == "لیست قفلی" and not is_private:
                text_msg = bot_modules.get_list_qofli(c, chat_id)
                bold_text = "لیست قفلی"
                send_formatted_message(chat_id, text_msg, msg_id, bold_text=bold_text)
                continue

            if cmd == "آمار گروه" and not is_private:
                group_name = get_chat_info(chat_id)
                text_msg = bot_modules.get_group_amar(c, chat_id, group_name)
                bold_text = "آمار گروه"
                result = send_formatted_message(chat_id, text_msg, msg_id, bold_text=bold_text)
                continue

            if cmd == "لیست تنظیم" and not is_private:
                try:
                    c.execute("SELECT default_warning_limit, default_mute_time, auto_delete, auto_delete_time FROM group_settings WHERE group_guid=%s", (chat_id,))
                    row = c.fetchone()

                    if row:
                        warning_limit = row[0] if row[0] is not None else 3
                        mute_time = row[1] if row[1] is not None else 3600
                        auto_delete = row[2] if row[2] is not None else 0
                        auto_delete_time = row[3] if row[3] is not None else 0
                    else:
                        warning_limit = 3
                        mute_time = 3600
                        auto_delete = 0
                        auto_delete_time = 0
                        log_message(" رکوردی در group_settings یافت نشد، از مقادیر پیش‌فرض استفاده شد")
                    
                    if mute_time >= 3600:
                        mute_display = f"{mute_time // 3600} ساعت"
                    elif mute_time >= 60:
                        mute_display = f"{mute_time // 60} دقیقه"
                    else:
                        mute_display = f"{mute_time} ثانیه"
                    
                    if auto_delete_time >= 3600:
                        auto_display = f"{auto_delete_time // 3600} ساعت"
                    elif auto_delete_time >= 60:
                        auto_display = f"{auto_delete_time // 60} دقیقه"
                    else:
                        auto_display = f"{auto_delete_time} ثانیه"
                    
                    auto_status = "روشن" if auto_delete == 1 else "خاموش"
                    
                    msg_status = f"""━━━━━━━━━━━━━━━
(⚙) -♡- >{{ لیست تنظیم }} <¥> 
━━━━━━━━━━━━━━━
⚠️ اخطار تنظیم شده: {warning_limit}

🔇 سکوت تنظیم شده: {mute_display}

💯 پاکسازی دستورات: {auto_status}
💯 زمان حذف: {auto_display}
━━━━━━━━━━━━━━━"""
                    
                    msg_help = f"""━━━━━━━━━━━━━━━
(📖)>{{ راهنما لیست تنظیم }} <¥> 
━━━━━━━━━━━━━━━
⚠️ تنظیم اخطار: (عدد)
⚠️ اخطار/حذف اخطار - ریپلای
🔇 تنظیم سکوت: (عدد) ساعت/دقیقه/ثانیه
🔇 سکوت/حذف سکوت
➜  ریپلای یا گوید
💯 پاکسازی دستورات (عدد) دقیقه/ساعت/ثانیه
💯 پاکسازی دستورات روشن/خاموش
━━━━━━━━━━━━━━━"""
                    
                    bold_status = "لیست تنظیم"
                    bold_help = "راهنما لیست تنظیم"
                    
                    res1 = send_formatted_message(chat_id, msg_status, msg_id, bold_text=bold_status)
                    
                    res2 = send_formatted_message(chat_id, msg_help, None, bold_text=bold_help)
                    
                except Exception as e:
                    log_message(f" خطا در لیست تنظیم: {e}")
                    import traceback
                    traceback.print_exc()
                    send_short_message(chat_id, f"خطا: {str(e)}", msg_id)
                continue
            if cmd.startswith("سکوت"):
                target = None
                mute_seconds = None
                time_part = ""

                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if not target:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue
                    parts = cmd.split()
                    if len(parts) > 1:
                        time_part = ' '.join(parts[1:])
                else:
                    parts = cmd.split()
                    for i, p in enumerate(parts[1:], start=1):
                        if p.startswith(('u0')) and len(p) > 10:
                            target = p
                            if len(parts) > i+1:
                                time_part = ' '.join(parts[i+1:])
                            break
                    if not target:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue

                if target == OWNER_ID:
                    target_rank = 3
                elif is_group_owner(chat_id, target):
                    target_rank = 2
                elif is_admin(chat_id, target):
                    target_rank = 1
                else:
                    target_rank = 0

                if access_level <= target_rank:
                    rank_names = {3: "سازنده ربات", 2: "مالک گروه", 1: "ادمین", 0: "کاربر عادی"}
                    actor_rank_name = rank_names.get(access_level, "کاربر")
                    target_rank_name = rank_names.get(target_rank, "کاربر")
                    send_short_message(chat_id, f" شما {actor_rank_name} هستید و نمی‌توانید {target_rank_name} را سکوت کنید.", msg_id)
                    continue

                c.execute("SELECT default_mute_time FROM group_settings WHERE group_guid=%s", (chat_id,))
                row = c.fetchone()
                mute_seconds = row[0] if row and row[0] else 3600  

                if time_part:
                    time_part = persian_to_english(time_part)
                    seconds = bot_modules.parse_time_to_seconds(time_part)
                    if seconds is not None:
                        mute_seconds = seconds
                    else:
                        send_short_message(chat_id, " فرمت زمان نامعتبر. مثال: سکوت 2 دقیقه", msg_id)
                        continue

                bot_modules.add_mute(c, target, chat_id, mute_seconds)
                conn.commit()

                if mute_seconds >= 3600:
                    time_display = f"{mute_seconds // 3600} ساعت"
                elif mute_seconds >= 60:
                    time_display = f"{mute_seconds // 60} دقیقه"
                else:
                    time_display = f"{mute_seconds} ثانیه"
                send_short_message(chat_id, f"به مدت {time_display} سکوت شد", msg_id)
                continue

            if cmd.startswith("حذف سکوت"):
                target = None

                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if not target:
                        send_short_message(chat_id, "کاربر یافت نشد. لطفاً روی پیام کاربر ریپلای کنید.", msg_id)
                        continue
                else:
                    
                    match = re.search(r'\b(u0[a-zA-Z0-9]{20,})\b', cmd)
                    if not match:
                        match = re.search(r'\b(g0[a-zA-Z0-9]{20,})\b', cmd)
                    if match:
                        target = match.group(1)
                    else:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue

                if not bot_modules.is_muted(c, target, chat_id):
                    send_short_message(chat_id, "کاربر در لیست سکوت نیست.", msg_id)
                    continue

                bot_modules.remove_mute(c, target, chat_id)
                conn.commit()
                send_short_message(chat_id, "سکوت کاربر برداشته شد.", msg_id)
                continue
            if cmd.startswith("تنظیم اخطار"):
                match = re.search(r'(\d+)', persian_to_english(cmd))
                if match:
                    try:
                        warning_limit = int(match.group(1))
                        if warning_limit < 0:
                            send_short_message(chat_id, "عدد اخطار باید مثبت باشد", msg_id)
                        else:
                            c.execute("UPDATE group_settings SET default_warning_limit = %s WHERE group_guid = %s", 
                                    (warning_limit, chat_id))
                            if c.rowcount == 0:
                                c.execute("INSERT INTO group_settings (group_guid, default_warning_limit) VALUES (%s, %s)", 
                                        (chat_id, warning_limit))
                            conn.commit()
                            send_short_message(chat_id, f"اخطار حداکثر {warning_limit} تنظیم شد", msg_id)
                    except ValueError:
                        send_short_message(chat_id, "لطفاً یک عدد معتبر وارد کنید", msg_id)
                else:
                    send_short_message(chat_id, "مثال: تنظیم اخطار 5", msg_id)
                continue
            if cmd.startswith("تنظیم سکوت"):
                time_part = cmd[11:].strip()  
                if time_part:
                    time_part = persian_to_english(time_part)
                    seconds = bot_modules.parse_time_to_seconds(time_part)
                    if seconds is not None:
                        c.execute("UPDATE group_settings SET default_mute_time = %s WHERE group_guid = %s", 
                                (seconds, chat_id))
                        if c.rowcount == 0:
                            c.execute("INSERT INTO group_settings (group_guid, default_mute_time) VALUES (%s, %s)", 
                                    (chat_id, seconds))
                        conn.commit()
                        send_short_message(chat_id, f"سکوت تنظیم شد", msg_id)
                    else:
                        send_short_message(chat_id, "فرمت نامعتبر. مثال]\n[ ♕/>تنظیم سکوت 2 دقیقه", msg_id)
                else:
                    send_short_message(chat_id, "مثال: تنظیم سکوت 2 دقیقه", msg_id)
                continue
            if cmd == "ریست اخطار" and not is_private:
                c.execute("UPDATE group_settings SET default_warning_limit = 3 WHERE group_guid=%s", (chat_id,))
                conn.commit()
                send_short_message(chat_id, "اخطار ریست شد", msg_id)
                continue

            if cmd == "ریست سکوت" and not is_private:
                c.execute("UPDATE group_settings SET default_mute_time = 3600 WHERE group_guid=%s", (chat_id,))
                conn.commit()
                send_short_message(chat_id, "سکوت ریست شد", msg_id)
                continue

            if cmd == "پاکسازی دستورات روشن" and not is_private:
                c.execute("""
                    INSERT INTO group_settings (group_guid, auto_delete, auto_delete_time, default_warning_limit, default_mute_time, group_status)
                    VALUES (%s, 1, %s, 3, 3600, 1)
                    ON DUPLICATE KEY UPDATE auto_delete = 1
                """, (chat_id, 0))  
                conn.commit()
                send_short_message(chat_id, "پاکسازی خودکار روشن شد.", msg_id)
                continue

            if cmd == "پاکسازی دستورات خاموش" and not is_private:
                c.execute("""
                    INSERT INTO group_settings (group_guid, auto_delete, auto_delete_time, default_warning_limit, default_mute_time, group_status)
                    VALUES (%s, 0, %s, 3, 3600, 1)
                    ON DUPLICATE KEY UPDATE auto_delete = 0
                """, (chat_id, 0))
                conn.commit()
                send_short_message(chat_id, "پاکسازی خودکار خاموش شد.", msg_id)
                continue

            if cmd.startswith("پاکسازی دستورات"):
                time_str = cmd[15:].strip()
                if time_str:
                    time_str = persian_to_english(time_str)
                    seconds = bot_modules.parse_time_to_seconds(time_str)
                    if seconds:
                        c.execute("UPDATE group_settings SET auto_delete_time = %s WHERE group_guid=%s", (seconds, chat_id))
                        conn.commit()
                        send_short_message(chat_id, f"پاکسازی به {time_str} تنظیم شد.", msg_id)
                else:
                    send_short_message(chat_id, "مثال: پاکسازی دستورات 2 دقیقه", msg_id)
                continue

            if cmd == "ریست اخطار" and not is_private:
                c.execute("UPDATE group_settings SET default_warning_limit = 3 WHERE group_guid=%s", (chat_id,))
                conn.commit()
                send_short_message(chat_id, "اخطار ریست شد", msg_id)
                continue

            if cmd == "ریست سکوت" and not is_private:
                c.execute("UPDATE group_settings SET default_mute_time = 3600 WHERE group_guid=%s", (chat_id,))
                conn.commit()
                send_short_message(chat_id, "سکوت ریست شد", msg_id)
                continue
            if cmd == "گویدم" and not is_private:
                user_name = get_user_info(sender)
                text_msg = f"""━━━━━━━━━━━━━━━
(🌀) -♡- >{{ گویدم }} <¥> 
━━━━━━━━━━━━━━━
👥 اکانت> {user_name}
🆔 گوید اکانت-> {sender}
━━━━━━━━━━━━━━━"""
                bold_text = "گویدم"
                mentions = [{"mention_text": user_name, "user_guid": sender}]
                mono_parts = [{"text": sender}]
                send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
                continue

            if cmd == "گوید" and not is_private:
                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if target:
                        user_name = get_user_info(target)
                        text_msg = f"""━━━━━━━━━━━━━━━
(🌀) -♡- >{{ گوید }} <¥> 
━━━━━━━━━━━━━━━
👥 اکانت> {user_name}
🆔 گوید اکانت-> {target}
━━━━━━━━━━━━━━━"""
                        bold_text = "گوید"
                        mentions = [{"mention_text": user_name, "user_guid": target}]
                        mono_parts = [{"text": target}]
                        send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
                    else:
                        send_short_message(chat_id, "کاربر یافت نشد", msg_id)
                else:
                    send_short_message(chat_id, "ریپلای کنید", msg_id)
                continue
            if cmd == "لیست سکوت" and not is_private:
                current_time = int(timer.time())
                c.execute("SELECT user_guid, until_time FROM mutes WHERE group_guid=%s AND until_time > %s", (chat_id, current_time))
                muted_users = c.fetchall()
                
                ZWSP = "\u200B"
                text_msg = """━━━━━━━━━━━━━━━
(🔇) -♡- >{{ لیست سکوت }} <¥>
━━━━━━━━━━━━━━━"""
                
                mentions = []
                mono_parts = []
                
                if not muted_users:
                    text_msg += "\n هیچ کاربری در لیست سکوت نیست."
                else:
                    for i, (user_guid, until_time) in enumerate(muted_users, 1):
                        user_name = get_user_info(user_guid)
                        if user_name == "مشاهده":
                            user_name = "مشاهده" + (ZWSP * i)  
                        remaining = until_time - current_time
                        if remaining >= 3600:
                            time_display = f"{remaining // 3600} ساعت"
                        elif remaining >= 60:
                            time_display = f"{remaining // 60} دقیقه"
                        else:
                            time_display = f"{remaining} ثانیه"
                        text_msg += f"\n👤اکانت>{i}< {user_name}\n⏱ زمان باقیمانده: {time_display}\nگوید اکانت->{user_guid}\n ━━━━━━━━━━━━━━━"
                        
                        mentions.append({"mention_text": user_name, "user_guid": user_guid})
                        mono_parts.append({"text": user_guid})
                
                bold_text = "لیست سکوت"
                send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
                continue
            if cmd == "گوید گروه" and not is_private:
                group_name = get_chat_info(chat_id)
                text_msg = f"""━━━━━━━━━━━━━━━
(🌀) -♡- >{{ گوید گروه }} <¥> 
━━━━━━━━━━━━━━━
👥 نام گروه> {group_name}
🆔 گوید گروه-> {chat_id}
━━━━━━━━━━━━━━━"""
                bold_text = "گوید گروه "
                mono_parts = [{"text": chat_id}]
                send_formatted_message(chat_id, text_msg, msg_id, mono_parts=mono_parts, bold_text=bold_text)
                continue

            if cmd == "لیست مقام" and not is_private:
                ZWSP = "\u200B"  
                
                owner_guid = grp.get('owner')
                admin1_guid = grp.get('admin1')
                admin2_guid = grp.get('admin2')
                admin3_guid = grp.get('admin3')
                
                main_owner_name = "مشاهده"
                owner_name = "مشاهده" + ZWSP if owner_guid else None
                admin1_name = "مشاهده" + (ZWSP * 2) if admin1_guid else None
                admin2_name = "مشاهده" + (ZWSP * 3) if admin2_guid else None
                admin3_name = "مشاهده" + (ZWSP * 4) if admin3_guid else None
            
                text_msg = """━━━━━━━━━━━━━━━
(⚜) -♡- >{{ لیست مقام }} <¥>
━━━━━━━━━━━━━━━
🔱 سازنده: {main_owner_name}
🆔 گوید اکانت-> {OWNER_ID}
━━━━━━━━━━━━━━━""".format(main_owner_name=main_owner_name, OWNER_ID=OWNER_ID)
                
                if owner_guid:
                    text_msg += """
👑 مالک گروه: {owner_name}
🆔 گوید اکانت-> {owner_guid}
━━━━━━━━━━━━━━━""".format(owner_name=owner_name, owner_guid=owner_guid)
                else:
                    text_msg += """
👑 مالک گروه: ندارد
━━━━━━━━━━━━━━━"""
                
                if admin1_guid:
                    text_msg += """
👥 ادمین اول: {admin1_name}
🆔 گوید اکانت-> {admin1_guid}
━━━━━━━━━━━━━━━""".format(admin1_name=admin1_name, admin1_guid=admin1_guid)
                else:
                    text_msg += """
👥 ادمین اول: ندارد
━━━━━━━━━━━━━━━"""
                
                if admin2_guid:
                    text_msg += """
👥 ادمین دوم: {admin2_name}
🆔 گوید اکانت-> {admin2_guid}
━━━━━━━━━━━━━━━""".format(admin2_name=admin2_name, admin2_guid=admin2_guid)
                else:
                    text_msg += """
👥 ادمین دوم: ندارد
━━━━━━━━━━━━━━━"""
                
                if admin3_guid:
                    text_msg += """
👥 ادمین سوم: {admin3_name}
🆔 گوید اکانت-> {admin3_guid}
━━━━━━━━━━━━━━━""".format(admin3_name=admin3_name, admin3_guid=admin3_guid)
                else:
                    text_msg += """
👥 ادمین سوم: ندارد
━━━━━━━━━━━━━━━"""
            
                bold_text = "لیست مقام"
                mentions = []
                mono_parts = []
                
                # اصلاح این خط: حذف "and not is_private" از داخل دیکشنری
                mentions.append({"mention_text": main_owner_name, "user_guid": OWNER_ID})
                mono_parts.append({"text": OWNER_ID})
                
                if owner_guid:
                    mentions.append({"mention_text": owner_name, "user_guid": owner_guid})
                    mono_parts.append({"text": owner_guid})
                if admin1_guid:
                    mentions.append({"mention_text": admin1_name, "user_guid": admin1_guid})
                    mono_parts.append({"text": admin1_guid})
                if admin2_guid:
                    mentions.append({"mention_text": admin2_name, "user_guid": admin2_guid})
                    mono_parts.append({"text": admin2_guid})
                if admin3_guid:
                    mentions.append({"mention_text": admin3_name, "user_guid": admin3_guid})
                    mono_parts.append({"text": admin3_guid})
            
                send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
                continue
            if cmd.startswith("حذف اصل") and not is_private:
                target = None

                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if not target:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue
                else:
                    
                    match = re.search(r'\b(u0[a-zA-Z0-9]{20,})\b', cmd)
                    if not match:
                        match = re.search(r'\b(g0[a-zA-Z0-9]{20,})\b', cmd)
                    if match:
                        target = match.group(1)
                    else:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue

                bot_modules.set_user_asl(c, target, chat_id, None)
                conn.commit()
                send_short_message(chat_id, f" اصل کاربر حذف شد.", msg_id)
                continue
            if cmd.startswith("تنظیم اصل") and access_level >= 1 and reply_id:
                parts = cmd.split(maxsplit=2)
                if len(parts) < 3:
                    continue
                text = parts[2].strip()
                target = extract_target_from_cache(reply_id, chat_id)
                if not target:
                    send_short_message(chat_id, "کاربر مورد نظر یافت نشد.", msg_id)
                    continue
                bot_modules.set_user_asl(c, target, chat_id, text)
                conn.commit()
                send_short_message(chat_id, f"اصل تنظیم شد.", msg_id)
                continue
            if cmd.startswith("تنظیم لقب") and access_level >= 1 and reply_id:
                parts = cmd.split(maxsplit=2)
                if len(parts) < 3:
                    continue
                text = parts[2].strip()
                target = extract_target_from_cache(reply_id, chat_id)
                if not target:
                    send_short_message(chat_id, "کاربر مورد نظر یافت نشد.", msg_id)
                    continue
                bot_modules.set_user_lagab(c, target, chat_id, text)
                conn.commit()
                send_short_message(chat_id, f"لقب تنظیم شد.", msg_id)
                continue
            

            if cmd.startswith("حذف لقب") and not is_private:
                target = None

                if reply_id:
                    target = extract_target_from_cache(reply_id, chat_id)
                    if not target:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue
                else:
                    
                    match = re.search(r'\b(u0[a-zA-Z0-9]{20,})\b', cmd)
                    if not match:
                        match = re.search(r'\b(g0[a-zA-Z0-9]{20,})\b', cmd)
                    if match:
                        target = match.group(1)
                    else:
                        send_short_message(chat_id, "ریپلای کن یا گوید وارد کن", msg_id)
                        continue

                bot_modules.set_user_lagab(c, target, chat_id, None)
                conn.commit()
                send_short_message(chat_id, f" لقب کاربر حذف شد.", msg_id)
                continue
            if cmd.startswith("حذف") and not is_private:
                parts = cmd.split()
                if len(parts) > 1:
                    parts[1] = persian_to_english(parts[1])
                
                if len(parts) == 1 and reply_id:
                    result = api_call("deleteMessage", {"chat_id": chat_id, "message_id": reply_id})
                    if result and result.get("status") == "OK":
                        send_short_message(chat_id, "پیام حذف شد.", msg_id)
                        c.execute("DELETE FROM message_log WHERE message_id=%s AND group_guid=%s", (reply_id, chat_id))
                        conn.commit()
                    else:
                        send_short_message(chat_id, "پاکسازی حذف نشد.", msg_id)
                    continue
                
                if len(parts) == 2:
                    c.execute("SELECT COUNT(*) FROM message_log WHERE group_guid=%s", (chat_id,))
                    total_count = c.fetchone()[0]
                    
                    if parts[1].isdigit():
                        count = min(int(parts[1]), total_count)
                        if count == 0:
                            send_short_message(chat_id, "پاکسازی هیچ پیامی در دیتابیس وجود ندارد.", msg_id)
                            continue
                    
                        c.execute("SELECT message_id FROM message_log WHERE group_guid=%s ORDER BY received_at DESC LIMIT %s", (chat_id, count))
                        rows = c.fetchall()
                        target_ids = [row[0] for row in rows]
                    
                        # ارسال پیام وضعیت و ذخیره message_id آن
                        status_result = send_normal_message(chat_id, f"🗑️ در حال حذف {len(target_ids)} پیام از {total_count} پیام موجود...", msg_id)
                        status_msg_id = None
                        if status_result and status_result.get("status") == "OK":
                            status_msg_id = status_result.get("data", {}).get("message_id")
                    
                        deleted = 0
                        for mid in target_ids:
                            if api_call("deleteMessage", {"chat_id": chat_id, "message_id": mid}):
                                deleted += 1
                                c.execute("DELETE FROM message_log WHERE message_id=%s AND group_guid=%s", (mid, chat_id))
                            time.sleep(0.2)
                        conn.commit()
                    
                        # حذف پیام وضعیت
                        if status_msg_id:
                            api_call("deleteMessage", {"chat_id": chat_id, "message_id": status_msg_id})
                    
                        send_short_message(chat_id, f"{deleted} از {count} پیام حذف شد. ({total_count - deleted} پیام باقی‌مانده در دیتابیس)", msg_id)
                        continue
                    
                    if parts[1] == "همه":
                        if total_count == 0:
                            send_short_message(chat_id, "پاکسازی هیچ پیامی در دیتابیس وجود ندارد.", msg_id)
                            continue
                    
                        # ارسال پیام وضعیت و گرفتن message_id آن
                        status_result = send_normal_message(chat_id, f"🗑️ در حال حذف {total_count} پیام...", msg_id)
                        status_msg_id = None
                        if status_result and status_result.get("status") == "OK":
                            status_msg_id = status_result.get("data", {}).get("message_id")
                    
                        c.execute("SELECT message_id FROM message_log WHERE group_guid=%s", (chat_id,))
                        all_ids = [row[0] for row in c.fetchall()]
                        deleted = 0
                        for mid in all_ids:
                            if api_call("deleteMessage", {"chat_id": chat_id, "message_id": mid}):
                                deleted += 1
                                c.execute("DELETE FROM message_log WHERE message_id=%s AND group_guid=%s", (mid, chat_id))
                            time.sleep(0.2)
                        conn.commit()
                    
                        # حذف پیام وضعیت
                        if status_msg_id:
                            api_call("deleteMessage", {"chat_id": chat_id, "message_id": status_msg_id})
                    
                        send_short_message(chat_id, f"{deleted} از {total_count} پیام حذف شد.", msg_id)
                        continue
                
                send_short_message(chat_id, "پاکسازی مثال‌های صحیح:\n• حذف (همراه ریپلای)\n• حذف 10\n• حذف همه", msg_id)
                continue
            if cmd.startswith("فونت") and not is_private:
                parts = cmd.split(maxsplit=1)
                if len(parts) < 2:
                    send_short_message(chat_id, "❌ مثال: فونت سلام", msg_id)
                    continue
                text_to_convert = parts[1].strip()
                if not text_to_convert:
                    send_short_message(chat_id, "❌ لطفاً متنی برای تبدیل وارد کنید.", msg_id)
                    continue
            
                font_styles = bot_modules.convert_to_font_styles(text_to_convert)
                if not font_styles:
                    send_short_message(chat_id, "❌ خطا در تبدیل فونت.", msg_id)
                    continue
            
                # ساخت خطوط معمولی
                font_lines = [f"{item['transformed_text']}" for item in font_styles]
            
                final_text = "━━━━━━━━━━━━━━━\n(🔤) -♡- >{{ فونت‌های متن }} <¥>\n━━━━━━━━━━━━━━━\n"
                final_text += " ".join(font_lines)
                final_text += "\n━━━━━━━━━━━━━━━"
            
                # ارسال معمولی (بدون هیچ فرمت مونو)
                send_normal_message(chat_id, final_text, msg_id)
                continue


       



        if cmd == "آمارم" and not is_private:
            user_name = get_user_info(sender)
            user_rank = access_level  
            text_msg = bot_modules.get_user_amar(c, sender, chat_id, user_name, user_rank, is_self=True)
            bold_text = "آمار شما"
            mentions = [{"mention_text": user_name, "user_guid": sender}]
            mono_parts = [{"text": sender}]
            send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
            continue
        if cmd == "آمار" and reply_id and not is_private:
            target = extract_target_from_cache(reply_id, chat_id)
            if not target:
                continue
            
            if target == OWNER_ID:
                target_rank = 3
            elif is_group_owner(chat_id, target):
                target_rank = 2
            elif is_admin(chat_id, target):
                target_rank = 1
            else:
                target_rank = 0
            
            user_name = get_user_info(target)
            text_msg = bot_modules.get_user_amar(c, target, chat_id, user_name, target_rank, is_self=False)
            bold_text = "آمار کاربر"
            mentions = [{"mention_text": user_name, "user_guid": target}]
            mono_parts = [{"text": target}]
            send_formatted_message(chat_id, text_msg, msg_id, mentions=mentions, mono_parts=mono_parts, bold_text=bold_text)
            continue

        if cmd == "تاریخ" and not is_private:
            dt = bot_modules.get_date_time()
            send_normal_message(chat_id, f"[ ♕/> {dt['shamsi']}]\n[ ♕/> \u200F{dt['gregorian']}]", msg_id)
            continue

        if cmd == "تایم" and not is_private:
            dt = bot_modules.get_date_time()
            send_normal_message(chat_id, f"[ ♕/>ساعت:{dt['time_24']}]\n[ ♕/>ساعت:{dt['time_12']}]", msg_id)
            continue
        if cmd == "فال" and not is_private:
            fortunes = ["فال شما عالی است!", "روز خوبی در پیش دارید.", "مراقب تصمیم‌های ناگهانی باشید.", "خوشبختی در انتظار شماست.", "به زودی خبر خوبی می‌شنوید."]
            send_normal_message(chat_id, f"🔮 فال:\n{random.choice(fortunes)}", msg_id)
            continue

        if cmd == "جوک" and not is_private:
            jokes = ["به کی میخندی؟ به خودم!", "چرا نت‌نت‌ها همیشه خوشحالن؟ چون بیکام!", "یک پنگوئن رفت لباس بخره، گفت این چند؟ گفت 200، گفت 200 چیه؟ مدلش؟!"]
            send_normal_message(chat_id, f"😂 جوک:\n{random.choice(jokes)}", msg_id)
            continue

        if cmd == "داستان" and not is_private:
            stories = ["روزی روزگاری رباتی بود که به انسان‌ها کمک می‌کرد...", "مردی به جنگل رفت و با حیوانات دوست شد...", "در شهری دور، بچه‌ای ستاره‌ها را می‌شمرد..."]
            send_normal_message(chat_id, f"📖 داستان کوتاه:\n{random.choice(stories)}", msg_id)
            continue

        if cmd == "چیستان" and not is_private:
            riddles = {"آن چیست که هرچه بیشتر از آن برداری، بزرگتر میشود؟": "گودال", "کدام کلید باز نمی‌شود؟": "کلید برنامه نویسی", "چه چیزی بدون زبان حرف میزند؟": "ایمیل"}
            q = random.choice(list(riddles.keys()))
            send_normal_message(chat_id, f"🧩 چیستان:\n{q}\n\nپاسخ را بفرستید...", msg_id)
            continue

        if cmd in ["جرات",  "جراعت", "جرعت",  "جرأت"] and not is_private:
            dares = ["به یکی از دوستانت زنگ بزن و آواز بخوان!", "یه عکس خنده‌دار از خودت بگیر و برای گروه بفرست!", "سه حقیقت در مورد خودت بگو که هیچکس نمی‌داند."]
            send_normal_message(chat_id, f"🎲 جرأت:\n{random.choice(dares)}", msg_id)
            continue

        if cmd == "حقیقت" and not is_private:
            truths = ["آخرین باری که گریه کردی کی بود؟", "تا حالا عاشق شده‌ای؟", "بدترین کارت در دوران مدرسه؟"]
            send_normal_message(chat_id, f"🤔 حقیقت:\n{random.choice(truths)}", msg_id)
            continue
        if cmd == "لیست سرگرمی" and not is_private:
            text_msg = bot_modules.get_sereshgari_list()
            bold_text = "لیست سرگرمی"
            send_formatted_message(chat_id, text_msg, msg_id, bold_text=bold_text)
            continue
        if cmd == "تاس" and not is_private:
            send_normal_message(chat_id, f"[ ♕/>🎲 نتیجه تاس: {random.randint(1,6)}]", msg_id)
            continue
        if cmd == "سکه" and not is_private:
            send_normal_message(chat_id, f"[ ♕/>🪙 نتیجه سکه: {random.choice(['خط','شیر'])}]", msg_id)
            continue
        if cmd in ["سنگ", "کاغذ", "قیچی"]:
            bot = random.choice(["سنگ","کاغذ","قیچی"])
            win = (cmd=="سنگ" and bot=="قیچی") or (cmd=="کاغذ" and bot=="سنگ") or (cmd=="قیچی" and bot=="کاغذ")
            res = "شما برنده شدید 🏅" if win else ("مساوی" if cmd==bot else "ربات برنده شد")
            send_short_message(chat_id, f"شما: {cmd}\nربات: {bot}\nنتیجه: {res}", msg_id)
            continue
        if cmd == "حذف اصل" and not is_private:
            target = sender
            bot_modules.set_user_asl(c, target, chat_id, None)
            conn.commit()
            send_short_message(chat_id, "اصل شما حذف شد.", msg_id)
            continue

        if cmd == "حذف لقب" and not is_private:
            target = sender
            bot_modules.set_user_lagab(c, target, chat_id, None)
            conn.commit()
            send_short_message(chat_id, "لقب شما حذف شد.", msg_id)
            continue
        if cmd.startswith("تنظیم اصل"):
            parts = cmd.split(maxsplit=2)
            if len(parts) < 3:
                continue
            text = parts[2].strip()
            bot_modules.set_user_asl(c, sender, chat_id, text)
            conn.commit()
            send_short_message(chat_id, f"اصل شما تنظیم شد", msg_id)
            continue

        if cmd.startswith("تنظیم لقب"):
            parts = cmd.split(maxsplit=2)
            if len(parts) < 3:
                continue
            text = parts[2].strip()
            bot_modules.set_user_lagab(c, sender, chat_id, text)
            conn.commit()
            send_short_message(chat_id, f"لقب تنظیم شد.", msg_id)
            continue

        if cmd == "راهنما" and not is_private:
            user_name = get_user_info(sender)
            text_msg = """━━━━━━━━━━━━━━━
     ✦راهنمای ربات✦LeGaNdR✦
━━━━━━━━━━━━━━
♦فعال - فعال کردن ربات و
 ➜مالک تنظیم می‌شوید در گروه 
♦غیرفعال - غیرفعال کردن ربات
♦انتقال مالکیت گروه
➜ انتقال مالکیت (ریپلای) 
━━━━━━━━━━━━━━━
⭕️)>{ لیست ها } <¥> 
♦لیست مقام - لیست تنظیم 
♦لیست قفلی - لیست سکوت 
♦لیست بن - لیست سرگرمی 
♦آمار (ریبلای) - آمارم - آمار گروه
♦گویدم-گوید(ریبلای)-گوید گروه 
━━━━━━━━━━━━━━━
⭕️)>{ تنظیم ادمین } <¥>
♦1-دستور - لیست مقام 
♦2-برای تنظیم ادمین 
♦تنظیم ادمین اول/دوم/سوم
♦تنظیم ادمین اول (ریپلای)
♦حذف ادمین اول/دوم/سوم
♦حذف ادمین اول امکان‌پذیر
➜(با ریبلای و بدون ریبلای)
━━━━━━━━━━━━━━━
⭕️)>{ بن. ان بن } <¥>
♦دستور - لیست بن
♦بن(ریبلای وگوید) 
♦آن بن (ریبلای وگوید)
━━━━━━━━━━━━━━━
⭕️)>{ تنظیم اخطار و سکوت....} <¥>
♦دستور - لیست تنظیم 
♦ همراه با راهنما زیر لیست
━━━━━━━━━━━━━━━
⭕️)>{ تنظیم قفلی } <¥>
♦دستور - لیست قفلی 
♦ همراه با راهنما وسط لیست 
━━━━━━━━━━━━━━━
⭕️)>{برای مشاهده سکوت ها} <¥>
♦دستور - لیست سکوت 
━━━━━━━━━━━━━━━
⭕️)>{راهنما بازی ها} <¥> 
♦دستور - لیست سرگرمی 
━━━━━━━━━━━━━━━
(⭕️) -♡- >{ دستورات آمار ها } <¥> 
♦آمارم - آمار(ریپلای) -آمار گروه 
♦1-آمارم-آمار=کاربر عادی
♦تنظیم لقب: شیطان / حذف لقب
♦تنظیم اصل: رضا / حذف اصل 
♦هر کاربر می تواند برای
➜ خودشو تنظیم یا حذف کند
♦مالک-با ریبلای می تواند
➜ برای همه رو حذف و تنظیم کند 
♦2-دستور مدال فقط برای 
➜ مالک هستی
♦تنظیم مدال:(عدد) 
♦3-دستور-آمارگروه فقط برای 
➜ ادمین مالک هستی
♦گروه باز/گروه بسته 
🤖دستورات سخنگو: هوش مصنوعی
♦سخنگو روشن/خاموش
♦یادگیری سوال : جواب - یاد دادن
🤖 هوش مصنوعی روشن/خاموش
👇استفاده از هوش مصنوعی𖣐👇
♦لجندر [سوال] - پرسیدن سوال
━━━━━━━━━━━━━━━
⭕️)>{دستورات های دستی} <¥> 
♦ گویدم - گوید گروه
➜ گوید (ریپلای) - گوید کاربر
♦سکوت (ریبلای.گوید)
➜ حذف سکوت (ریبلای.گوید)
♦اخطار 5 (ریبلای.گوید)  
➜ حذف اخطار 2 (ریبلای.گوید)
♦تنظیم مدال (عدد) با (ریبلای)
♦حذف پیام ها/حذف پیام (عدد) 
➜ حذف (ریبلای)
♦فونت [متن] - فونت‌های مختلف
➜مثال: فونت حامد یا فونت hello
🔺تاریخ - تاریخ امروز
🔺تایم - ساعت الان
━━━━━━━━━━━━━━━
👨‍🏫 آموزش فعال سازی ربات با فیلم 
[ @AmUzeEsh_LeGaNdR ]"""
            bold_text = "راهنمای ربات✦LeGaNdR"
            mono_parts = [{"text": sender}]
            send_formatted_message(chat_id, text_msg, msg_id, mono_parts=mono_parts, bold_text=bold_text)
            continue
        
    send_banner_to_all_groups()


