from telethon import TelegramClient, events
from telethon.tl import functions, types
from telethon.tl.functions.users import GetFullUserRequest
import asyncio
import os
import re
import json
import random
from io import BytesIO
from datetime import datetime, timedelta

import requests
import jdatetime
import pytz

from deep_translator import GoogleTranslator

# ============================== تنظیمات ==============================
# بهتره از متغیر محیطی خونده بشه تا مقادیر حساس داخل کد هاردکد نباشن
api_id = int(os.getenv("TG_API_ID", "12345"))
api_hash = os.getenv("TG_API_HASH", "YOUR_API_HASH")

BRS_API_KEY = os.getenv("BRS_API_KEY", "YOUR_BRSAPI_KEY")  # رایگان از https://brsapi.ir بگیر

client = TelegramClient(
    "arian2",
    api_id,
    api_hash,
    device_model="self society",
    system_version="Android 14",
    app_version="Telegram 10.5"
)

# ============================== وضعیت‌ها ==============================
time_name_status = False
time_bio_status = False
current_font = 7

auto_forward_status = False
auto_forward_interval = 60
auto_forward_message = None

original_name = None
original_bio = None

OWNER_ID = None

enemies = {}  # {chat_id: set(user_ids)}

enemy_replies = [
    "باشه", "چته", "خفه شو", "بسه دیگه", "ولم کن", "حوصله ندارم",
    "برو کنار", "مزاحم نشو", "باشه فهمیدیم", "چیکار داری",
    "ول کن", "بسه", "باشه بابا", "چته تو", "خفه",
    "باشه دیگه", "چیکارم داری", "برو پی کارت", "باشه آروم باش",
    "نمی‌خوام", "ولم کن لطفاً", "باشه فهمیدم", "باشه باشه",
    "باشه دیگه اذیت نکن", "چته آخه", "چیکار داری بهم",
    "باشه برو", "باشه ولم کن", "باشه تمومش کن"
]

auto_answers = {}   # {"کلمه": "جواب"}  -- مطابقت دقیق، نه substring
monshi_status = False

bold_status = False
reject_membership_status = False
auto_reaction_emoji = None
online_status = False

# --- سلف (تایمر مصرف/فروش) ---
# همینجا عدد روز رو تنظیم کن؛ مثلاً بنویس 30 یعنی این کد از اولین اجرا فقط
# 30 روز کار می‌کنه و بعدش خودکار خاموش میشه. برای نامحدود، None بذار.
SELF_LICENSE_DAYS = 30

LICENSE_FILE = "self_license.json"
self_expire_at = None   # timestamp یا None = نامحدود (خودکار از تنظیمات بالا پر میشه)

fonts = {
    "0": ["０","⓿","𝟎","𝟘","𝟬","𝟶","⓪","0"],
    "1": ["１","➊","𝟏","𝟙","𝟭","𝟷","①","1"],
    "2": ["２","➋","𝟐","𝟚","𝟮","𝟸","②","2"],
    "3": ["３","➌","𝟑","𝟛","𝟯","𝟹","③","3"],
    "4": ["４","➍","𝟒","𝟜","𝟰","𝟺","④","4"],
    "5": ["５","➎","𝟓","𝟝","𝟱","𝟻","⑤","5"],
    "6": ["６","➏","𝟔","𝟞","𝟲","𝟼","⑥","6"],
    "7": ["７","➐","𝟕","𝟟","𝟳","𝟽","⑦","7"],
    "8": ["８","➑","𝟖","𝟠","𝟴","𝟾","⑧","8"],
    "9": ["９","➒","𝟗","𝟡","𝟵","𝟿","⑨","9"]
}

def convert_font(text, style):
    if style == 7:
        return text
    result = ""
    for ch in text:
        if ch.isdigit():
            result += fonts[ch][style]
        else:
            result += ch
    return result

def get_time():
    return datetime.now().strftime("%H:%M")

# اعمال فوری فونت جدید روی اسم/بیوی فعال، بدون نیاز به خاموش/روشن کردن دستی
async def apply_font_now():
    global time_name_status, time_bio_status, original_name, original_bio, current_font
    t = convert_font(get_time(), current_font)

    if time_name_status and original_name is not None:
        try:
            await client(functions.account.UpdateProfileRequest(first_name=f"{original_name} | {t}"))
        except Exception as e:
            print(e)

    if time_bio_status and original_bio is not None:
        try:
            await client(functions.account.UpdateProfileRequest(about=f"{original_bio} | {t}"))
        except Exception as e:
            print(e)

# ============================== سلف / لایسنس ==============================
# توجه مهم: چون این اسکریپت روی اکانت خود کاربر اجرا میشه و کد کاملاً در
# اختیار اونه، این فقط یک تایمر ساده‌ست، نه یک قفل امنیتی واقعی.

def load_license():
    global self_expire_at
    try:
        if os.path.exists(LICENSE_FILE):
            with open(LICENSE_FILE, "r") as f:
                self_expire_at = json.load(f).get("expire_at")
        else:
            if SELF_LICENSE_DAYS is not None:
                self_expire_at = (datetime.now() + timedelta(days=SELF_LICENSE_DAYS)).timestamp()
                save_license(self_expire_at)
            else:
                self_expire_at = None
    except Exception as e:
        print(e)
        self_expire_at = None

def save_license(expire_at):
    global self_expire_at
    self_expire_at = expire_at
    try:
        with open(LICENSE_FILE, "w") as f:
            json.dump({"expire_at": expire_at}, f)
    except Exception as e:
        print(e)

def is_self_active():
    if self_expire_at is None:
        return True
    return datetime.now().timestamp() < self_expire_at

# ============================== کمکی: ترجمه رایگان (بدون کلید) ==============================
LANG_MAP = {
    "انگلیسی": "en", "فارسی": "fa", "عربی": "ar", "کره ای": "ko", "کره‌ای": "ko",
    "ترکی": "tr", "روسی": "ru", "فرانسوی": "fr", "آلمانی": "de", "چینی": "zh-CN",
    "ژاپنی": "ja", "اسپانیایی": "es", "ایتالیایی": "it", "هندی": "hi"
}

def translate_text(src_text, lang_name):
    target = LANG_MAP.get(lang_name.strip(), lang_name.strip())
    return GoogleTranslator(source="auto", target=target).translate(src_text)

# ============================== کمکی: تاریخ و ساعت دقیق ایران ==============================
def iran_datetime_text():
    tehran = pytz.timezone("Asia/Tehran")
    now = datetime.now(tehran)
    jd = jdatetime.datetime.fromgregorian(datetime=now)
    day_names = ["شنبه", "یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه"]
    day_name = day_names[jd.weekday()]
    return f"📅 {day_name} {jd.year}/{jd.month:02d}/{jd.day:02d}\n🕒 {now.strftime('%H:%M:%S')} (به وقت ایران)"

# ============================== کمکی: قیمت دلار/طلا/یورو/تتر/ترون ==============================
def fetch_prices():
    try:
        url = f"https://BrsApi.ir/Api/Market/Gold_Currency.php?key={BRS_API_KEY}"
        return requests.get(url, timeout=10).json()
    except Exception as e:
        print(e)
        return None

def find_price(data, keywords):
    if not data:
        return None
    for section in ("gold", "currency", "cryptocurrency"):
        for item in (data.get(section) or []):
            name = f"{item.get('name','')} {item.get('name_en','')}"
            if any(k in name for k in keywords):
                return item
    return None

PRICE_MAP = {
    "قیمت دلار": (["دلار", "USD"], "دلار آمریکا"),
    "قیمت طلا": (["طلای 18", "طلا ۱۸", "18 عیار", "گرم طلا"], "طلای ۱۸ عیار"),
    "قیمت یورو": (["یورو", "EUR"], "یورو"),
    "قیمت تتر": (["تتر", "USDT", "Tether"], "تتر"),
    "قیمت ترون": (["ترون", "TRX", "Tron"], "ترون"),
}

# ============================== کمکی: ارسال با دور زدن نیاز به عضویت (best-effort) ==============================
async def safe_send(dest, media_buf, caption):
    try:
        if media_buf:
            media_buf.seek(0)
            await client.send_file(dest, media_buf, caption=caption)
        else:
            await client.send_message(dest, caption)
        return True
    except Exception as e:
        if reject_membership_status:
            m = re.search(r'@(\w+)', str(e))
            if m:
                try:
                    await client(functions.channels.JoinChannelRequest(m.group(1)))
                    await asyncio.sleep(1)
                    if media_buf:
                        media_buf.seek(0)
                        await client.send_file(dest, media_buf, caption=caption)
                    else:
                        await client.send_message(dest, caption)
                    return True
                except Exception as e2:
                    print(e2)
        print(e)
        return False

# ============================== هندلر اصلی (دستورات owner) ==============================
@client.on(events.NewMessage)
async def handler(event):
    global OWNER_ID, time_name_status, time_bio_status
    global original_name, original_bio, current_font
    global auto_forward_status, auto_forward_interval, auto_forward_message
    global enemies, auto_answers, monshi_status
    global bold_status, reject_membership_status, auto_reaction_emoji, online_status
    global self_expire_at

    if not is_self_active():
        return

    if OWNER_ID is None:
        me = await client.get_me()
        OWNER_ID = me.id

    if event.sender_id != OWNER_ID:
        return

    text = (event.raw_text or "").strip()

    # پنل
    if text == "پنل":
        await event.reply(
            "🔧 **پنل مدیریت**\n\n"
            "⏰ تایم اسم: تایم اسم روشن / خاموش\n"
            "📜 تایم بیو: تایم بیو روشن / خاموش\n"
            "🎨 فونت: فونت 1 تا 7 / فونت خاموش\n\n"
            "📤 ارسال خودکار: فوروارد خودکار <دقیقه> (ریپلای) / فوروارد خودکار خاموش\n"
            "👥 فوروارد دستی: فوروارد مخاطب / فوروارد پیوی (ریپلای)\n\n"
            "⚠️ دشمن: دشمن روشن / دشمن خاموش (ریپلای)\n\n"
            "🤖 منشی: منشی <کلمه> <جواب> / منشی روشن / خاموش / دلیت\n\n"
            "🖼️ ذخیره مدیای تایمردار: ریپلای + مرسی/میسی/./جون\n"
            "📥 دانلود استوری: دانلود <لینک>\n\n"
            "🅱️ بولد: بولد روشن / خاموش\n\n"
            "🌍 ترجمه: (ریپلای) ترجمه <زبان>\n\n"
            "⏳ سلف: سلف <روز> / سلف خاموش / سلف وضعیت\n\n"
            "🚪 رد کردن عضویت: رد کردن عضویت روشن / خاموش\n\n"
            "❤️ ری‌اکشن خودکار: ری اکشن خودکار <ایموجی> / خاموش\n\n"
            "🟢 آنلاین: آنلاین روشن / خاموش\n\n"
            "ℹ️ اطلاعات: (ریپلای) اطلاعات\n\n"
            "🕒 تایم: تایم\n"
            "💰 قیمت: قیمت دلار / طلا / یورو / تتر / ترون\n"
        )
        return

    # انتخاب فونت
    if text.startswith("فونت"):
        if text == "فونت خاموش":
            current_font = 7
            await apply_font_now()
            await event.reply("🎨 فونت معمولی فعال شد")
            return
        try:
            num = int(text.split()[1])
            if 1 <= num <= 7:
                current_font = num - 1
                await apply_font_now()
                await event.reply(f"🎨 فونت {num} فعال شد")
                return
        except:
            pass

    # ارسال خودکار روشن
    if text.startswith("فوروارد خودکار") and event.is_reply:
        parts = text.split()
        if len(parts) == 3 and parts[2].isdigit():
            minutes = int(parts[2])
            auto_forward_interval = minutes * 60
            auto_forward_status = True
            auto_forward_message = await event.get_reply_message()
            await event.reply(f"📤 ارسال خودکار هر {minutes} دقیقه فعال شد")
            return

    # ارسال خودکار خاموش
    if text == "فوروارد خودکار خاموش":
        auto_forward_status = False
        await event.reply("📤 ارسال خودکار خاموش شد")
        return

    # فوروارد مخاطب
    if text == "فوروارد مخاطب" and event.is_reply:
        msg = await event.get_reply_message()
        await event.reply("📤 در حال ارسال پیام به تمام مخاطبین...")

        media_buf = None
        if msg.media:
            try:
                buf = BytesIO()
                await client.download_media(msg, file=buf)
                buf.seek(0)
                media_buf = buf
            except:
                media_buf = None

        caption = msg.text or ""
        contacts = await client.get_contacts()

        sent = 0
        for c in contacts:
            ok = await safe_send(c.id, media_buf, caption)
            if ok:
                sent += 1

        await event.reply(f"✅ پیام برای {sent} مخاطب ارسال شد")
        return

    # فوروارد پیوی
    if text == "فوروارد پیوی" and event.is_reply:
        msg = await event.get_reply_message()
        await event.reply("📤 در حال ارسال پیام به تمام پیوی‌هایی که قبلاً پیام دادی...")

        media_buf = None
        if msg.media:
            try:
                buf = BytesIO()
                await client.download_media(msg, file=buf)
                buf.seek(0)
                media_buf = buf
            except:
                media_buf = None

        caption = msg.text or ""
        dialogs = await client.get_dialogs()

        sent = 0
        for d in dialogs:
            if d.is_user and not d.entity.bot:
                ok = await safe_send(d.id, media_buf, caption)
                if ok:
                    sent += 1

        await event.reply(f"✅ پیام برای {sent} پیوی ارسال شد")
        return

    # دشمن روشن
    if text == "دشمن روشن" and event.is_reply:
        reply = await event.get_reply_message()
        user_id = reply.sender_id
        chat_id = event.chat_id
        if chat_id not in enemies:
            enemies[chat_id] = set()
        enemies[chat_id].add(user_id)
        await event.reply("⚠️ دشمن در این چت فعال شد")
        return

    # دشمن خاموش
    if text == "دشمن خاموش" and event.is_reply:
        reply = await event.get_reply_message()
        user_id = reply.sender_id
        chat_id = event.chat_id
        if chat_id in enemies and user_id in enemies[chat_id]:
            enemies[chat_id].remove(user_id)
        await event.reply("✅ دشمن در این چت خاموش شد")
        return

    # منشی اضافه (فقط اگر جزو دستورات ثابت منشی نباشه)
    if text.startswith("منشی ") and len(text.split()) >= 3 and text not in ["منشی روشن", "منشی خاموش", "منشی دلیت"]:
        parts = text.split(maxsplit=2)
        key = parts[1]
        value = parts[2]
        auto_answers[key] = value
        await event.reply(f"🤖 منشی اضافه شد:\nاگر کسی دقیقاً گفت «{key}» → جواب بده «{value}»")
        return

    if text == "منشی روشن":
        monshi_status = True
        await event.reply("🤖 منشی روشن شد")
        return

    if text == "منشی خاموش":
        monshi_status = False
        await event.reply("❌ منشی خاموش شد")
        return

    if text == "منشی دلیت":
        auto_answers.clear()
        await event.reply("🗑️ تمام دستورات منشی حذف شد")
        return

    # تایم اسم روشن/خاموش
    if text == "تایم اسم روشن":
        me = await client.get_me()
        if original_name is None:
            original_name = me.first_name
        time_name_status = True
        t = convert_font(get_time(), current_font)
        await client(functions.account.UpdateProfileRequest(first_name=f"{original_name} | {t}"))
        await event.reply("⏰ تایم اسم روشن شد")
        return

    if text == "تایم اسم خاموش":
        if original_name:
            await client(functions.account.UpdateProfileRequest(first_name=original_name))
        time_name_status = False
        await event.reply("⏰ تایم اسم خاموش شد")
        return

    # تایم بیو روشن/خاموش
    if text == "تایم بیو روشن":
        me = await client.get_me()
        full = await client(GetFullUserRequest(me.id))
        bio = full.full_user.about or ""
        if original_bio is None:
            original_bio = bio
        time_bio_status = True
        t = convert_font(get_time(), current_font)
        await client(functions.account.UpdateProfileRequest(about=f"{original_bio} | {t}"))
        await event.reply("📜 تایم بیو روشن شد")
        return

    if text == "تایم بیو خاموش":
        if original_bio is not None:
            await client(functions.account.UpdateProfileRequest(about=original_bio))
        time_bio_status = False
        await event.reply("📜 تایم بیو خاموش شد")
        return

    # ---------------- بولد ----------------
    if text == "بولد روشن":
        bold_status = True
        await event.reply("🅱️ حالت بولد روشن شد")
        return
    if text == "بولد خاموش":
        bold_status = False
        await event.reply("🅱️ حالت بولد خاموش شد")
        return

    # ---------------- ترجمه ----------------
    if text.startswith("ترجمه ") and event.is_reply:
        lang = text.split(maxsplit=1)[1].strip()
        reply_msg = await event.get_reply_message()
        src_text = reply_msg.text or ""
        if not src_text:
            await event.reply("⚠️ متنی برای ترجمه پیدا نشد")
            return
        try:
            translated = await asyncio.to_thread(translate_text, src_text, lang)
            await event.reply(translated)
        except Exception as e:
            print(e)
            await event.reply("⚠️ خطا در ترجمه")
        return

    # ---------------- سلف (تایمر مصرف) ----------------
    if text.startswith("سلف") and text not in ["سلف خاموش", "سلف وضعیت"]:
        parts = text.split()
        if len(parts) == 2 and parts[1].isdigit():
            days = int(parts[1])
            expire_at = (datetime.now() + timedelta(days=days)).timestamp()
            save_license(expire_at)
            await event.reply(f"⏳ سلف برای {days} روز فعال شد")
            return

    if text == "سلف خاموش":
        save_license(None)
        await event.reply("♾️ محدودیت سلف برداشته شد (نامحدود)")
        return

    if text == "سلف وضعیت":
        if self_expire_at is None:
            await event.reply("♾️ سلف نامحدوده")
        else:
            remaining = self_expire_at - datetime.now().timestamp()
            if remaining <= 0:
                await event.reply("⛔ سلف منقضی شده")
            else:
                days_left = int(remaining // 86400)
                hours_left = int((remaining % 86400) // 3600)
                await event.reply(f"⏳ {days_left} روز و {hours_left} ساعت تا انقضا باقیه")
        return

    # ---------------- رد کردن عضویت (best-effort) ----------------
    if text == "رد کردن عضویت روشن":
        reject_membership_status = True
        await event.reply("🚪 رد کردن عضویت روشن شد")
        return
    if text == "رد کردن عضویت خاموش":
        reject_membership_status = False
        await event.reply("🚪 رد کردن عضویت خاموش شد")
        return

    # ---------------- ری‌اکشن خودکار ----------------
    if text.startswith("ری اکشن خودکار"):
        if text == "ری اکشن خودکار خاموش":
            auto_reaction_emoji = None
            await event.reply("❌ ری‌اکشن خودکار خاموش شد")
            return
        parts = text.split(maxsplit=2)
        if len(parts) == 3:
            auto_reaction_emoji = parts[2].strip()
            await event.reply(f"✅ ری‌اکشن خودکار {auto_reaction_emoji} فعال شد")
            return

    # ---------------- آنلاین دائم ----------------
    if text == "آنلاین روشن":
        online_status = True
        await event.reply("🟢 حالت آنلاین دائم روشن شد")
        return
    if text == "آنلاین خاموش":
        online_status = False
        await event.reply("⚪ حالت آنلاین دائم خاموش شد")
        return

    # ---------------- اطلاعات ----------------
    if text == "اطلاعات" and event.is_reply:
        reply_msg = await event.get_reply_message()
        uid = reply_msg.sender_id
        try:
            user = await client.get_entity(uid)
            full = await client(GetFullUserRequest(uid))
            bio = full.full_user.about or "ندارد"
            username = f"@{user.username}" if user.username else "ندارد"
            info = (
                f"👤 اطلاعات کاربر:\n"
                f"آیدی عددی: {uid}\n"
                f"یوزرنیم: {username}\n"
                f"نام: {user.first_name or ''} {user.last_name or ''}\n"
                f"بیوگرافی: {bio}\n"
                f"پرمیوم: {'بله' if getattr(user, 'premium', False) else 'خیر'}"
            )
            await event.reply(info)
        except Exception as e:
            print(e)
            await event.reply("⚠️ خطا در دریافت اطلاعات")
        return

    # ---------------- تاریخ و ساعت ایران ----------------
    if text == "تایم":
        await event.reply(iran_datetime_text())
        return

    # ---------------- قیمت‌ها ----------------
    if text in PRICE_MAP:
        keywords, label = PRICE_MAP[text]
        data = await asyncio.to_thread(fetch_prices)
        item = find_price(data, keywords)
        if item:
            price = item.get("price", item.get("Price", "-"))
            await event.reply(f"💰 {label}: {price}")
        else:
            await event.reply("⚠️ قیمت پیدا نشد. کلید BRS_API_KEY و اتصال اینترنت رو چک کن.")
        return


# ============================== دشمن پاسخ‌دهنده ==============================
@client.on(events.NewMessage)
async def enemy_responder(event):
    if not is_self_active():
        return
    chat_id = event.chat_id
    user_id = event.sender_id
    if chat_id in enemies and user_id in enemies[chat_id]:
        await event.reply(random.choice(enemy_replies))


# ============================== منشی (فقط پیوی، مطابقت دقیق) ==============================
@client.on(events.NewMessage)
async def monshi_responder(event):
    global monshi_status, auto_answers, OWNER_ID
    if not is_self_active():
        return
    if not monshi_status:
        return
    if not event.is_private:
        return
    if OWNER_ID is None:
        me = await client.get_me()
        OWNER_ID = me.id
    if event.sender_id == OWNER_ID:
        return

    text = (event.raw_text or "").strip()
    if text in auto_answers:
        await event.reply(auto_answers[text])


# ============================== بولد خودکار روی پیام‌های خودم ==============================
@client.on(events.NewMessage(outgoing=True))
async def bold_responder(event):
    if not is_self_active():
        return
    if not bold_status:
        return
    if not event.raw_text or event.raw_text.startswith("**"):
        return
    try:
        await client.edit_message(event.chat_id, event.id, f"**{event.raw_text}**", parse_mode="markdown")
    except Exception as e:
        print(e)


# ============================== ری‌اکشن خودکار ==============================
@client.on(events.NewMessage)
async def auto_reaction_handler(event):
    global OWNER_ID
    if not is_self_active():
        return
    if not auto_reaction_emoji:
        return
    if OWNER_ID is None:
        me = await client.get_me()
        OWNER_ID = me.id
    if event.sender_id == OWNER_ID:
        return

    should_react = False
    if event.is_private:
        should_react = True
    elif event.is_reply:
        replied = await event.get_reply_message()
        if replied and replied.sender_id == OWNER_ID:
            should_react = True

    if should_react:
        try:
            await client(functions.messages.SendReactionRequest(
                peer=event.chat_id,
                msg_id=event.id,
                reaction=[types.ReactionEmoji(emoticon=auto_reaction_emoji)]
            ))
        except Exception as e:
            print(e)


# ============================== ذخیره عکس/ویدیو تایمردار ==============================
@client.on(events.NewMessage)
async def save_timer_media_handler(event):
    if not is_self_active():
        return
    if not event.is_reply:
        return

    reply = await event.get_reply_message()
    if not (reply.media and getattr(reply.media, "ttl_seconds", None)):
        return

    triggers = ["مرسی", "میسی", ".", "جون"]
    if (event.raw_text or "").strip() in triggers:
        try:
            buf = BytesIO()
            await client.download_media(reply, file=buf)
            buf.seek(0)
            await client.send_file("me", buf)
        except Exception as e:
            print(e)


# ============================== دانلود استوری تلگرام ==============================
@client.on(events.NewMessage)
async def download_story_handler(event):
    global OWNER_ID
    if not is_self_active():
        return
    if OWNER_ID is None:
        me = await client.get_me()
        OWNER_ID = me.id
    if event.sender_id != OWNER_ID:
        return

    text = (event.raw_text or "").strip()
    if text.startswith("دانلود"):
        cmd_parts = text.split()
        if len(cmd_parts) < 2:
            await event.reply("لینک استوری را بعد از دانلود بفرست ✖️")
            return

        link = cmd_parts[1]
        try:
            link_parts = link.split("/")
            story_id = int(link_parts[-1])
            username = link_parts[-3]

            user = await client.get_entity(username)
            result = await client(functions.stories.GetStoriesByIDRequest(peer=user, id=[story_id]))

            if not result.stories or not result.stories[0].media:
                await event.reply("استوری پیدا نشد یا قابل دانلود نیست ✖️")
                return

            buf = BytesIO()
            await client.download_media(result.stories[0].media, file=buf)
            buf.seek(0)
            await client.send_file("me", buf)
            await event.reply("استوری ذخیره شد در پیام های ذخیره شما✅")
        except Exception as e:
            await event.reply("خطا در دانلود✖️")
            print(e)


# ============================== حلقه‌های پس‌زمینه ==============================
async def auto_forward_loop():
    global auto_forward_status, auto_forward_interval, auto_forward_message
    while True:
        if is_self_active() and auto_forward_status and auto_forward_message:
            dialogs = await client.get_dialogs()

            media_buf = None
            if auto_forward_message.media:
                try:
                    buf = BytesIO()
                    await client.download_media(auto_forward_message, file=buf)
                    buf.seek(0)
                    media_buf = buf
                except:
                    media_buf = None

            caption = auto_forward_message.text or ""

            for d in dialogs:
                if d.is_group:
                    await safe_send(d.id, media_buf, caption)

            await asyncio.sleep(auto_forward_interval)
        else:
            await asyncio.sleep(2)


async def auto_update():
    global time_name_status, time_bio_status
    global original_name, original_bio, current_font
    while True:
        if is_self_active():
            now = convert_font(get_time(), current_font)
            if time_name_status:
                try:
                    await client(functions.account.UpdateProfileRequest(first_name=f"{original_name} | {now}"))
                except Exception as e:
                    print(e)
            if time_bio_status:
                try:
                    await client(functions.account.UpdateProfileRequest(about=f"{original_bio} | {now}"))
                except Exception as e:
                    print(e)
        await asyncio.sleep(30)


async def online_loop():
    while True:
        if is_self_active() and online_status:
            try:
                await client(functions.account.UpdateStatusRequest(offline=False))
            except Exception as e:
                print(e)
            await asyncio.sleep(20)
        else:
            await asyncio.sleep(5)


async def main():
    global OWNER_ID
    me = await client.get_me()
    OWNER_ID = me.id

    asyncio.create_task(auto_update())
    asyncio.create_task(auto_forward_loop())
    asyncio.create_task(online_loop())
    await client.run_until_disconnected()


load_license()
client.start()
client.loop.run_until_complete(main())
