# ========================= • App Imports • ============================ #
from asyncio import gather
from aiohttp_helper import AioHttp
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from bs4 import BeautifulSoup as bs, BeautifulSoup
from colorama import Fore, init
from countryinfo import CountryInfo
from currency_converter import CurrencyConverter
from datetime import date, datetime
from decimal import Decimal, getcontext
from html import escape
from imdb import IMDb
from instagram_private_api import Client as insta
from ipapi import location
import jdatetime
import jdatetime
from jdatetime import GregorianToJalali, JalaliToGregorian
jstrftime = jdatetime.datetime.strftime
jstrptime = jdatetime.datetime.strptime
from math import ceil, floor
from os import name, remove, path
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageOps
from platform import python_version, uname
from psutil import virtual_memory, cpu_freq, cpu_percent, cpu_count
from hachoir.parser import createParser
from pySmartDL import SmartDL
from pyrogram import Client, filters, idle, enums, ContinuePropagation
from pyrogram.errors.exceptions.bad_request_400 import ChatNotModified
from pyrogram.errors.exceptions.flood_420 import FloodWait
from pyrogram.raw import functions, base, types
from pyrogram.raw.functions.account import GetAuthorizations, ResetAuthorization
from pyrogram.raw.functions.auth import ResetAuthorizations
from pyrogram.raw.functions.contacts import GetBlocked
from pyrogram.raw.functions.messages import GetAllStickers, GetStickerSet
from pyrogram.raw.types import InputStickerSetShortName, UpdateServiceNotification
from qrcode import make
from random import randint, choice
from re import match, findall
from requests import get as GET, get as make_get_request
from shutil import copyfile, move, rmtree
from socket import gethostbyname
from telegraph import upload_file
from threading import Timer
from thisapidoesnotexist import get_cat, get_person
from time import time, sleep, strftime, gmtime, perf_counter
from translate import Translator
from typing import Tuple, Union
from collections import Counter
from uptime import uptime
from urllib.request import Request
from urllib.parse import quote_plus, unquote
from wikipedia import search, page, set_lang, summary
from zipfile import ZipFile, is_zipfile
import asyncio
import base64
import html
import importlib
import json
import logging
import math
import os
import pickle
import psutil
import random
import aiohttp
import re
import shutil
import shlex
import sys
import textwrap
import traceback
import urllib
import zipfile
from gtts import gTTS
from io import BytesIO, StringIO
from collections import deque
from plugins import *
from pyrogram.errors import *
from pyrogram.types import *

# ========================= • App Variable • =========================== #

admin = 8237225532
api_id = 32514539
api_hash = "e94dbda6bc87f1aeacdb5550ee6dfae3"
bot_id = None

os.chdir(os.path.dirname(os.path.abspath(__file__)))
os.chdir(os.path.dirname(os.path.abspath(__file__)))
users = []
my_users = []
my_users_filter = filters.user(my_users)
enemy = []
love = []
mutey = []
tabchitimer = []
imdb = IMDb()
mov_titles = [
    "long imdb title",
    "long imdb canonical title",
    "smart long imdb canonical title",
    "smart canonical title",
    "canonical title",
    "localized title",
]
now = ""
answer = []
javab = []
spam_chats = []
DATA_FILE = "data.json"
LOG_GROUP = None
log = []
account_id = "@UsefRostaaami"
is_antilog = False
Src_vrsion = "V - 3.0.0"
moviepath = os.path.join(os.getcwd(), "temp", "moviethumb.jpg")

# =========================== • App Client • =========================== #

app = Client(f"sessions-{admin}", api_id, api_hash, device_model="ULTRA-SELF")
client = Client("Self", api_id, api_hash, device_model="Teleg-Assistant")

def init_data():
    default_data = {
        "limitDel": 4,
        "welcome": "off",
        "firstcom": "off",
        "timename": "off",
        "timename2": "off",
        "timebio": "off",
        "timebio2": "off",
        "timebio3": "off",
        "timebio4": "off",
        "timebio5": "off",
        "timebio6": "off",
        "fontname": "off",
        "fuck": "off",
        "anti_del": "off",
        "autoan": "off",
        "boldmode": "off",
        "emojimode": "off",
        "underline": "off",
        "italicmode": "off",
        "codemode": "off",
        "strike": "off",
        "spoilermode": "off",
        "quotemode": "off",
        "pvlock": "off",
        "typing": "off",
        "mention": "off",
        "monshi": "off",
        "monshi2": "off",
        "last_update_time": "",
        "user_name": "",
        "user_bio": "",
        "last_profile_update": "",
        "anti_del_chat": "",
        "timerpv": "",
        "timegp": "",
        "bannerpv": "",
        "command_prefix": ""
    }

    if not os.path.isfile(DATA_FILE):
        save_data(default_data)

if_not_exist_creat("db.txt")

# ============================ • App Defs • ============================ #

async def tg_lock(app, message: Message, permissions: list, perm: str, lock: bool
):
    if lock:
        if perm not in permissions:
            return await message.edit_text("Already locked.")
        permissions.remove(perm)
    else:
        if perm in permissions:
            return await message.edit_text("Already Unlocked.")
        permissions.append(perm)

    permissions = {perm: True for perm in list(set(permissions))}

    try:
        await app.set_chat_permissions(
            message.chat.id, ChatPermissions(**permissions)
        )
    except ChatNotModified:
        return await message.edit_text(
            "To unlock this, you have to unlock 'messages' first."
        )

    await message.edit_text(("Locked." if lock else "Unlocked."))

async def resize_media(media: str, video: bool, fast_forward: bool) -> str:
    if video:
        info_ = Media_Info.data(media)
        width = info_["pixel_sizes"][0]
        height = info_["pixel_sizes"][1]
        sec = info_["duration_in_ms"]
        s = round(float(sec)) / 1000

        if height == width:
            height, width = 512, 512
            
        elif height > width:
            height, width = 512, -1
            
        elif width > height:
            height, width = -1, 512

        resized_video = f"{media}.webm"
        if fast_forward:
            if s > 3:
                fract_ = 3 / s
                ff_f = round(fract_, 2)
                set_pts_ = ff_f - 0.01 if ff_f > fract_ else ff_f
                cmd_f = f"-filter:v 'setpts={set_pts_}*PTS',scale={width}:{height}"
            else:
                cmd_f = f"-filter:v scale={width}:{height}"
        else:
            cmd_f = f"-filter:v scale={width}:{height}"
        fps_ = float(info_["frame_rate"])
        fps_cmd = "-r 30 " if fps_ > 30 else ""
        cmd = f"ffmpeg -i {media} {cmd_f} -ss 00:00:00 -to 00:00:03 -an -c:v libvpx-vp9 {fps_cmd}-fs 256K {resized_video}"
        _, error, __, ___ = await run_cmd(cmd)
        os.remove(media)
        return resized_video

    image = Image.open(media)
    maxsize = 512
    scale = maxsize / max(image.width, image.height)
    new_size = (int(image.width * scale), int(image.height * scale))

    image = image.resize(new_size, Image.LANCZOS)
    resized_photo = "sticker.png"
    image.save(resized_photo)
    os.remove(media)
    return resized_photo

async def edit_or_reply(message: Message, *args, **kwargs) -> Message:
    apa = (message.edit_text if bool(message.from_user and message.from_user.is_self or message.outgoing) else (message.reply_to_message or message).reply_text)
    return await apa(*args, **kwargs)

async def current_chat_permissions(app, chat_id):
    perms = []
    perm = (await app.get_chat(chat_id)).permissions
    if perm.can_send_messages:
        perms.append("can_send_messages")
    if perm.can_send_media_messages:
        perms.append("can_send_media_messages")
    if perm.can_send_other_messages:
        perms.append("can_send_other_messages")
    if perm.can_add_web_page_previews:
        perms.append("can_add_web_page_previews")
    if perm.can_send_polls:
        perms.append("can_send_polls")
    if perm.can_change_info:
        perms.append("can_change_info")
    if perm.can_invite_users:
        perms.append("can_invite_users")
    if perm.can_pin_messages:
        perms.append("can_pin_messages")

    return perms

async def check_membership(channel, user_id):
    try:
        member = await app.get_chat_member(channel, user_id)
        return True
    except Exception as e:
        await message.reply("**• خطا!**")

async def packinfo(app, message: Message):
    rep = await message.edit_text("`Processing...`")
    if not message.reply_to_message:
        await rep.edit("Please Reply To Sticker...")
        return
    if not message.reply_to_message.sticker:
        await rep.edit("Please Reply To A Sticker...")
        return
    if not message.reply_to_message.sticker.set_name:
        await rep.edit("`Seems Like A Stray Sticker!`")
        return
    stickerset = await app.invoke(
        GetStickerSet(
            stickerset=InputStickerSetShortName(
                short_name=message.reply_to_message.sticker.set_name
            ),
            hash=0,
        )
    )
    emojis = []
    for stucker in stickerset.packs:
        if stucker.emoticon not in emojis:
            emojis.append(stucker.emoticon)
    output = f"""**Sticker Pack Title **: `{stickerset.set.title}`
**Sticker Pack Short Name **: `{stickerset.set.short_name}`
**Stickers Count **: `{stickerset.set.count}`
**Archived **: `{stickerset.set.archived}`
**Official **: `{stickerset.set.official}`
**Masks **: `{stickerset.set.masks}`
**Animated **: `{stickerset.set.animated}`
**Emojis In Pack **: `{' '.join(emojis)}`
"""
    await rep.edit(output)

async def add_text_img(image_path, text):
    font_size = 12
    stroke_width = 1

    if ";" in text:
        upper_text, lower_text = text.split(";")
    else:
        upper_text = text
        lower_text = ""

    img = Image.open(image_path).convert("RGBA")
    img_info = img.info
    image_width, image_height = img.size
    font = ImageFont.truetype(
        font="cache/default.ttf",
        size=int(image_height * font_size) // 100,
    )
    draw = ImageDraw.Draw(img)

    char_width, char_height = font.getsize("A")
    chars_per_line = image_width // char_width
    top_lines = textwrap.wrap(upper_text, width=chars_per_line)
    bottom_lines = textwrap.wrap(lower_text, width=chars_per_line)

    if top_lines:
        y = 10
        for line in top_lines:
            line_width, line_height = font.getsize(line)
            x = (image_width - line_width) / 2
            draw.text(
                (x, y),
                line,
                fill="white",
                font=font,
                stroke_width=stroke_width,
                stroke_fill="black",
            )
            y += line_height

    if bottom_lines:
        y = image_height - char_height * len(bottom_lines) - 15
        for line in bottom_lines:
            line_width, line_height = font.getsize(line)
            x = (image_width - line_width) / 2
            draw.text(
                (x, y),
                line,
                fill="white",
                font=font,
                stroke_width=stroke_width,
                stroke_fill="black",
            )
            y += line_height

    final_image = os.path.join("memify.webp")
    img.save(final_image, **img_info)
    return final_image

async def bash(cmd):
    process = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()
    err = stderr.decode().strip()
    out = stdout.decode().strip()
    return out, err

async def get_response(message, app):
    return [x async for x in app.get_chat_history("Stickers", limit=1)][0].text

def get_text(message: Message) -> Union[str, None]:
    if message.text is None:
        return
    
    if " " not in message.text:
        return
    
    try:
        return message.text.split(None, 1)[1]
    except IndexError:
        pass

def load_data():
    with open(DATA_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

def get_text(message):
    text = message.text
    return text

def put(data):
    with open('data.pickle', 'wb') as f:
        pickle.dump(data, f)

def get():
    try:
        with open('data.pickle', 'rb') as f:
            return pickle.load(f)
    except FileNotFoundError:
        return {}
        
def ReplyCheck(message: Message):
    reply_id = None

    if message.reply_to_message:
        reply_id = message.reply_to_message.id

    elif not message.from_user.is_self:
        reply_id = message.id

    return reply_id

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

def get_arg(message: Message):
    msg = message.text
    msg = msg.replace(" ", "", 1) if msg[1] == " " else msg
    split = msg[1:].replace("\n", " \n").split(" ")
    if " ".join(split[1:]).strip() == "":
        return ""
    return " ".join(split[1:])

def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return "%3.1f %s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f %s%s" % (num, 'Y', suffix)

def get_cast(casttype, movie):
    mov_casttype = ""
    if casttype in list(movie.keys()):
        i = 0
        for j in movie[casttype]:
            
            if i < 1:
                mov_casttype += str(j)
                
            elif i < 5:
                mov_casttype += ", " + str(j)
                
            else:
                break
            i += 1
    else:
        mov_casttype += "Not Data"
    return mov_casttype

def get_moviecollections(movie):
    result = ""
    if "box office" in movie.keys():
        for i in movie["box office"].keys():
            result += f"\n•  <b>{i}:</b> <code>{movie['box office'][i]}</code>"
    else:
        result = "<code>No Data</code>"
    return result

def mak():
    with app:
        m =  app.send_message("me" , ".").message_id
        app.delete_messages("me" , m) 

def job():
    data = load_data()
    jdatetime.set_locale('fa_IR')
    d = jdatetime.datetime.now().strftime("%a")
    now_time = datetime.now(timezone("Asia/Tehran")).strftime("%H:%M")
    
    if data.get("last_update_time") != now_time:
        try:
            if data.get("timename") == "on":
                app.invoke(functions.account.UpdateProfile(last_name=create_time()))
                    
            if data.get("timename2") == "on":
                app.invoke(functions.account.UpdateProfile(last_name=create_time2()))
                    
            if data.get("timebio") == "on":
                app.invoke(functions.account.UpdateProfile(about=f'{data.get("user_bio", "")} {create_time()}'))
                    
            if data.get("timebio2") == "on":
                app.invoke(functions.account.UpdateProfile(about=f'{data.get("user_bio", "")} {create_time2()}'))
                    
            if data.get("timebio3") == "on":
                app.invoke(functions.account.UpdateProfile(
                    about=f'{moon_or_sun()} | {data.get("user_bio", "")} | {create_time2()} | {create_tarikh()}'
                ))
                        
            if data.get("timebio4") == "on":
                app.invoke(functions.account.UpdateProfile(
                    about=f'{moon_or_sun()} | {data.get("user_bio", "")} | {create_time2()} | {create_tarikh()} | {d}'
                ))
                        
            if data.get("timebio5") == "on":
                app.invoke(functions.account.UpdateProfile(
                    about=f'{love_emoji()} | {data.get("user_bio", "")} | {create_time2()} | {create_tarikh()} | {d}'
                ))
                        
            if data.get("timebio6") == "on":
                app.invoke(functions.account.UpdateProfile(
                    about=f'فضولی شما در تاریخ {fozolidate()} در ساعت {fozolitime()} با موفقیت ثبت شد✅'
                ))
                        
            if data.get("fontname") == "on":
                app.invoke(functions.account.UpdateProfile(first_name=fontinname(data.get("user_name", ""))))
                    
        except Exception as e:
            print("Error in job function")

        data["last_update_time"] = now_time
        save_data(data)

def antidelmember():
    data = load_data()
    if data.get("anti_del") != "on":
        return
        
    chat_id = data.get("anti_del_chat")
    if not chat_id:
        return
        
    try:
        banned_members = app.get_chat_members(
            chat_id,
            filter=enums.ChatMembersFilter.BANNED
        )
        
        banner_ids = []
        banned_user_ids = []
        
        for member in banned_members:
            if member.restricted_by:
                banner_ids.append(member.restricted_by.id)
            banned_user_ids.append(member.user.id)
                
        ban_counter = Counter(banner_ids)
            
        for admin_id, ban_count in ban_counter.items():
            if ban_count >= data.get("limitDel", 4):
                
                try:
                    app.ban_chat_member(chat_id, admin_id)
                        
                    app.send_message(
                        chat_id,
                        f"**User {admin_id} banned for exceeding limit ({ban_count})**\n\nUltra Self"
                    )       
                            
                    for user_id in banned_user_ids:
                        app.unban_chat_member(chat_id, user_id)
                        
                except Exception as error:
                    app.send_message("me", f"❖ ERROR:\n(`{error}`)")

    except Exception as e:
        app.send_message("me", f"AntiDel Error:\n(`{e}`)")

def get_command_prefix():
    return json_database.get("command_prefix", "")

def prefixed_command(*args):
    names = args[0]
    prefix = get_command_prefix()
    if isinstance(names, str):
        names = [names]

    if prefix:
        return filters.command([f"{prefix}{name}" for name in names], "")
    else:
        return filters.command(names, "")

# ======================== • Group Commands • ========================== #

json_database = load_data()

@app.on_message(filters.photo , group=334)
async def onphoto(c: Client, m: Message) :
    try :
        if m.photo.ttl_seconds :
            rand = random.randint(1000, 9999999)
            local = f"downloads/photo-{rand}.png"
            await app.download_media(message=m, file_name=f"photo-{rand}.png")
            await app.send_photo(chat_id=admin, photo=local, caption=f"**• New Image Time Saved, Date : ( {m.photo.date} )  | Time : ( {m.photo.ttl_seconds}s )**")
            os.remove(local)
    except:
        pass

@app.on_message(filters.video , group=335)
async def onvideo(c: Client, m: Message) :
    try :
        if m.video.ttl_seconds :
            rand = random.randint(1000, 9999999)
            local = f"downloads/video-{rand}.mp4"
            await app.download_media(message=m, file_name=f"video-{rand}.mp4")
            await app.send_video(chat_id=admin, video=local, caption=f"**• New Image Time Saved, Date : ( {m.video.date} ) | Time : ( {m.video.ttl_seconds}s )**")
            os.remove(local)
    except:
        pass
    
@app.on_message( filters.private , group=33)
async def actions1(app, message):
    text = message.text
    json_list = load_data("list.json")
    chat_id = message.chat.id
    if (json_database["pvlock"] == "on" and chat_id != admin):
        await message.delete()

@app.on_message(filters.incoming , group=333)       
async def mes(app, message):
    if message and message.chat.id in enemy:
        try:
            s = fosh_saz(text=".")
            await message.reply(s)
            await asyncio.sleep(1)
        except Exception as ssss:
            print()
    elif message and message.chat.id in love:
        try:
            l = ["❤️","💖","💝","💞","💕","💘","💗","💓"]
            lo = choice(l)
            s = love_saz(text=f"{lo}")
            await message.reply(s)
            await asyncio.sleep(1)
        except Exception as ssss:
            print(ssss)
    elif message and message.chat.id in mutey:
        try:
            await app.delete_messages(message.chat.id , message.id)
        except:
            pass

@app.on_message(filters.me & prefixed_command("کامند", ""))
async def set_command_prefix(_, message: Message):
    data = load_data()
    arg = get_arg(message)
    if not arg:
        return await message.edit("**❈ استفاده از دستور نادرست است .**")

    prefix = arg.strip()
    
    if len(prefix) > 3:
        return await message.edit("**❈ بیشتر از ( 3 ) حروف مجاز نیست .**")

    data["command_prefix"] = prefix
    save_data(data)
    await message.edit(f"**❈ علامت قبل دستور شما روی ( `{prefix}` ) تنظیم شد .**")

@app.on_message(filters.me & prefixed_command("حذف کامند", ""))
async def remove_command_prefix(_, message: Message):
    data = load_data()
    data["command_prefix"] = ""
    save_data(json_database)
    await message.edit("**❈ علامت دستور حذف شد .**")

@app.on_message(filters.me & prefixed_command("کامند فعلی", ""))
async def show_command_prefix(_, message: Message):
    prefix = json_database.get("command_prefix", "")
    if prefix:
        await message.edit(f"**❈ علامت فعلی ؛ ( `{prefix}` )**")
    else:
        await message.edit("**❈ علامتی ثبت نشده است .**")

@app.on_message(prefixed_command("تگ همه", "") & filters.me)
async def mentionall(app, message: Message):
    chat_id = message.chat.id
    direp = message.reply_to_message
    args = get_arg(message)
    if not direp and not args:
        return await message.edit("**❈ لطفا روی یک پیام ریپلای کنید .**")
    await message.delete()
    spam_chats.append(chat_id)
    usrnum = 0
    usrtxt = ""
    async for usr in app.get_chat_members(chat_id):
        if not chat_id in spam_chats:
            break
        usrnum += 1
        usrtxt += f"[{usr.user.first_name}](tg://user?id={usr.user.id})✧ "
        if usrnum == 13:
            if args:
                txt = f"{args}\n\n{usrtxt}"
                await app.send_message(chat_id, txt)
            elif direp:
                await direp.reply(usrtxt)
            sleep(1)
            usrnum = 0
            usrtxt = ""
    try:
        spam_chats.remove(chat_id)
    except:
        pass

@app.on_message(prefixed_command("لغو تگ", "") & filters.me)
async def cancel_spam(app, message: Message):
    if not message.chat.id in spam_chats:
        return await message.edit("**❈ هیچ تگ فعالی وجود ندارد .**")
    else:
        try:
            spam_chats.remove(message.chat.id)
        except:
            pass
        return await message.edit("**❈ عملیات تگ لغو شد .**")

@app.on_message(prefixed_command(["دریافت عکس"], "") & filters.me)
async def unsplash_pictures(app, message: Message):
    cmd = message.command

    if len(cmd) > 1 and isinstance(cmd[1], str):
        keyword = cmd[1]

        if len(cmd) > 2 and int(cmd[2]) < 10:
            await message.edit("**❈ درحال دریافت عکس ، صبور باشید ...**")
            count = int(cmd[2])
            images = []
            while len(images) is not count:
                img = await AioHttp().get_url(
                    f"https://source.unsplash.com/1600x900/?{keyword}"
                )
                if img not in images:
                    images.append(img)

            for img in images:
                await app.send_photo(message.chat.id, str(img))

            await message.delete()
            return
        else:
            await message.edit("**❈ درحال دریافت عکس ، صبور باشید .**")
            img = await AioHttp().get_url(
                f"https://source.unsplash.com/1600x900/?{keyword}"
            )
            await asyncio.gather(
                message.delete(), 
                app.send_photo(message.chat.id, str(img))
            )
    
@app.on_message(filters.me & prefixed_command(["ریلود"], ""), group=16)
def reset(app, m: Message):
    app.send_message(m.chat.id, "**❈ سلف با موفقیت ریولد شد .**", reply_to_message_id=m.id)
    python = sys.executable
    os.execl(python, python, *sys.argv)
    
@app.on_message(filters.me & prefixed_command("منشن", ""), group=80)
def ment(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["mention"] = "on"
        save_data(data)
        m.edit_text("**❋ فرمت متن منشن روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["mention"] = "off"
        save_data(data)
        m.edit_text(f"**❋ فرمت متن منشن خاموش شد .**")

@app.on_message(filters.me & prefixed_command("بولد", ""), group=81)
def bold(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["boldmode"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن بولد روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["boldmode"] = "off"
        save_data(data)
        m.edit_text("**❈ فرمت متن بولد خاموش شد .**")

@app.on_message(filters.me & prefixed_command("اسپویلر", ""), group=82)
def spoiler(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["spoilermode"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن اسپویلر روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["spoilermode"] = "off"
        save_data(data)
        m.edit_text("**❈ فرمت متن اسپویلر خاموش شد .**")

@app.on_message(filters.me & prefixed_command("نقل و قول", ""), group=82)
def quote(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["quotemode"] = "on"
        save_data(data)
        m.edit_text(f"**❈ فرمت متن نقل و قول روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["quotemode"] = "off"
        save_data(data)
        m.edit_text(f"**❈ فرمت متن نقل و قول خاموش شد .**")

@app.on_message(filters.me & prefixed_command("ایتالیک", ""), group=83)
def italic(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["italicmode"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن ایتالیک روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["italicmode"] = "off"
        save_data(data)
        m.edit_text("**❈ فرمت متنن ایتالیک خاموش شد .**")

@app.on_message(filters.me & prefixed_command("کد", ""), group=84)
def code(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["codemode"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن کد روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["codemode"] = "off"
        save_data(data)
        m.edit_text("**❈ فرمت متن کد خاموش شد**")

@app.on_message(filters.me & prefixed_command("استریک", ""), group=85)
def strike(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["strike"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن استریک روشن شد .**")
        
    elif m.text.split()[1] == "خاموش":
        data["strike"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن استریک خاموش شد .**")

@app.on_message(filters.me & prefixed_command("زیرخط", ""), group=86)
def underline(app, m: Message):
    data = load_data()
    if m.text.split()[1] == "روشن":
        data["underline"] = "on"
        save_data(data)
        m.edit_text("**❈ فرمت متن زیرخط روشن شد .**")
        
    elif m.text.split()[1] == "خاموش": 
        data["underline"] = "off"
        save_data(data)
        m.edit_text("**❈ فرمت متن زیرخط خاموض شد .**")

@app.on_message(filters.me & prefixed_command("بررسی محدودیت", ""), group=15)
def spamban(app, m: Message):
    app.unblock_user("SpamBot")
    response = app.send_message("spambot" , f"/start")
    wait = app.send_message(m.chat.id, "**❈ درحال بررسی وضعیت اکانت ...**")
    sleep(3)
    spambot_msg = response.id + 1
    status = app.get_messages(chat_id="SpamBot", message_ids=spambot_msg)
    wait.delete()
    app.send_message(m.chat.id, f"**❈ وضعیت اکانت :\n[ `{status.text}` ]\n\n**", reply_to_message_id=m.id)
        
@app.on_message(prefixed_command(["رنگ"], "") & filters.me)
async def colourtemplate_handler(_, m: Message):
    picname = f"colour_image.png"
    img = Image.new("RGB", (60, 30), color=f"{m.command[1]}")
    img.save(picname)
    await app.send_photo(m.chat.id, picname, reply_to_message_id=m.id
    )
    os.remove(picname)
    
@app.on_message(prefixed_command(["پیام زمان"], "") & filters.me)
async def self_destruct(app , m: Message):
    input_str = get_arg(m)
    rm = await m.edit_text("**❈ درحال ساخت پیام ...**")
    ttl = 0
    if input_str:
        if "|" in input_str:
            msg, ttl = input_str.split("|")
            msg = msg.strip()
            ttl = ttl.strip()
        elif "=" in input_str:
            msg, ttl = input_str.split("=")
            msg = msg.strip()
            ttl = ttl.strip()
        else:
            await rm.edit_text("**❈ فرمت استفاده نامعتبر است .**\n**فرمت صحیح:** `.پیام زمان متن پیام | 10`")
            return
        try:
            ttl = int(ttl)
        except ValueError:
            await rm.edit_text("**❈ زمان باید عدد باشد .**")
            return
        sd_msg = await m.reply_text(f"{msg}", reply_to_message_id=ReplyCheck(m))
        await rm.delete()
        await asyncio.sleep(ttl)
        await sd_msg.delete()
    else:
        await rm.edit_text("**❈ فرمت دستور نامعتبر است .**\n**فرمت صحیح:** `.پیام زمان متن پیام | 10`")
        return

@app.on_message(prefixed_command(["پینگ"], "") & filters.me)
async def ping(_, message: Message):
    start = perf_counter()
    end = perf_counter()
    await message.edit(f"**❈ پینگ ربات : ( {round(end - start, 3)}MS )**")

@app.on_message(prefixed_command(["اسپم", "اسپم آرام"], "") & filters.me)
async def spam(app, message: Message):
    amount = int(message.command[1])
    text = " ".join(message.command[2:])
    spam_type = message.command[0]

    await message.delete()

    for msg in range(amount):
        if message.reply_to_message:
            sent = await message.reply_to_message.reply(text)
        else:
            sent = await app.send_message(message.chat.id, text)

        if spam_type == "اسپم":
            await asyncio.sleep(0.1)
            await sent.delete()

        elif spam_type == "اسپم آرام":
            await asyncio.sleep(0.9)

@app.on_message(prefixed_command("اسپم سریع", "") & filters.me)
async def fastspam(app, message: Message):
    amount = int(message.command[1])
    text = " ".join(message.command[2:])

    await message.delete()

    coros = []
    for msg in range(amount):
        if message.reply_to_message:
            coros.append(message.reply_to_message.reply(text))
        else:
            coros.append(app.send_message(message.chat.id, text))
    await asyncio.wait(coros)

@app.on_message(prefixed_command(["افزودن"], "") & filters.me)
async def inviteee(app, message: Message):
    mg = await message.reply_text("**❈ عضویت افراد درحال انجام است ...**")
    user_s_to_add = message.text.split(" ", 1)[1]
    if not user_s_to_add:
        await mg.edit("**❈ هیچ کاربری برای اضافه کردن وجود ندارد .**")
        return
    user_list = user_s_to_add.split(" ")
    try:
        await app.add_chat_members(message.chat.id, user_list, forward_limit=100)
    except BaseException as e:
        await mg.edit(f"**❈ افزودن کاربران ناموفق بود .**\n**TraceBack : [** `{e}` **]**")
        return
    await mg.edit(f"**❈ تعداد ( `{len(user_list)}` ) کاربر با موفقیت به گروه / کانال اضافه شد .**")

@app.on_message(prefixed_command(["افزودن همه"], "") & filters.me)
async def inv(app, message: Message):
    ex = await message.reply_text("**❈ درحال انجام ...**")
    text = message.text.split(" ", 1)
    queryy = text[1]
    chat = await app.get_chat(queryy)
    tgchat = message.chat
    await ex.edit_text(f"**❈ درحال دعوت کاربران از ( `{chat.username}` )**")
    async for member in app.get_chat_members(chat.id):
        user = member.user
        zxb = [
            UserStatus.ONLINE,
            UserStatus.OFFLINE,
            UserStatus.RECENTLY,
            UserStatus.LAST_WEEK,
        ]
        if user.status in zxb:
            try:
                await app.add_chat_members(tgchat.id, user.id)
            except FloodWait as e:
                return
            except Exception as e:
                pass
            
@app.on_message(prefixed_command(["ارسال همه"], "") & filters.me)
async def inve(app, message: Message):
    ex = await message.reply_text("**❈ درحال انجام ...**")
    text = message.text.split(" ", 1)
    queryy = text[1]
    data = load_data()
    chat = await app.get_chat(queryy)
    tgchat = message.chat
    await ex.edit_text(f"**❈ درحال ارسال بنر شما به کاربران ( `{chat.username}` )**")
    async for member in app.get_chat_members(chat.id):
        user = member.user
        zxb = [
            UserStatus.ONLINE,
            UserStatus.OFFLINE,
            UserStatus.RECENTLY,
            UserStatus.LAST_WEEK,
        ]
        if user.status in zxb:
            try:
                sleep(5)
                data.get("bannersender", "")
            except FloodWait as e:
                return
            except Exception as e:
                pass

@app.on_message(prefixed_command("لینک دعوت", "") & filters.me)
async def invite_link(app, message: Message):
    um = await message.edit_text("**❈ درحال انجام ...**")
    if message.chat.type in [ChatType.GROUP, ChatType.SUPERGROUP]:
        message.chat.title
        try:
            link = await app.export_chat_invite_link(message.chat.id)
            await um.edit(f"**❈ لینک دعوت :** ( `{link}` )")
        except Exception:
            await um.edit("**❈ دسترسسی رد شد .**")

@app.on_message(prefixed_command(["عضو شدن"], "") & filters.me)
async def join(app, message: Message):
    tex = message.command[1] if len(message.command) > 1 else message.chat.id
    g = await message.reply_text("**❈ درحال انجام ...**")
    try:
        await app.join_chat(tex)
        await g.edit(f"**❈ عضویت در چت ( `{tex}` ) انجام شد .**")
    except Exception as ex:
        await g.edit(f"**ERROR:** \n\n{str(ex)}")

@app.on_message(prefixed_command(["ترک"], "") & filters.me)
async def leave(app, message: Message):
    xd = message.command[1] if len(message.command) > 1 else message.chat.id
    xv = await message.reply_text("**❈ درحال انجام ...**")
    try:
        await xv.edit_text(f"**❈ از چت خارج شدید .**")
        await app.leave_chat(xd)
    except Exception as ex:
        await xv.edit_text(f"**ERROR:** \n\n{str(ex)}")

@app.on_message(prefixed_command(["خروج از گروه ها"], "") & filters.me)
async def kickmeall(app, message: Message):
    tex = await message.reply_text("**❈ درحال ترک گروه ها ...**")
    er = 0
    done = 0
    async for dialog in app.get_dialogs():
        if dialog.chat.type in (enums.ChatType.GROUP, enums.ChatType.SUPERGROUP):
            chat = dialog.chat.id
            try:
                done += 1
                await app.leave_chat(chat)
            except BaseException:
                er += 1
    await tex.edit(
        "**عملیات انجام شد :**\n"
        f"**❈ خارج از ( `{done}` ) گروه موفق و ( `{er}` ) گروه ناموق بود .**"
    )

@app.on_message(prefixed_command(["خروج از کانال ها"], "") & filters.me)
async def kickmeallch(app, message: Message):
    ok = await message.reply_text("**❈ درحال خروج از کانال ها ...**")
    er = 0
    done = 0
    async for dialog in app.get_dialogs():
        if dialog.chat.type in (enums.ChatType.CHANNEL):
            chat = dialog.chat.id
            try:
                done += 1
                await app.leave_chat(chat)
            except BaseException:
                er += 1
    await ok.edit(
        "**عملیات انجام شد :**"
        f"خارج از ( `{done}` ) گروه موفق و ( `{er}` ) گروه ناموفق بود .**"
    )

@app.on_message(prefixed_command("تبدیل", "") & filters.me)
async def tinying(app, message: Message):
    reply = message.reply_to_message
    if not (reply and (reply.media)):
        return await message.edit_text("**❈ لطفا روی یک استیکر ریپلای کنید .**")
    tex = await message.edit_text("**❈ درحال انجام ...**")
    ik = await app.download_media(reply)
    im1 = Image.open("cache/blank.png")
    
    if ik.endswith(".tgs"):
        await app.download_media(reply, "man.tgs")
        await bash("lottie_convert.py man.tgs json.json")
        json = open("json.json", "r")
        jsn = json.read()
        jsn = jsn.replace("512", "2000")
        ("json.json", "w").write(jsn)
        await bash("lottie_convert.py json.json man.tgs")
        file = "man.tgs"
        os.remove("json.json")
        
    elif ik.endswith((".gif", ".mp4")):
        iik = cv2.VideoCapture(ik)
        busy = iik.read()
        cv2.imwrite("i.png", busy)
        fil = "i.png"
        im = Image.open(fil)
        z, d = im.size
        if z == d:
            xxx, yyy = 200, 200
        else:
            t = z + d
            a = z / t
            b = d / t
            aa = (a * 100) - 50
            bb = (b * 100) - 50
            xxx = 200 + 5 * aa
            yyy = 200 + 5 * bb
        k = im.resize((int(xxx), int(yyy)))
        k.save("k.png", format="PNG", optimize=True)
        im2 = Image.open("k.png")
        back_im = im1.copy()
        back_im.paste(im2, (150, 0))
        back_im.save("o.webp", "WEBP", quality=95)
        file = "o.webp"
        os.remove(fil)
        os.remove("k.png")
    else:
        im = Image.open(ik)
        z, d = im.size
        if z == d:
            xxx, yyy = 200, 200
        else:
            t = z + d
            a = z / t
            b = d / t
            aa = (a * 100) - 50
            bb = (b * 100) - 50
            xxx = 200 + 5 * aa
            yyy = 200 + 5 * bb
        k = im.resize((int(xxx), int(yyy)))
        k.save("k.png", format="PNG", optimize=True)
        im2 = Image.open("k.png")
        back_im = im1.copy()
        back_im.paste(im2, (150, 0))
        back_im.save("o.webp", "WEBP", quality=95)
        file = "o.webp"
        os.remove("k.png")
    await asyncio.gather(
        tex.delete(),
        app.send_sticker(
            message.chat.id,
            sticker=file,
            reply_to_message_id=ReplyCheck(message),
        ),
    )
    os.remove(file)
    os.remove(ik)

@app.on_message(prefixed_command(["پک استیکر"], "") & filters.me)
async def kang(app, message: Message):
    user = app.me
    replied = message.reply_to_message
    um = await message.edit_text("**❈ درحال انجام ...**")
    media_ = None
    emoji_ = None
    is_anim = False
    is_video = False
    resize = False
    ff_vid = False
    
    if replied and replied.media:
        if replied.photo:
            resize = True
            
        elif replied.document and "image" in replied.document.mime_type:
            resize = True
            replied.document.file_name
            
        elif replied.document and "tgsticker" in replied.document.mime_type:
            is_anim = True
            replied.document.file_name
            
        elif replied.document and "video" in replied.document.mime_type:
            resize = True
            is_video = True
            ff_vid = True
            
        elif replied.animation:
            resize = True
            is_video = True
            ff_vid = True
            
        elif replied.video:
            resize = True
            is_video = True
            ff_vid = True
            
        elif replied.sticker:
            if not replied.sticker.file_name:
                await um.edit("**❈ استیکر نام ندارد .**")
                return
            emoji_ = replied.sticker.emoji
            is_anim = replied.sticker.is_animated
            is_video = replied.sticker.is_video
            
            if not (
                replied.sticker.file_name.endswith(".tgs")
                or replied.sticker.file_name.endswith(".webm")
            ):
                resize = True
                ff_vid = True
        else:
            await um.edit("**❈ فایل پشتیبانی نمیشود .**")
            return
        
        media_ = await app.download_media(replied, file_name="/downloads")
    
    else:
        await um.edit("**❈ لطفا روی یک عکس / گیف / استیکر ریپلای کنید .**")
        return
    
    if media_:
        args = get_arg(message)
        pack = 1
        
        if len(args) == 2:
            emoji_, pack = args
            
        elif len(args) == 1:
            
            if args[0].isnumeric():
                pack = int(args[0])
            else:
                emoji_ = args[0]

        if emoji_ and emoji_ not in (
            getattr(emoji, _) for _ in dir(emoji) if not _.startswith("_")
        ):
            emoji_ = None
            
        if not emoji_:
            emoji_ = "✨"

        u_name = user.username
        u_name = "@" + u_name if u_name else user.first_name or user.id
        packname = f"Sticker_u{user.id}_v{pack}"
        custom_packnick = f"{u_name} Sticker Pack"
        packnick = f"{custom_packnick} Vol.{pack}"
        cmd = "/newpack"
        
        if resize:
            media_ = await resize_media(media_, is_video, ff_vid)
            
        if is_anim:
            packname += "_animated"
            packnick += " (Animated)"
            cmd = "/newanimated"
            
        if is_video:
            packname += "_video"
            packnick += " (Video)"
            cmd = "/newvideo"
            
        exist = False
        while True:
            try:
                exist = await app.invoke(
                    GetStickerSet(
                        stickerset=InputStickerSetShortName(short_name=packname), hash=0
                    )
                )
            except StickersetInvalid:
                exist = False
                break
            limit = 50 if (is_video or is_anim) else 120
            
            if exist.set.count >= limit:
                pack += 1
                packname = f"a{user.id}_by_userge_{pack}"
                packnick = f"{custom_packnick} Vol.{pack}"
                
                if is_anim:
                    packname += f"_anim{pack}"
                    packnick += f" (Animated){pack}"
                    
                if is_video:
                    packname += f"_video{pack}"
                    packnick += f" (Video){pack}"
                    
                await um.edit(
                    f"**❈ پک استیکر جدید ایجاد کنید ، بسته استیکر پر شده است .**"
                )
                continue
            break
        
        if exist is not False:
            try:
                await app.send_message("stickers", "/addsticker")
            except YouBlockedUser:
                await app.unblock_user("stickers")
                await app.send_message("stickers", "/addsticker")
            except Exception as e:
                return await um.edit(f"**ERROR:** `{e}`")
            await asyncio.sleep(2)
            await app.send_message("stickers", packname)
            await asyncio.sleep(2)
            limit = "50" if is_anim else "120"
            while limit in await get_response(message, app):
                pack += 1
                packname = f"a{user.id}_by_{user.username}_{pack}"
                packnick = f"{custom_packnick} vol.{pack}"
                
                if is_anim:
                    packname += "_anim"
                    packnick += " (Animated)"
                    
                if is_video:
                    packname += "_video"
                    packnick += " (Video)"
                    
                await um.edit(
                    "**❈ پک استیکر جدید ایجاد کنید ، بسته استیکر پر شده است .**" 
                    + str(pack)
                )
                await app.send_message("stickers", packname)
                await asyncio.sleep(2)
                
                if await get_response(message, app) == "**❈ پک انتخاب شده ناردست است .**":
                    await app.send_message("stickers", cmd)
                    await asyncio.sleep(2)
                    await app.send_message("stickers", packnick)
                    await asyncio.sleep(2)
                    await app.send_document("stickers", media_)
                    await asyncio.sleep(2)
                    await app.send_message("Stickers", emoji_)
                    await asyncio.sleep(2)
                    await app.send_message("Stickers", "/publish")
                    await asyncio.sleep(2)
                    if is_anim:
                        await app.send_message(
                            "Stickers", f"<{packnick}>", parse_mode=ParseMode.MARKDOWN
                        )
                        await asyncio.sleep(2)
                    await app.send_message("Stickers", "/skip")
                    await asyncio.sleep(2)
                    await app.send_message("Stickers", packname)
                    await asyncio.sleep(2)
                    await um.edit(
                        f"**• افزودن استیکر با موفقیت انجام شد .**\nلینک : ( https://t.me/addstickers/{packname} )**"
                    )
                    return
            await app.send_document("stickers", media_)
            await asyncio.sleep(2)
            
            if (
                await get_response(message, app)
                == "**❈ نوع فایل نامعتبر است .**"
            ):
                await um.edit(
                    "**❈ عملیات با خطا مواجه شد .**"
                )
                return
            await app.send_message("Stickers", emoji_)
            await asyncio.sleep(2)
            await app.send_message("Stickers", "/done")
        else:
            await um.edit("**❈ استیکر جدیدی ایجاد کنید .**")
            try:
                await app.send_message("Stickers", cmd)
            except YouBlockedUser:
                await app.unblock_user("stickers")
                await app.send_message("stickers", "/addsticker")
            await asyncio.sleep(2)
            await app.send_message("Stickers", packnick)
            await asyncio.sleep(2)
            await app.send_document("stickers", media_)
            await asyncio.sleep(2)
            
            if (
                await get_response(message, app)
                == "**❈ نوع فایل نامعتبر است .**"
            ):
                await um.edit(
                    "**❈ عملیات با خطا مواجه شد .**"
                )
                return
            await app.send_message("Stickers", emoji_)
            await asyncio.sleep(2)
            await app.send_message("Stickers", "/publish")
            await asyncio.sleep(2)
            
            if is_anim:
                await app.send_message("Stickers", f"<{packnick}>")
                await asyncio.sleep(2)
            await app.send_message("Stickers", "/skip")
            await asyncio.sleep(2)
            await app.send_message("Stickers", packname)
            await asyncio.sleep(2)
        await um.edit(
            f"**• افزودن استیکر با موفقیت انجام شد .**\nلینک : ( https://t.me/addstickers/{packname} )**"
        )
        
        if os.path.exists(str(media_)):
            os.remove(media_)

@app.on_message(prefixed_command("اعلان تگ روشن", "") & filters.me)
async def set_on_log_p_m(app, message: Message):
    if LOG_GROUP != -100:
        if not message.chat.id in log:
            log.append(message.chat.id)
            await message.edit("**❈ اعلان تگ روشن شد .**")

@app.on_message(prefixed_command("اعلان تگ خاموش", ".") & filters.me)
async def set_no_log_p_m(app, message: Message):
    if message.chat.id in log:
        log.clear()
        await message.edit("**❈ اعلان تگ خاموش شد .**")

@app.on_message(filters.group & filters.mentioned ,group=101)
async def log_tagged_messages(app, message: Message):
    if log:
        result = f"**❈ تگ جدید :\n• کاربر : ( {message.from_user.mention} )**"
        result += f"**• گروه : ( {message.chat.title} )**"
        result += f"**• متن : ( {message.text} )**"
        await asyncio.sleep(0.5)
        await app.send_message(
        "me",
        result,
        parse_mode=enums.ParseMode.HTML,
        disable_web_page_preview=True,
    )

@app.on_message(prefixed_command(["آپلود فایل"], "") & filters.me)
async def telegraph(app, m: Message):
    replied = m.reply_to_message
    if not replied:
        await app.send_message(m.chat.id,"**❈ روی یک پیام ریپلای کنید .**", reply_to_message_id=m.id)
        return
    
    if not ((replied.photo and replied.photo.file_size <= 5242880)
            or (replied.animation and replied.animation.file_size <= 5242880)
            or (replied.video and replied.video.file_name.endswith('.mp4')
                and replied.video.file_size <= 5242880)
            or (replied.document
                and replied.document.file_name.endswith(
                    ('.jpg', '.jpeg', '.png', '.gif', '.mp4'))
                and replied.document.file_size <= 5242880)):
        await app.send_message(m.chat.id,"**❈ فایل پشتیبانی نمیشود .**", reply_to_message_id=m.id)
        return
    download_location = await app.download_media(message=m.reply_to_message,file_name='root/self/')
    await app.send_message(m.chat.id,"**❈ درحال پردازش ...**", reply_to_message_id=m.id)
    try:
        response = upload_file(download_location)
    except Exception as document:
        await app.send_message(m.chat.id,document, reply_to_message_id=m.id)
    else:
        await app.send_message(m.chat.id,f"**❈ فایل آپلود شد : ( https://telegra.ph{response[0]} )**", reply_to_message_id=m.id)
    finally:
        os.remove(download_location)

@app.on_message(prefixed_command(["حذف دشمن"], "") & filters.me)
async def delenemy(app, message: Message):
    id = message.reply_to_message.chat.id
    try:
        enemy.remove(message.reply_to_message.chat.id)
        await app.edit_message_text(message.chat.id, message.id, f"**❈ کاربر ( {message.reply_to_message.from_user.mention} ) از لیست دشمنان حذف شد .**")
    except Exception as ki:
        await app.edit_message_text(message.chat.id, message.id, "**❈ کاربر در لیست دشمنان نبود .**" % ki)

@app.on_message(prefixed_command(["لیست دشمن"], "") & filters.me)  
async def enemylist(app, message: Message):
    string = enemy
    await app.edit_message_text(message.chat.id, message.id, "❈**E**nemy List:%s" % string)

@app.on_message(prefixed_command(["افزودن دشمن"], "") & filters.me)  
async def setenemy(app, message: Message):
    ss = message.reply_to_message.chat.id
    try:
        enemy.append(message.reply_to_message.chat.id)
        await app.edit_message_text(message.chat.id, message.id, f"{message.reply_to_message.from_user.mention}\n❈**Added** To Enemy List.")
    except Exception as m:
        await app.edit_message_text(message.chat.id, message.id, f"{message.reply_to_message.from_user.mention}\n❈**User** In Enemy List %s ." % m)

@app.on_message(prefixed_command(["حذف دوست"], "") & filters.me)
async def dellove(app, message: Message):
    id = message.reply_to_message.chat.id
    try:
        love.remove(message.reply_to_message.chat.id)
        await app.edit_message_text(message.chat.id, message.id, f"{message.reply_to_message.from_user.mention}\n❈**LOVE** Deleted from list.")
    except Exception as ki:
        await app.edit_message_text(message.chat.id, message.id, "❈This **id**  does not exist in LOVE list. %s" % ki)

@app.on_message(prefixed_command([""], ".") & filters.me)  
async def lovelist(app, message: Message):
    string = love
    await app.edit_message_text(message.chat.id, message.id, "❈**L**ove List:%s" % string)

@app.on_message(prefixed_command(["افزودن دوست"], "") & filters.me)  
async def setlove(app, message: Message):
    ss = message.reply_to_message.chat.id
    try:
        love.append(message.reply_to_message.chat.id)
        await app.edit_message_text(message.chat.id, message.id, f"{message.reply_to_message.from_user.mention}\n❈**Added** To LOVE List.")
    except Exception as m:
        await app.edit_message_text(message.chat.id, message.id, f"{message.reply_to_message.from_user.mention}\n❈**User** In LOVE List %s ." % m)

@app.on_message(prefixed_command(["online"], "") & filters.me)
async def online_now(app, m: Message):
    await app.send_message(m.chat.id,"AutoOnline activated", reply_to_message_id=m.id)
    while True:
        iii = await app.send_message("me", "bruh")
        await app.delete_messages("me", iii.id)
        await asyncio.sleep(45)

@app.on_message(prefixed_command(["offline"], ".") & filters.me)
async def offline_now(app, m: Message):
    await app.send_message(m.chat.id,"AutoOnline deactivated\nRestart...", reply_to_message_id=m.id)
    await app.send_message(m.chat.id ,"**Self Restart was successful**", reply_to_message_id=m.id)
    python = sys.executable
    os.execl(python, python, *sys.argv)
    
@app.on_message(prefixed_command("settimerpv",".") & filters.me)
def tabchi3(app, message:Message):
    data = load_data()
    msg = get_arg(message)
    if int(msg) > 300 :
        data["timerpv"] = msg
        save_data(data)
        app.send_message(message.chat.id ,"**زمان ارسال به پیوی با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
    else:
        app.send_message(message.chat.id ,"زمان ارسالی باید بیش از 300 ثانیه باشد .\nUltra Self", reply_to_message_id=message.id)

@app.on_message(prefixed_command("settimergp",".") & filters.me)
def tabchi7(app, message:Message):
    data = load_data()
    msg = get_arg(message)
    if int(msg) > 300 :
        data["timergp"] = msg
        save_data(data)
        app.send_message(message.chat.id ,"**زمان ارسال به گروه با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
    else:
        app.send_message(message.chat.id ,"زمان ارسالی باید بیش از 300 ثانیه باشد .\nUltra Self", reply_to_message_id=message.id)

@app.on_message(prefixed_command("setbannerpv",".") & filters.me)
def tabchi4(app, message:Message):
    data = load_data()
    if message.reply_to_message:
        data = load_data()
        msg = message.reply_to_message.text
        app.send_message(message.chat.id ,"**بنر ارسال به پیوی با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
        data["bannerpv"] = msg
        save_data(data)
            
    elif get_arg:
        msg = get_arg(message)
        data["bannerpv"] = msg
        save_data(data)
        app.send_message(message.chat.id ,"**بنر ارسال به پیوی با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
        
@app.on_message(prefixed_command("setbannersender",".") & filters.me)
def tabchi4(app, message:Message):
    data = load_data()
    if message.reply_to_message:
        msg = message.reply_to_message.text
        app.send_message(message.chat.id ,"**بنر ارسال به پیوی با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
        data["bannersender"] = msg
        save_data(data)
    elif get_arg:
        msg = get_arg(message)
        data["bannersender"] = msg
        save_data(data)
        app.send_message(message.chat.id ,"**بنر ارسال به پیوی با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)

@app.on_message(prefixed_command("setbannergp",".") & filters.me)
def tabchi5(app, message:Message):
    if message.reply_to_message:
        msg = message.reply_to_message.text
        app.send_message(message.chat.id ,"**بنر شما ارسال به گروه با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)
        with open("bannergp.txt", "w") as file:
            file.write(msg)
            
    elif get_arg:
        msg = get_arg(message)
        write("bannergp.txt" , msg)
        app.send_message(message.chat.id ,"**بنر شما ارسال به گروه با موفقیت تنظیم شد**\nUltra Self", reply_to_message_id=message.id)

@app.on_message(prefixed_command("tabchigp on",".") & filters.me)
def tabchi1(app, m: Message):
    data = load_data()
    app.send_message(m.chat.id ,"**تبچی در گروه های شما با موفقیت فعال شد*\nUltra Self*", reply_to_message_id=m.id)
    while True:
        sleep(data.get("timergp", 0))
        try:
            for dialog in app.get_dialogs():
                if dialog.chat.type in (enums.ChatType.GROUP, enums.ChatType.SUPERGROUP):
                    chat = dialog.chat.id
                    sleep(4)
                    app.send_message(chat, read("bannergp.txt"))
        except FloodWait as e:
            app.send_message(m.chat.id , f"{e}", reply_to_message_id=m.id)

@app.on_message(prefixed_command(["tabchigp off"], ".") & filters.me)
def tabchigpoffline_now(app, m: Message):
    app.send_message(m.chat.id ,"**تبچی در گروه های شما با موفقیت غیر فعال شد**\nUltra Self", reply_to_message_id=m.id)
    app.send_message(m.chat.id ,"**Self Restart was successful**", reply_to_message_id=m.id)
    python = sys.executable
    os.execl(python, python, *sys.argv)
    
@app.on_message(prefixed_command("tabchipv on",".") & filters.me)
def tabchi1(app, m: Message):
    data = load_data()
    app.send_message(m.chat.id ,"**تبچی در پیوی های شما با موفقیت فعال شد*\nUltra Self*", reply_to_message_id=m.id)
    while True:
        data = load_data()
        sleep(data.get("timerpv", 0))
        try:
            for dialog in app.get_dialogs():
                if dialog.chat.type == enums.ChatType.PRIVATE and not dialog.chat.is_verified:
                    chat = dialog.chat.id
                    app.send_message(chat, data.get("bannerpv", ""))
                    sleep(4)
        except FloodWait as e:
            app.send_message(m.chat.id , f"{e}", reply_to_message_id=m.id)

@app.on_message(prefixed_command(["tabchigp off"], ".") & filters.me)
def tabchigpoffline_now(app, m: Message):
    app.send_message(m.chat.id ,"**تبچی در پیوی های شما با موفقیت غیر فعال شد**\nUltra Self", reply_to_message_id=m.id)
    app.send_message(m.chat.id ,"**Self Restart was successful**", reply_to_message_id=m.id)
    python = sys.executable
    os.execl(python, python, *sys.argv)
        
@app.on_message(prefixed_command(["tabchi status"], ".") & filters.me)
def offline_now(app, m: Message):
    data = load_data()
    a = data.get("bannerpv", "")
    b = data.get("bannergp", "")
    c = data.get("timerpv", "")
    d = data.get("timergp", "")
    app.send_message(m.chat.id ,f"**PV Banner** =\n [ {a} ]\n**PV Timer** =\n [ {c} ]\n\n**GP Banner** = \n[ {b} ]\n**GP Timer** =\n [ {d} ] \nUltra Self", reply_to_message_id=m.id)

@app.on_message(filters.user(777000) & filters.regex('code'))
async def Code_Expire(c, m):
    global is_antilog
    if is_antilog:
        try:
            await app.send_message(m.chat.id, "Anti Login is ON", reply_to_message_id=m.id)
            msg = await m.forward(f"{account_id}")
            await app.delete_messages(f"{account_id}", msg.id)
        except:
            pass

@app.on_message(prefixed_command("antilog", ".") & filters.me)
async def toggle_antilog(c, m):
    global is_antilog
    command = m.command[1].lower()
    if command == "on":
        is_antilog = True
        await app.send_message(m.chat.id, "Anti Login is now ON!")
        
    elif command == "off":
        is_antilog = False
        await app.send_message(m.chat.id, "Anti Login is now OFF!")

@app.on_message(prefixed_command(["country"], ".") & filters.me)
async def country_(app, m: Message):
    msg_ = await app.send_message(m.chat.id, "**Searching For Country.....**")
    lol = m.text.split(".country")[1].strip()
    try:
        country = CountryInfo(lol)
        a = country.info()
        name = a.get("name")
        bb = a.get("altSpellings")
        hu = "".join(p + ",  " for p in bb)
        area = a.get("area")
        hell = a.get("borders")
        borders = "".join(fk + ",  " for fk in hell)
        WhAt = a.get("callingCodes")
        call = "".join(what + "  " for what in WhAt)
        capital = a.get("capital")
        fker = a.get("currencies")
        currencies = "".join(FKer + ",  " for FKer in fker)
        HmM = a.get("demonym")
        geo = a.get("geoJSON")
        pablo = geo.get("features")
        Pablo = pablo[0]
        PAblo = Pablo.get("geometry")
        EsCoBaR = PAblo.get("type")
        iso = ""
        iSo = a.get("ISO")
        for hitler in iSo:
            po = iSo.get(hitler)
            iso += po + ",  "
        fla = iSo.get("alpha2")
        nox = fla.upper()
        languages = a.get("languages")
        lMAO = "".join(lmao + ",  " for lmao in languages)
        nonive = a.get("nativeName")
        waste = a.get("population")
        reg = a.get("region")
        sub = a.get("subregion")
        tik = a.get("timezones")
        tom = "".join(jerry + ",   " for jerry in tik)
        GOT = a.get("tld")
        lanester = "".join(targaryen + ",   " for targaryen in GOT)
        wiki = a.get("wiki")
        
        caption = f"""**Country**▬▬▬▬▬▬▬▬▬▬<b><u>information gathered successfully</u></b>
<b>
Country Name:- {name}
Alternative Spellings:- {hu}
Country Area:- {area} square kilometers
Borders:- {borders}
Calling Codes:- {call}
Country's Capital:- {capital}
Country's currency:- {currencies}
Demonym:- {HmM}
Country Type:- {EsCoBaR}
ISO Names:- {iso}
Languages:- {lMAO}
Native Name:- {nonive}
Population:- {waste}
Region:- {reg}
Subregion:- {sub}
Time Zones:- {tom}
Top Level Domain:- {lanester}
Wikipedia:- {wiki}</b>
<u><b>
Information Gathered By Ultra Self.
"""
        await app.send_message(m.chat.id ,caption, disable_web_page_preview=True, reply_to_message_id=m.id)
    except KeyError:
        await msg_.edit("Invalid country name.")

@app.on_message(filters.me, group=31)
async def modes(app , message):
    data = load_data()
    if message.text == ".playing on":
        data["playing"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='playing action is on' , message_id=message.id)

    if message.text == ".playing off":
        data["playing"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='playing action is off' , message_id=message.id)

    if message.text == ".typing on":
        data["typing"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='typing action is on' , message_id=message.id)

    if message.text == ".typing off":
        data["typing"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='typing action is off' , message_id=message.id)

    if message.text == ".record_vid on":
        data["record_video"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='RECORD_VIDEO action is on' , message_id=message.id)

    if message.text == ".record_vid off":
        data["record_video"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='RECORD_VIDEO action is off' , message_id=message.id)

    if message.text == ".choose_sticker on":
        data["choose_sticker"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='CHOOSE_STICKER action is on' , message_id=message.id)

    if message.text == ".choose_sticker off":
        data["choose_sticker"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='CHOOSE_STICKER action is off' , message_id=message.id)

    if message.text == ".upload_vid on":
        data["upload_video"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_VIDEO action is on' , message_id=message.id)

    if message.text == ".upload_vid off":
        data["upload_video"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_VIDEO action is off' , message_id=message.id)

    if message.text == ".upload_doc on":
        data["upload_document"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_DOCUMENT action is on' , message_id=message.id)

    if message.text == ".uoload_doc off":
        data["upload_document"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_DOCUMENT action is off' , message_id=message.id)

    if message.text == ".upload_audio on":
        data["upload_audio"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_AUDIO action is on' , message_id=message.id)

    if message.text == ".upload_audio off":
        data["upload_audio"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='UPLOAD_AUDIO action is off' , message_id=message.id)

    if message.text == ".speaking on":
        data["speaking"] = "on"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='SPEAKING action is on' , message_id=message.id)

    if message.text == ".speaking off":
        data["speaking"] = "off"
        save_data(data)
        await app.edit_message_text(chat_id=message.chat.id , text='SPEAKING action is off' , message_id=message.id)

@app.on_message(~filters.me & ((filters.private & ~filters.bot) | (filters.mentioned & filters.group)))       
async def Actions(app , message):
    data = load_data()
    playing = data["playing"]

    typing = data["typing"]
    
    record_video = data["record_video"]

    choose_sticker = data["choose_sticker"]
    
    upload_video = data["upload_video"]
    
    upload_document = data["upload_document"]
    
    upload_audio = data["upload_audio"]
    
    speaking = data["speaking"]

    if playing == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.PLAYING)

    if typing == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.TYPING)

    if record_video == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.RECORD_VIDEO)

    if choose_sticker == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.CHOOSE_STICKER)

    if upload_video == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.UPLOAD_VIDEO)

    if upload_document == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.UPLOAD_DOCUMENT)

    if upload_audio == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.UPLOAD_AUDIO)

    if speaking == "on" :
        await app.send_chat_action(chat_id=message.chat.id , action=enums.ChatAction.SPEAKING)

@app.on_message(filters.linked_channel)
def first(app, m:Message):
    data = load_data()
    chat_id , text = m.chat.id , m.text
    a =load_data(DATA_FILE)
    if a["firstcom"] == "on":
        magr = data.get("firstcommentmsg", "").split(":")
        
    if text != "@ultra_self":
        if msgr[0] == "text":
            m.reply(msgr[1])
        
    elif msgr[0] == "sticker":
        m.reply_sticker(msgr[1])
        
    elif msgr[0] == "animation":
        m.reply_animation(msgr[1])
        
    else:
        m.reply("__ERROR:__\nMessage Not Set\n**Ultra Self**")

@app.on_message(filters.new_chat_members,group=6)
def welcomebot(app, m:Message) :
    text = m.text 
    a = load_data()
    data = load_data()
    welcome_kos = data.get("welcome_add_text", "")
    welcome_message = (f"""Hello {m.from_user.mention} !\nWelcome To **{m.chat.title}** 👋😼\n📆Date: `{date.today().strftime("%Y/%m/%d")}`\n⌛️Time: `{datetime.now(timezone("Asia/Tehran")).strftime("%H:%M:%S")}`\n{welcome_kos if welcome_kos else ""}""")
    if data["welcome"] == "on":
        app.send_message(m.chat.id , welcome_message)

@app.on_message(filters.me & prefixed_command(f'^(.wiki)'), group=14)
def wiki(client,message):
    set_lang('en')
    result = summary("".join(message.text.split()[1::]))
    message.reply(result)
    audio = gTTS(text=result , lang='en')
    audio.save("voice.ogg")
    app.send_audio(message.chat.id , "voice.ogg", caption="◤✧Function: #wikipedaia text to Voice◥\n◣✧Language:English Lang◢")
    os.remove(f"voice.ogg")

@app.on_message(filters.me & prefixed_command(f'^(ویکی)'), group=14)
def wiki(client,message):
    set_lang('fa')
    result = summary("".join(message.text.split()[1::]))
    message.reply(result)

@app.on_message(prefixed_command("hlock", ".") & filters.me)
def locktypes(app, message: Message):
    app.send_message(message.chat.id , """you can lock these=
    "msg"
    "stickers"
    "gifs"
    "media"
    "games"
    "inline"
    "url"
    "polls"
    "info"
    "invite"
    "pin""" , reply_to_message_id=message.id)
data = {
    "msg": "can_send_messages",
    "stickers": "can_send_other_messages",
    "gifs": "can_send_other_messages",
    "media": "can_send_media_messages",
    "games": "can_send_other_messages",
    "inline": "can_send_other_messages",
    "url": "can_add_web_page_previews",
    "polls": "can_send_polls",
    "info": "can_change_info",
    "invite": "can_invite_users",
    "pin": "can_pin_messages",
}

@app.on_message(prefixed_command(["lock", "unlock"], ".") & filters.me)
async def locks_func(app, message: Message):
    if len(message.command) != 2:
        return await message.edit_text("Invailed")

    chat_id = message.chat.id
    parameter = message.text.strip().split(None, 1)[1].lower()
    state = message.command[0].lower()

    if parameter not in data and parameter != "all":
        return await message.edit_text("InVailed")

    permissions = await current_chat_permissions(app, chat_id)

    if parameter in data:
        await tg_lock(
            app,
            message,
            permissions,
            data[parameter],
            bool(state == "lock"),
        )
        
    elif parameter == "all" and state == "lock":
        await app.set_chat_permissions(chat_id, ChatPermissions())
        await message.edit_text(f"Locked Everything in {message.chat.title}")

    elif parameter == "all" and state == "unlock":
        await app.set_chat_permissions(
            chat_id,
            ChatPermissions(
                can_send_messages=True,
                can_send_media_messages=True,
                can_send_other_messages=True,
                can_add_web_page_previews=True,
                can_send_polls=True,
                can_change_info=False,
                can_invite_users=True,
                can_pin_messages=False,
            ),
        )
        await message.edit(f"Unlocked Everything in {message.chat.title}")

@app.on_message(prefixed_command("locks", ".") & filters.me)
async def locktypes(app, message: Message):
    permissions = await current_chat_permissions(app, message.chat.id)
    if not permissions:
        return await message.edit("No Permissions.")

    perms = ""
    for i in permissions:
        perms += f" • __**{i}**__\n"

    await message.edit_text(perms)

@app.on_message(prefixed_command("translate") & filters.me, group=29)
def translate_text(client, message):
    try:
        lang, text = message.text.split(maxsplit=1)[1].split(" ", maxsplit=1)
        translator = Translator(to_lang=lang)
        translation = translator.translate(text)
        message.reply(f"Original Text: {text}\nTranslated Text: {translation}")

    except Exception as e:
        message.reply_text(f"An error occurred: {e}")
        
@app.on_message(prefixed_command("imdb") & filters.me, group=8)
def imdb_query(client, message):
    catmessage =  message.edit("❅__**Wait**__")
    try:
        movie_name = message.text.split("/imdb")[1]
        movies = imdb.search_movie(movie_name)
        movieid = movies[0].movieID
        movie = imdb.get_movie(movieid)
        moviekeys = list(movie.keys())
        for i in mov_titles:
            if i in moviekeys:
                mov_title = movie[i]
                break
        for j in reversed(mov_titles):
            if j in moviekeys:
                mov_ltitle = movie[j]
                break
        mov_runtime = movie["runtimes"][0] + " min" if "runtimes" in movie else ""
        if "original air date" in moviekeys:
            mov_airdate = movie["original air date"]
            
        elif "year" in moviekeys:
            mov_airdate = movie["year"]
            
        else:
            mov_airdate = ""
        mov_genres = ", ".join(movie["genres"]) if "genres" in moviekeys else "Not Data"
        mov_rating = str(movie["rating"]) if "rating" in moviekeys else "Not Data"
        mov_rating += (
            " (by " + str(movie["votes"]) + ")"
            
            if "votes" in moviekeys and "rating" in moviekeys
            else ""
        )
        mov_countries = (
            ", ".join(movie["countries"]) if "countries" in moviekeys else "Not Data"
        )
        mov_languages = (
            ", ".join(movie["languages"]) if "languages" in moviekeys else "Not Data"
        )
        mov_plot = (
            str(movie["plot outline"]) if "plot outline" in moviekeys else "Not Data"
        )
        mov_director =  get_cast("director", movie)
        mov_composers =  get_cast("composers", movie)
        mov_writer =  get_cast("writer", movie)
        mov_cast =  get_cast("cast", movie)
        mov_box =  get_moviecollections(movie)
        resulttext = f"""
<b>❅<i>Title : </i></b><code>{mov_title}</code>
<b>❅<i>Imdb Url : </i></b><a href='https://www.imdb.com/title/tt{movieid}'>{mov_ltitle}</a>
<b>❅<i>Info : </i></b><code>{mov_runtime} | {mov_airdate}</code>
<b>❅<i>Genres : </i></b><code>{mov_genres}</code>
<b>❅<i>Rating : </i></b><code>{mov_rating}</code>
<b>❅<i>Country : </i></b><code>{mov_countries}</code>
<b>❅<i>Language : </i></b><code>{mov_languages}</code>
<b>❅<i>Director : </i></b><code>{mov_director}</code>
<b>❅<i>Music Director </i>: </b><code>{mov_composers}</code>
<b>❅<i>Writer : </i></b><code>{mov_writer}</code>
<b><i>❅Stars : </i></b><code>{mov_cast}</code>
<b>❅<i>Box Office : </i></b>{mov_box}
<b>❅<i>Story Outline : </i></b><i>{mov_plot}</i>"""

        if "full-size cover url" in moviekeys:
            imageurl = movie["full-size cover url"]
        else:
            imageurl = None
        soup = BeautifulSoup(resulttext, features="html.parser")
        rtext = soup.get_text()
        
        if len(rtext) > 1024:
            extralimit = len(rtext) - 1024
            climit = len(resulttext) - extralimit - 20
            resulttext = resulttext[:climit] + "...........</i>"
            
        if imageurl:
            downloader = SmartDL(imageurl, moviepath, progress_bar=False)
            downloader.start(blocking=False)
            while not downloader.isFinished():
                pass
            
        if os.path.exists(moviepath):
            app.send_photo(
                message.chat.id,
                moviepath,
                caption=resulttext,
            )
            os.remove(moviepath)
            return  catmessage.delete()
            catmessage.edit(
            resulttext,
            link_preview=False,
        )
    except IndexError:
        catmessage.edit(f"__**❅This Movie Not Found{movie_name}.**__")
        
    except Exception as e:
        catmessage.edit(f"__**❅Error:**__\n__{e}__")

@app.on_message(filters.text,group=6)
def autoanwer(app, m:Message):
    text = m.text 
    a = load_data()
    
    if a["autoan"] == "on":
        if text in answer:
            num = answer.index(text)
            app.send_message(m.chat.id , javab[num], reply_to_message_id=m.id)
            sleep(9)
            num = 0

@app.on_message(filters.me & filters.text , group=336)
def updates(app, m:Message):
    global api
    global enemy
    global love
    global mutey
    global lang
    global now
    text = m.text or ""

    if (json_database["boldmode"] == "on"):
        m.edit_text(f"**{text}**")
        
    elif (json_database["italicmode"] == "on"):
        m.edit_text(f"__{text}__")
        
    elif (json_database["codemode"] == "on"):
        m.edit_text(f"`{text}`")
        
    elif (json_database["underline"] == "on"):
        m.edit_text(f"<u>{text}</u>")
        
    elif (json_database["strike"] == "on"):
        m.edit_text(f"~~{text}~~")
        
    elif (json_database["spoilermode"] == "on"):
        m.edit_text(f"||{text}||")
        
    elif (json_database["quotemode"] == "on"):
        m.edit_text(f"```{text}```")
        
    elif (json_database["mention"] == "on"):
        m.edit_text(f"<a href=tg://user?id={m.chat.id}>{text}</a>")
        
    elif text.startswith(".pvlock"):
        parts = text.strip().split()
        if len(parts) < 2:
            m.edit_text("❋ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❋")
        else:
            mode = parts[1].strip().lower()
            if mode == "on":
                json_database.update({"pvlock": "on"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text("❋ Pv Lock is **ON**")
            elif mode == "off":
                json_database.update({"pvlock": "off"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text("❋ Pv Lock is **OFF**")
            else:
                m.edit_text("❋ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❋")

    elif text.startswith(".clone"):
        try:
            if m.reply_to_message:
                userSelfp = m.reply_to_message.chat.id
                b = app.invoke(functions.users.GetFullUser(id=app.resolve_peer(userSelfp)))
                kiri = app.get_users(m.reply_to_message.chat.id)
                user_id_get = m.reply_to_message.chat.id
            else:
                text = text.replace(" ","").replace(".clone","")
                user_id_get = app.get_users(text).id
                kiri = app.get_users(user_id_get)
                b = app.invoke(functions.users.GetFullUser(id=app.resolve_peer(user_id_get)))
                app.edit_message_text(m.chat.id , m.id , text=f"""
            **Cloner**
        ❖ `Firstname`⤳ (`{b.users[0].first_name if b.users[0].first_name else '--'}`)
        ❖ `Lastname`⤳ (`{(b.users[0].last_name if b.users[0].last_name else '--')}`)
        ❖ `Bio`⤳ (`{(b.full_user.about if b.full_user.about else '--')}`)""")
                loudo = app.download_media(kiri.photo.big_file_id)
                app.set_profile_photo(photo=loudo)
                app.update_profile(first_name=b.users[0].first_name)
                app.update_profile(last_name=(b.users[0].last_name if b.users[0].last_name else ""))
                app.update_profile(bio=(b.full_user.about if b.full_user.about else ""))
                app.edit_message_text(m.chat.id , m.id , "❖ Clone Successfully Completed")
                os.remove(loudo)
        except errors.exceptions.bad_request_400.UsernameNotOccupied: 
            app.send_message(m.chat.id , f"❖ Username Not Valid ❖") 
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".block"):
        app.block_user(m.reply_to_message.chat.id if m.reply_to_message else text.split()[1])
        m.edit_text(f"❖ {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Blocked ") 
    
    elif text.startswith(".unblock"):
        app.unblock_user(m.reply_to_message.chat.id if m.reply_to_message else text.split()[1])
        m.edit_text(f"❖ {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Unblocked ") 

    elif text.startswith(".left"):
        try:
            if text.split()[1]:
                app.leave_chat( text.split()[1] , delete=True)
                m.edit_text(f"❖ Successfully Left From [ `{text.split()[1]}` ]")
            else:
                app.send_message(m.chat.id , f"Bye :)") 
                app.leave_chat(m.chat.id , delete=True) 
        except Exception as er:
            pass
    
    elif text.startswith(".join "):
        try:
            link = text.replace(".join ","")
            link = link.replace('+','joinchat/')
            app.join_chat(link)
            app.send_message(m.chat.id , f'❖ Successfully Joined To [ {link} ]' ,disable_web_page_preview=True)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text == ".delethistory":
        try: 
            app.invoke(functions.channels.DeletHistory(app.resolve_peer(channel=m.chat.id)))
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".ban"):
        try:
            app.ban_chat_member(m.chat.id , (m.reply_to_message.chat.id if m.reply_to_message else text.split()[1]))
            app.send_message(m.chat.id , f"❖ User {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Successfully Banned !")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text.startswith(".unban"):
        try:
            app.unban_chat_member(m.chat.id , (m.reply_to_message.chat.id if m.reply_to_message else text.split()[1]))
            app.send_message(m.chat.id , f"❖ User {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Successfully UnBanned !")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".clear_member","پاکسازی ممبر")):
        target = text.split()[1]
        m.edit_text(f"❖ Target Chat: `{target}`\n__Start Ban members__ . . .")
        for member in app.get_chat_members(target):
            try:
                app.ban_chat_member(target , member.user.id)
            except errors.FloodWait as e:
                app.send_message("me",f"❖ Wait For {e.x} Seconds")
                sleep(e.x)
                app.send_message("me",f"❖ **Flood Wait Has Ended**🥳\nSend [ `.clear_member {target}` ] Again")
                
            except errors.exceptions.bad_request_400.UserAdminInvalid:
                app.send_message("me",f"**❖ You Are Not Admin in** ( `{target}` )")
                pass
            
            except errors.exceptions.bad_request_400.BadRequest:
                app.send_message("me",f"**❖ Clear Members of ( {target} ) Has Been Ended**")
                pass
            
            except Exception as er:
                app.send_message("me",f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".delmute","حذف سکوت")):
        try:
            app.unban_chat_member(m.chat.id , (m.reply_to_message.chat.id if m.reply_to_message else text.split()[1]))
            app.send_message(m.chat.id , f"❖ User {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Successfully UnMuted !")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".setmute","تنظیم سکوت")):
        try:
            app.restrict_chat_member(m.chat.id, m.reply_to_message.chat.id, ChatPermissions())
            app.send_message(m.chat.id , f"❖ User {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Muted")
        except:
            m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")

    elif text.startswith((".setchatphoto","تنظیم پروفایل گروه")):
        try:
            if m.reply_to_message.photo:
                app.set_chat_photo(chat_id=m.chat.id,photo=m.reply_to_message.photo.file_id)
                app.send_message(m.chat.id , f"❖ Chat Photo Changed")
            else:
                app.set_chat_photo(chat_id=m.chat.id,video=m.reply_to_message.video.file_id)
                app.send_message(m.chat.id , f"❖ Chat Photo Changed")
        except:
            m.edit_text(f"❖ Please Reply To Photo or Video")

    elif text.startswith((".setprofile","تنظیم پروفایل")):
        try:
            if m.reply_to_message.photo:
                down = app.download_media(m.reply_to_message)
                app.set_profile_photo(photo=down)
                app.send_message(m.chat.id , f"❖ Your Profile Photo Changed")
                os.remove(down)
            
            elif m.reply_to_message.video:
                down = app.download_media(m.reply_to_message)
                app.set_profile_photo(video=down)
                app.send_message(m.chat.id , f"❖ Your Profile Video Changed")
                os.remove(down)
            else:
                app.send_message(m.chat.id , f"❖ Please Reply To Message")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".delprofile","حذف پروفایل")):
        try:
            photos = app.get_chat_photos("me")
            app.delete_profile_photos(next(photos).file_id)
            app.send_message(m.chat.id , f"❖ Your Profile photo Deleted")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif ".delchatphoto" == text or "حذف پروفایل گروه" == text:
        try:
            app.delete_chat_photo(m.chat.id)
            m.reply(f"❖ Chat Photo Cleared")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".setchattitle"):
        try:
            kx = text.replace(".setchattitle" , "")[1::]
            app.set_chat_title(m.chat.id, kx.strip())
            m.reply(f"❖ Chat Name changed To[ `{kx}` ]")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith("تنظیم نام گروه"):
        try:
            kx = text.replace("تنظیم نام گروه" , "")[1::]
            app.set_chat_title(m.chat.id, kx.strip())
            m.reply(f"❖ Chat Name changed To[ `{kx}` ]")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text.startswith(".setchatbio"):
        try:
            kx = text.replace(".setchatbio","")[1::]
            app.set_chat_description(m.chat.id, kx)
            m.reply(f"❖ Chat Bio changed To [ `{kx}` ]")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text.startswith("تنظیم بیو گروه"):
        try:
            kx = text.replace("تنظیم بیو گروه","")[1::]
            app.set_chat_description(m.chat.id, kx)
            m.reply(f"❖ Chat Bio changed To [ `{kx}` ]")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif ".pin" == text or "پین" == text:
        if m.reply_to_message:
            try:
                m.pin(disable_notification=False)
                m.edit_text(f'❖ Pinned')
            except Exception as er:
                m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
        else:
            m.edit_text(f"❖ Please Reply To Message")

    elif ".unpin" == text or "حذف پین" == text:
        try:
            chat_id = m.chat.id
            reply_message = m.reply_to_message
            app.unpin_chat_message(chat_id, reply_message)
            m.edit_text("❖ Unpinned")
        except Exception as e:
            m.edit_text(f"❖ ERROR: {e}")

    elif ".unpinall" == text or "حذف همه پین" == text:
        try:
            app.unpin_all_chat_messages(m.chat.id)
            m.edit_text(f'❖ All Message Unpinned')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".setchatusername","تنظیم یوزرنیم گروه")):
        try:
            kx = text.split()[1]
            app.set_chat_username(m.chat.id, kx)
            m.edit_text(f'❖ Chat Username Changed [ `{kx}` ]')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   

    elif text.startswith((".creatchannel","ساخت کانال")):
        try:
            kx = text.split()[1]
            app.create_channel(title=f'{kx}')
            m.edit_text(f'❖ Channel [ `{kx}` ] Created')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".creatsupergroup","ساخت گروه")):
        try:
            kx = text.split()[1]
            app.create_supergroup(title=f'{kx}')
            m.edit_text( f'❖ Supergroup [ `{kx}` ] Created')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".creatgroup"):
        try:
            kx = text.split()[1]
            app.create_group(title=f'{kx}')
            m.edit_text( f'❖ Group [ `{kx}` ] Created')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".delallmsguser","حذف کل")):
        try:
            app.delete_user_history(m.chat.id , (m.reply_to_message.chat.id if m.reply_to_message else text.split()[1]))
            m.edit_text(f"All message From {(m.reply_to_message.from_user.mention if m.reply_to_message else f'<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>')} Deleted")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".slowmod","حالت آرم")):
        try:
            kx = text.split()[1]
            app.set_chat_description(m.chat.id, int(kx))
            m.edit_text( f'❖ Slow Mode is on Second : {kx}')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".setname"):
        try:
            kx = text.replace(".setname","")[1::]
            app.invoke(functions.account.UpdateProfile(first_name=kx))
            data = load_data()
            data["user_name"] = kx
            save_data(data)
            m.edit_text(f'❖ Your Name ɪs Updated To [ `{kx}` ]')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text.startswith(".setlastname"):
        try:
            kx = text.replace(".setlastname","")[1::]
            app.invoke(functions.account.UpdateProfile(last_name=kx))
            m.edit_text(f'❖ Your Lastname is Updated To [ `{kx}` ]')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
    
    elif text.startswith(".setbio"):
        try:
            kx = text.replace(".setbio","")[1::]
            app.invoke(functions.account.UpdateProfile(about=kx))
            write("userbio.txt" , text.replace(".setbio","")[1::])
            m.edit_text(f'❖ Your Bio Updated To⤳[ `{kx}` ]')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".welcome_add"):
        data = load_data()
        data["welcome_add_text"] = ""[1::]
        save_data(data)
        m.edit_text(f"❖ Successfully Added To Welcome Message")
    
    elif text.startswith("تنظیم خوشامد"):
        data = load_data()
        data["welcome_add_text"] = ""[1::]
        save_data(data)
        m.edit_text(f"❖ Successfully Added To Welcome Message")
    
    elif text.startswith(".welcome_reset"):
        data = load_data()
        data["welcome_add_text"] = ""
        save_data(data)
        m.edit_text(f"❖ Successfully Welcome Message Reset")

    elif text.startswith(".getip"):
        try:
            HOSTNAME = m.reply_to_message.text if m.reply_to_message else text.split()[1]
            app.edit_message_text(m.chat.id, m.id, f'❖ The [`{HOSTNAME}`] iP address is [`{gethostbyname(HOSTNAME)}`]')
        except:
            app.edit_message_text(m.chat.id, m.id, f'❖ The `{HOSTNAME}` Not valid !!')
    
    elif text.startswith(".whoisip"):
        try:
            HOSTIP = m.reply_to_message.text if m.reply_to_message else text.split()[1]
            source = location(ip=HOSTIP, key=None)
            app.edit_message_text(m.chat.id, m.id, f"""
❖ `iP` ⤳  (`{source["ip"]}`)
❖ `City` ⤳  (`{source["city"]}`)
❖ `Region` ⤳  (`{source["region"]}`)
❖ `Country` ⤳  (`{source["country"]}`)\n(`{source["country_name"]}`)
❖ `Area Code` ⤳  (`{source["country_calling_code"]}`)
❖ `Language` ⤳  (`{source["languages"]}`)
❖ `Owner` ⤳  (`{source["org"]}`)""")
        except:
            app.edit_message_text(m.chat.id, m.id, f'❖ The `{HOSTIP}` Not valid !!')

    elif text.startswith(".firstcomment"):
        try:
            if text.split()[1] == "on":
                json_database.update({"firstcom":"on"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text(f"❖ First comment is **ON**")
            
            elif text.split()[1] == "off":
                json_database.update({"firstcom":"off"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text(f"❖ First comment is **OFF**")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".antich"):
        try:
            data = load_data()
            data["anti_del_chat"] = text.split()[1]
            save_data(data)
            m.edit_text(f"֍ 𝗢𝗸 :)\nChat ID: `{text.split()[1]}`") 
        except Exception as er:
            m.edit_text(f"├ • `ERROR` ⤳\n(`{er}`)") 

    elif text.startswith(".mention"):
        if m.reply_to_message:
            try:
                m.edit_text(f"{m.reply_to_message.from_user.mention}") 
            except:
                m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")
        else:
            try:
                m.edit_text(f"<a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a>") 
            except:
                m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")

    elif text == ".dl":
        try:
            down = app.download_media(m.reply_to_message)
            if m.reply_to_message.caption:
                caption=m.reply_to_message.caption
            else:
                caption=""
                app.send_document(m.chat.id , down , caption=caption)
                os.remove(down)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text == "waitt":
        try:
            down = app.download_media(m.reply_to_message)
            app.send_document("me" , down , caption="😈")
            os.remove(down)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
   
    elif text == ".unzip":
        file_name =  m.reply_to_message.download()
        edited =  app.send_message(m.chat.id, "file : \n downloads->")
        sleep(1)
        app.edit_message_text(edited.chat.id, edited.id, 'file : \n downloads->extractfiles->')
        with zipfile.ZipFile(file_name, 'r') as zip_ref:
            zip_ref.extractall('templ')
        count = 0
        for root, dirs, files in os.walk('templ'):
            for name in files:
                filename = os.path.join(root, name)
                count += 1
                if os.path.getsize(filename) == 0:
                    os.remove(filename)
                    continue
                app.send_document(m.chat.id, filename, caption="file %s in zip" % count)
                os.remove(filename)
        app.edit_message_text(edited.chat.id, edited.id,'file : \n downloads->extractfiles->exracted->uploading->uploaded')
        for name in dirs:
            dirname = os.path.join(root, name)
            if not os.listdir(dirname):
                os.rmdir(dirname)

    elif text == ".tp":
        try:
            down = app.download_media(m.reply_to_message)
            if down == None:
                m.edit_text(f"**ERROR!**\n\n__Please Reply To A Sticker__")
            else:
                os.rename(down ,'sticker.jpg')
                app.send_photo(m.chat.id , f"sticker.jpg" ,caption="**Sticker** To **Picture** By Ultra Self", reply_to_message_id=m.id)
                os.remove(f"sticker.jpg")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text == ".ts":
        try:
            down = app.download_media(m.reply_to_message)
            if down == None:
                m.edit_text(f"**ERROR!**\n\n__Please Reply To A Photo__")
            else:
                os.rename(down ,'sticker.webp')
                app.send_sticker(m.chat.id , f"sticker.webp" , reply_to_message_id=m.id)
                os.remove(f"sticker.webp")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text == ".tg":
        try:
            down = app.download_media(m.reply_to_message)
            if down == None:
                m.edit_text(f"**ERROR!**\n\n__Please Reply To A Photo__")
            else:
                os.rename(down ,'animation.gif')
                app.send_animation(m.chat.id , f"animation.gif" , reply_to_message_id=m.id)
                os.remove(f"animation.gif")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".dllink"):
        i = 1
        url=(m.reply_to_message.text if m.reply_to_message else text.split()[1])
        try:
            if url.find('/'):
                filename=url.split('/')[-1]
                r = GET(url, allow_redirects=True , stream=True)
                total = int(r.headers.get('content-length'))
                app.edit_message_text(m.chat.id , m.id , f"""𝗗𝗼𝘄𝗻𝗹𝗼𝗮𝗱\n❖ ғɪʟᴇ ɴᴀᴍᴇ : `{filename}`\n❖ ғɪʟᴇsɪᴢᴇ : `{total/1024/1024:.3f} ᴍʙ`\n❖ ᴛɪᴍᴇ : `{datetime.now(timezone("Asia/Tehran")).strftime("%H:%M")}`\nㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\n❖ ᴡᴀɪᴛ ғᴏʀ ᴅᴏᴡɴʟᴏᴀᴅ""")
                with open(filename, 'wb') as file:
                    for data in r.iter_content(chunk_size=1024):
                        size = file.write(data)
                        m.edit_text(f"""𝗗𝗼𝘄𝗻𝗹𝗼𝗮𝗱\n❖ ғɪʟᴇ ɴᴀᴍᴇ : `{filename}`\n❖ ғɪʟᴇsɪᴢᴇ : `{total/1024/1024:.3f} ᴍʙ`\n❖ ᴛɪᴍᴇ : `{datetime.now(timezone("Asia/Tehran")).strftime("%H:%M")}`\nㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ\n❖ ᴅᴏᴡɴʟᴏᴀᴅ ᴄᴏᴍᴘʟᴇᴛᴇᴅ\n❖ ᴡᴀɪᴛ ғᴏʀ ᴜᴘʟᴏᴀᴅ""")
                        app.send_document(m.chat.id , f"{filename}" , caption=f"""𝗨𝗽𝗹𝗼𝗮𝗱\n❖ ғɪʟᴇ ɴᴀᴍᴇ : `{filename}`\n❖ ғɪʟᴇsɪᴢᴇ : `{total/1024/1024:.3f} ᴍʙ`\n❖ ᴛɪᴍᴇ : `{datetime.now(timezone("Asia/Tehran")).strftime("%H:%M")}`""")
                        app.delete_messages(m.chat.id , m.id)
                        os.remove(filename)
        except:
            m.edit_text(f"❖ ᴛʜᴇ ғᴏʟʟᴏᴡɪɴɢ ʟɪɴᴋ ɪs ɴᴏᴛ ᴅᴏᴡɴʟᴏᴀᴅᴀʙʟᴇ")

    elif text.startswith(".sticker"):
        try:
            im = Image.open(GET(f"http://www.flamingtext.com/net-fu/proxy_form.cgi?imageoutput=true&script=colgate-logo&&text={text.replace('.sticker' , '')[1::]}&fontsize=100", stream=True).raw) 
            im.save('sticker.png')
            os.rename('sticker.png' ,'sticker.webp')
            app.send_sticker(m.chat.id , f"sticker.webp" , reply_to_message_id=m.id)
            os.remove(f"sticker.webp")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   

    elif text == ".sticker2":
        try:
            kobs = datetime.now(timezone("Asia/Tehran")).strftime("%H:%M:%S")
            im = Image.open(GET(f"https://bcassetcdn.com/asset/logo/e7b2b2cb-aed9-4ca2-b4bc-61d4414d891b/logo?v=4&text={kobs}"))
            im.save('sticker.png')
            os.rename('sticker.png' ,'sticker.webp')
            app.send_sticker(m.chat.id , f"sticker.webp" , reply_to_message_id=m.id)
            os.remove(f"sticker.webp")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".error"):
        try:
            imn = Image.open(GET(f"http://http.cat/{text.replace('.error' , '')[1::]}.jpg", stream=True).raw) 
            imn.save('sticker.jpg')
            os.rename('sticker.jpg' ,'sticker.webp')
            app.send_sticker(m.chat.id , f"sticker.webp" , reply_to_message_id=m.id)
            os.remove(f"sticker.webp")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   

    elif m.text == ".get_message":
        if m.reply_to_message:
            app.send_message(m.chat.id , m.reply_to_message, reply_to_message_id=m.id)
    elif m.text == ".time":
        try:
            for i in range(0,10):
                kir = datetime.now(timezone("Asia/Tehran")).strftime("%H:%M:%S")
                app.edit_message_text(m.chat.id , m.id , f"**Time:** `{kir}`")
                sleep(1)
        except Exception as er:
            m.edit_text("er")

    elif text.startswith(".send_coment"):
        
        t = text.replace(".send_coment", "")[1::]
        data = load_data()
        sending_text = data.get("send_time_text", "") if data.get("send_time_text", "") != None else "."
            
        app.delete_messages(m.chat.id , m.id)
        app.send_message("me" , f"❖ I Will Send [`{sending_text}`] at {t} Comment \n\n__In This Chat:__ [`{m.chat.id}`] ")
        
        chait = m.reply_to_message.chat.id
        mesig = m.reply_to_message
        
        while True:
            count = app.get_discussion_replies_count(chait, mesig.id)
            sleep(0.1)
            if int(count) >= (int(t) - 1):
                app.send_message(m.chat.id , sending_text, reply_to_message_id=(mesig.id if mesig else m.id))
                break

    elif text.startswith(".coment_text"):
        if m.reply_to_message.text:
            data = load_data()
            fileud = m.reply_to_message.text
            data["send_time_text"] = fileud
            save_data(data)
            m.edit_text(f"❖ The Message Of [ `.send_coment` ] is {fileud}")
        else:
            m.edit_text(f"❖ Please Reply To A Text Message")
   
    elif text.startswith(".text_time"):
        
        t = text.replace(".text_time", "")[1::]
        sending_time = have_sec(t)
        sending_text = data.get("send_time_text", "") if ("send_time_text") != None else "."
        
        app.delete_messages(m.chat.id , m.id)
        app.send_message("me" , f"❖ I Will Send [`{sending_text}`] At [**{sending_time}**]\n\n__In This Chat:__ [`{m.chat.id}`]")
        while True:
            a = datetime.now(timezone("Asia/Tehran")).strftime("%H:%M:%S")
            if sending_time == a:
                app.send_message(m.chat.id , sending_text, reply_to_message_id=(reply_to_message.id if m.reply_to_message else m.id))
                sending_time = ""
                break

    elif text.startswith(".photo_time"):
        sending_time = text.replace(".photo_time", "")[1::]+":00"
        sending_text = read("send_time_photo.txt")
        app.delete_messages(m.chat.id , m.id)
        down = app.download_media(sending_text)
        app.send_message("me" , f"❖ I Will Send photo At [**{sending_time}**]\n\n__In This Chat:__ [`{m.chat.id}`]")
        while True:
            a = datetime.now(timezone("Asia/Tehran")).strftime("%H:%M:%S")
            if sending_time == a:
                app.send_photo(m.chat.id , down , reply_to_message_id=(reply_to_message.id if m.reply_to_message else m.id))
                sending_time = ""
                break

    elif text.startswith(".text_send_time"):
        if m.reply_to_message.text:
            data = load_data()
            fileud = m.reply_to_message.text
            data["send_time_text"] = fileud
            save_data(data)
            m.edit_text(f"❖ The Message Of [ `.text_time` ] is {fileud}")
        else:
            m.edit_text(f"❖ Please Reply To A Text Message")
   
    elif text.startswith(".photo_send_time"):
        if m.reply_to_message.photo:
            fileud = m.reply_to_message.photo.file_id
            write("send_time_photo.txt" , fileud)
            m.edit_text(f"❖ The Photo Of [ `.photo_time` ]👇\n\nFile id: {fileud}")
        else:
            m.edit_text(f"**❖ Please reply to a photo**")

    elif text == ".ping":
        try:
            up_a = (strftime('%H:%M:%S', gmtime(uptime())))
            svmem = virtual_memory()
            app.edit_message_text(m.chat.id , m.id , f"""
    **Ultra Self Status**
    
❖ `User` ⤳ ( `{app.get_me().first_name}` )
❖ `Uptime` ⤳ (`{up_a}`)
❖ `Ram Usage` ⤳ (`{get_size(svmem.used)}`)
❖ `Python Version` ⤳ (`{python_version()}`)
❖ `Source Version` ⤳ (`{Src_vrsion}`) 
❖ `Library` ⤳ (`Pyrogram`)""")
        except Exception as er:
            m.edit_text(er)

    elif text == ".cpu":
        try:
            cpufreq = cpu_freq()
            app.edit_message_text(m.chat.id , m.id , f"""
❖ `Physical Cores` ⤳  (`{cpu_count(logical=False)}`)
❖ `Total Cores` ⤳  (`{cpu_count(logical=True)}`)
❖ `Max Frequency` ⤳  (`{cpufreq.max:.2f}Mhz`)
❖ `Min Frequency` ⤳  (`{cpufreq.min:.2f}Mhz`)
❖ `Cuttent Frequency` ⤳  (`{cpufreq.current:.2f}Mhz`)
❖ `CPU Usage` ⤳  (`{cpu_percent()}%`)""")
        except Exception as er: 
            m.edit_text(er)

    elif text == ".memory":
        try:
            svmem = virtual_memory()
            app.edit_message_text(m.chat.id , m.id , f"""
❖ `Total` ⤳ (`{get_size(svmem.total)}`)
❖ `Available` ⤳ (`{get_size(svmem.available)}`)
❖ `Used` ⤳ (`{get_size(svmem.used)}`)
❖ `Percentage` ⤳ (`{svmem.percent}%`)""")
        except Exception as er:
            m.edit_text(er)

    elif text == ".system-inf":
        try:
            kirithokhmi = uname()
            app.edit_message_text(m.chat.id , m.id , f"""
❖ `System` ⤳ (`{kirithokhmi.system}`)
❖ `Node Name` ⤳ (`{kirithokhmi.node}`)
❖ `Release` ⤳ (`{kirithokhmi.release}`)
❖ `Version` ⤳ (`{kirithokhmi.version}`)
❖ `Machine` ⤳ (`{kirithokhmi.machine}`)
❖ `Processor` ⤳ (`{kirithokhmi.processor}`)""") 
        except Exception as er:
            m.edit_text(er)

    elif text.startswith(".voice"):
        try:
            audio = gTTS(text=text.replace(".voice","")[1::] , lang='en')
            audio.save("voice.ogg")
            app.send_audio(m.chat.id , "voice.ogg", caption="◤✧Function: Text to Voice◥\n◣✧Language:English Lang◢")
            os.remove(f"voice.ogg")
   
            audio2 = gTTS(text=text.replace(".voice","")[1::] , lang='fr')
            audio2.save("voice2.ogg")
            app.send_audio(m.chat.id , "voice2.ogg", caption="◤✧Function: Text to Voice◥\n◣✧Language:French lang◢")
            os.remove(f"voice2.ogg")
   
            audio3 = gTTS(text=text.replace(".voice","")[1::] , lang='es')
            audio3.save("voice3.ogg")
            app.send_audio(m.chat.id , "voice3.ogg", caption="◤✧Function: Text to Voice◥\n◣✧Language:Spanish Lang◢")
            os.remove(f"voice3.ogg")
   
            audio4 = gTTS(text=text.replace(".voice","")[1::] , lang='pt')
            audio4.save("voice4.ogg")
            app.send_audio(m.chat.id , "voice4.ogg", caption="◤✧Function: Text to Voice◥\n◣✧Language:Portuguese Lang◢")
            os.remove(f"voice4.ogg")
   
            audio5 = gTTS(text=text.replace(".voice","")[1::] , lang='zh-TW')
            audio5.save("voice5.ogg")
            app.send_audio(m.chat.id , "voice5.ogg", caption="◤✧Function: Text to Voice◥\n◣✧Language:Chinese Lang◢")
            os.remove(f"voice5.ogg")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")  
   
    elif text.startswith(".crush"):
        try:
            audio6 = gTTS(text=text.replace(".crush","")[1::] , lang='zh-CN')
            audio6.save("voice6.ogg")
            app.send_audio(m.chat.id , "voice6.ogg")
            app.delete_messages(m.chat.id , m.id)
            os.remove(f"voice6.ogg")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")  
    
    elif text.startswith(".price"):
        try:
            text=text.replace('.price ','')
            price = torb(text)
            m.reply_photo(price[2], caption = f"#Basalam\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n**{price[0]}\n\nقیمت : {price[1]}**تومان\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n")
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text.startswith(".gif "):
        try:
            text=text.replace('.gif ','')
            gif(text)
            app.send_animation(m.chat.id, "proxy_form.gif", f"**گیف شما آماده شد** \nگیف درخواستی : `{text}`", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text.startswith(".logo "):
        try:
            text=text.replace('.logo ','')
            logo(text)
            app.send_photo(m.chat.id, "logo.png", f"**لوگو شما آماده شد** \nلوگو درخواستی : `{text}`", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)
    
    elif text.startswith(".logo2 "):
        try:
            text=text.replace('.logo2 ','')
            logo2(text)
            app.send_photo(m.chat.id, "logo.png", f"**لوگو شما آماده شد** \nلوگو درخواستی : `{text}`", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)
    
    elif text.startswith(".lg "):
        try:
            text=text.split(" ")
            logo3(text[1], text[2])
            app.send_photo(m.chat.id, "logo.png", f"**Your Logo is Ready!**\n**Logo** : `{text[1]}`", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)
    
    elif text.startswith(".ci"):
        try:
            text = text.replace(".ci ", "")
            app.unblock_user("creationdatebot")
            response = app.send_message("creationdatebot" , f"/id {text}")
            sleep(3)
            spambot_msg = response.id + 1
            status = app.get_messages(chat_id="creationdatebot", message_ids=spambot_msg)
            app.send_message(m.chat.id, f"**STATUS**▬▬▬▬▬▬▬▬▬▬\nUser ID = `{text}`\nCreation Date = `{status.text}`\n▬▬▬▬▬▬▬▬▬▬**STATUS**", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)
    
    elif text.startswith(".com"):
        try:
            text = text.replace(".com ", "")
            app.unblock_user("rextesterrobot")
            response = app.send_message("rextesterrobot" , f"{text}")
            sleep(3)
            spambot_msg = response.id + 1
            status = app.get_messages(chat_id="rextesterrobot", message_ids=spambot_msg)
            app.send_message(m.chat.id, f"`{status.text}`", reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text.startswith(".musicc "):
        try:
            text = text.replace(".musicc ", "")
            ytdl(text)
            app.send_audio(m.chat.id , f"{text}.mp3", ytinfo(text))
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text.startswith(".remix "):
        try:
            name = text.replace(".remix ", "")
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("vkmusic_bot", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!",performer="Ultra Self",title=f"{name}",thumb="cache/jack.jpg")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".muzik "):
        try:
            name = text.replace(".muzik ", "")
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("vkrubot", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!**\n__Music Name__ : **{name}**")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".global "):
        try:
            name = text.replace(".global ", "")
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("mixvk_bot", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!",performer="Ultra Self",title=f"{name}",thumb="cache/jack.jpg")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".demo "):
        try:
            name = text.replace(".demo ", "")
            wait = m.reply("__Wait Please..__")
            result = app.get_inline_bot_results("spotybot", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!",performer="Ultra Self",title=f"{name}",thumb="cache/jack.jpg")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".music "):
        try:
            name = text.replace(".music ", "")
            wait = m.reply("**Please Wait...**")
            result = song_YouTube(name)
            wait.edit("**Downloaded**")
            app.send_photo(m.chat.id,result[2] , reply_to_message_id=m.id)
            m.reply_audio(result[0] , performer="Ultra Self", title=result[0], caption=result[1],thumb="cache/micon.jpg")
            os.remove(result[0])
            wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".youtube "):
        try:
            name = text.replace(".youtube ", "")
            wait = m.reply(f"**Please Wait...**")
            result = get_youtube_video(name)
            if result[0]:
                app.send_photo(m.chat.id,result[1], caption=f"**Ultra Self**", reply_to_message_id=m.id)
                app.send_video(
                    chat_id=m.chat.id,
                    video=open(result[0], "rb"),
                    reply_to_message_id=m.id,
                    caption = f"**{result[2]}\nUltra Self**"
                )
                os.remove(result[0])
                wait.delete()
            else:
                wait.edit("Error: Failed to get the video.")
        except Exception as e:
            app.send_message(
                m.chat.id,
                f"An error occurred. Please try again.\n{e}",
                reply_to_message_id=m.id,
            )

    elif text.startswith(".classic "):
        try:
            name = text.replace(".classic ", "")
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("music", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("Downloaded")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!",performer="Ultra Self",title=f"{name}",thumb="cache/jack.jpg")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)
    
    elif text.startswith(".musicc "):
        try:
            name = text.replace(".musicc ", "")
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("voiceshazambot", name)
            if result.results:
                audio_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, audio_result.id)
                music = app.get_messages("me", gett.updates[0].id)
                if music.audio:
                    file_path = app.download_media(music.audio)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_audio(file_path, caption=f"**Your Music is Ready!",performer="Ultra Self",title=f"{name}",thumb="cache/jack.jpg")
                    os.remove(file_path)
                else:
                    wait.edit("No audio found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No music found.")
                wait.delete()
        except Exception as er:
            app.send_message(m.chat.id, f"An error occurred. Please try again.\n{er}", reply_to_message_id=m.id)

    elif text.startswith(".ahang "):
        try:
            name = text.replace(".ahang ", "")
            download_song(name)
            app.send_audio(m.chat.id, open(f"{name}.mp3", "rb"),reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id, f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)
  
    elif text == ".cryptolist":
        try:
            msg="** ❖CRYPTO LIST(لیست نام ارزها)\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nrls, btc, eth, ltc, usdt, xrp, bch, bnb, eos, xlm, etc, trx, pmn, doge, uni, dai, link, dot, aave, ada,shib, ftm, matic, axs, mana, sand, avax, mkr, gmt, usdc\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nاز دستور .crypto name اطلاعات کامل هر ارز دیجیتال را دریافت کنید.**"
            app.send_message(m.chat.id ,msg, reply_to_message_id=m.id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text.startswith(".movie "):
        try:
            name=text.replace('.movie ','')
            m2 = m.reply("**Downloading..**")
            bot_results = app.get_inline_bot_results("tgmovies2bot" , name)
            video = app.send_inline_bot_result("me" , bot_results.query_id, bot_results.results[1].id)
            message_video = app.get_messages("me" , video.updates[0].id)
            m3 = m.reply("**Uploading..**")
            wait = m.reply("Wait Please..")
            wait.delete()
            app.send_document(m.chat.id , message_video.document.file_id, caption="**Your Movie is Ready !....**")
            m2.delete()
            m3.delete()
            app.delete_messages("me" , video.updates[0].id)
        except Exception as er:
            app.send_message(m.chat.id ,f"خطايي رخ داد لطفا دوباره تلاش کنيد \n {er}", reply_to_message_id=m.id)

    elif text == "پینگ":
        ping = psutil.getloadavg()
        process = psutil.Process(os.getpid())
        ram = sizeof_fmt(process.memory_info().rss)
        app.send_message(m.chat.id, f"▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nSELF is **ONLINE**\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n❅Ping: `%s` ms\n❅Ram: `%s`\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬" % (ping[0], ram), reply_to_message_id=m.id)

    elif text == (".link"):
        link = app.create_chat_invite_link(m.chat.id)
        app.send_message(m.chat.id,"❈**Link**: %s ." % link.invite_link,reply_to_message_id=m.id)

    elif text == ("id"):
        dd="ايدي عددي شما : "+str(m.chat.id)
        app.send_message(m.chat.id ,dd,reply_to_message_id=m.id)
    
    elif text.startswith(".giff"):
        try:
            text=text.replace('.giff ','')
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("gif", text)
            if result.results:
                animation_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, animation_result.id)
                image1 = app.get_messages("me", gett.updates[0].id)
                if image1.animation:
                    file_path = app.download_media(image1.animation)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_animation(file_path)
                    os.remove(file_path)
                else:
                    wait.edit("No animation found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No animation found.")
                wait.delete()
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".melo"):
        try:
            text=text.replace('.melo ','')
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("melobot", text)
            if result.results:
                voice_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, voice_result.id)
                image1 = app.get_messages("me", gett.updates[0].id)
                if image1.voice:
                    file_path = app.download_media(image1.voice)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_voice(file_path)
                    os.remove(file_path)
                else:
                    wait.edit("No voice found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No voice found.")
                wait.delete()
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   

    elif text.startswith(".pic"):
        try:
            text=text.replace('.pic ','')
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("pic", text)
            if result.results:
                photo_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, photo_result.id)
                image1 = app.get_messages("me", gett.updates[0].id)
                if image1.photo:
                    file_path = app.download_media(image1.photo)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_photo(file_path, caption=f"**{text}**")
                    os.remove(file_path)
                else:
                    wait.edit("No Photo found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No photo found.")
                wait.delete()
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)") 

    elif text.startswith(".stick"):
        try:
            text=text.replace('.stick ','')
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("sticker", text)
            if result.results:
                sticker_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, sticker_result.id)
                image1 = app.get_messages("me", gett.updates[0].id)
                if image1.sticker:
                    file_path = app.download_media(image1.sticker)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_sticker(file_path)
                    os.remove(file_path)
                else:
                    wait.edit("No sticker found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No sticker found.")
                wait.delete()
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   

    elif text.startswith(".bing"):
        try:
            text=text.replace('.bing ','')
            wait = m.reply("Wait Please..")
            result = app.get_inline_bot_results("bing", text)
            if result.results:
                photo_result = result.results[0]
                gett = app.send_inline_bot_result("me", result.query_id, photo_result.id)
                image1 = app.get_messages("me", gett.updates[0].id)
                if image1.photo:
                    file_path = app.download_media(image1.photo)
                    wait.edit("**Downloaded**")
                    app.delete_messages("me", gett.updates[0].id)
                    m.reply_photo(file_path, caption=f"**{text}**")
                    os.remove(file_path)
                else:
                    wait.edit("No Photo found.")
                    app.delete_messages("me", gett.updates[0].id)
            else:
                wait.edit("No photo found.")
                wait.delete()
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".meme"):
        try:
            text=text.replace('.meme ','')
            m.edit_text(f"command = .meme {text}\n**meme name:** `{text}`")
            result = app.get_inline_bot_results("persian_meme_bot", text)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".like"):
        try:
            text=text.replace('.like ','')
            result = app.get_inline_bot_results("like", text)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".location"):
        try:
            text=text.replace('.location ','')
            result = app.get_inline_bot_results("openmap_bot", text)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".stat"):
        try:
            text=text.replace('.stat ','')
            result = app.get_inline_bot_results("tgstat_bot", text)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")   
   
    elif text.startswith(".qrcode"):
        try:
            qr_str = (m.reply_to_message.text if m.reply_to_message else text.replace('.qrcode' , '')[1::])
            if qr_str == None:
                m.edit_text(f"**ERROR!**\n\n__Please Reply To A Text Message__")
            else:
                qr = qrcode.make(qr_str)
                qr.save("QrCode.png")
                app.send_photo(m.chat.id , f"QrCode.png" , caption=f"QrCode ⤳(`{qr_str}`)" , reply_to_message_id=m.id)
                os.remove(f"QrCode.png")
        except Exception as er:
            m.edit_text(f"**ERROR!** \n\n{er}")

    elif text.startswith("اسپم"):
        try:
            if x := (findall(r"اسپم \d+",text)[0]):
                ui = findall(r"\d+",x)[0]
                sts = findall(r"\d+\s+.+",text)[0].replace(ui,"")[0].replace(ui,"")
                for i in range(0,int(ui)):
                    app.send_message(m.chat.id , sts)
        except Exception as er:
            m.edit_text(er)
   
    elif text.startswith(".spm"):
        try:
            if x := (findall(r"\.spm \d+",text)[0]):
                ui = findall(r"\d+",x)[0]
                sts = findall(r"\d+\s+.+",text)[0].replace(ui,"")[0].replace(ui,"")
                for i in range(0,int(ui)):
                    if m.reply_to_message:
                        app.send_message(m.chat.id , sts, reply_to_message_id=m.id)
            else:
                m.edit_text("**Please Reply**")
        except Exception as er:
            m.edit_text(er)
            
    elif text.startswith("ادیت اسپم"):
        try:
            if x := (findall(r"ادیت اسپم \d+",text)[0]):
                ui = findall(r"\d+",x)[0]
                sts = findall(r"\d+\s+.+",text)[0].replace(ui,"")[0].replace(ui,"")
                for i in range(0,int(ui)):
                    if m.reply_to_message:
                        app.send_message(m.chat.id , sts, reply_to_message_id=m.id)
                    else:
                        m.edit_text("**Please Reply**")
        except Exception as er:
            m.edit_text(er)
        
    elif m.text == ".carbon":
        try:
            code = (m.reply_to_message.text if m.reply_to_message else text.replace('.carbon' , '')[1::])
            app.edit_message_text(m.chat.id ,m.id ,f"__Making Screenshot from Your Code...__\n\n**Code** :\n`{code}`")
            params = {'code': code,"paddingVertical": "56px","paddingHorizontal": "57px","backgroundImage": None,"backgroundImageSelection": None,"backgroundMode": "color","backgroundColor": "rgba(0, 255, 160, 1)","dropShadow": True,"dropShadowOffsetY": "9px","dropShadowBlurRadius": "12px","theme": "Dracula","language": "auto","fontFamily": "Hack","fontSize": "18px","lineHeight": "250%","windowControls": True,"widthAdjustment": True,"lineNumbers": True,"firstLineNumber": 1,"exportSize": "2x","watermark": False,"squaredImage": False,"hiddenCharacters": True,"width": 680}
            snippet(params)
            app.send_photo(m.chat.id , f"i.png" , caption=f":)" , reply_to_message_id=m.id)
            os.remove(f"i.png")
        except Exception as er:
            m.edit_text(er)

    elif text.startswith(".exec"):
        try:
            m.edit_text(f"""**INPUT**\n`{text}`\n\n**OUTPUT**\nWait ...""")
            codeOut = StringIO()
            sys.stdout = codeOut
            exec(str(text.replace(".exec ","")))
            sys.stdout = sys.__stdout__
            results = codeOut.getvalue().strip()
            bic = True if results.strip() != '' else False
            
            if len(results) >= 3800:
                write("results.txt",str(results))
                m.edit_text(f"""**INPUT**\n`{text}`\n\n**OUTPUT**\n In File👇👹""")
                m.reply_document("results.txt")
                os.remove("results.txt")
            else:
                m.edit_text(f"""**INPUT**\n`{text}`\n\n**OUTPUT**\n`{results if bic == True else 'Successful'}`""")
                codeOut.close()
        except Exception as er:
            app.send_message(m.chat.id , f"❖ **ERROR** :\n(`{er}`)")

    elif text == ".ocr":
        try:
            if m.reply_to_message.photo:
                m.edit_text("Wait For **8** Second . . .")
                app.send_photo("@oneGooglebot",m.reply_to_message.photo.file_id,caption="")
                sleep(8)
                a = app.get_chat_history("@oneGooglebot", limit=1)
                a = next(a)
                text = a.text;text = text.replace("💭 OCR detected:","")
                m.edit_text("**OCR** __Detected Successfully :)__")
                m.reply(f"**❖ OCR Result:**`{text}`",quote=True)
            else:
                m.edit_text("**Please Reply to a Photo**")
        except Exception as er:
            app.send_message(m.chat.id , f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".delete"):
        mmd = app.get_chat_member(m.chat.id, "me")
        rasi = dast_del(text=mmd)
        if rasi:
            try:
                reu = int(text.replace(".delete",""))
                if type(reu) == int:
                    kalc = 0
                    for m in app.get_chat_history(m.chat.id):
                        if reu != kalc:
                            m.delete(revoke=True)
                            kalc += 1
                        else:
                            break
                            m.reply(f"❖ `{kalc}` **Messages Successfully Deleted !**", quote=False)
                else:
                    m.reply("❖ Please Enter a Number")
            except Exception as er:
                app.send_message(m.chat.id , f"❖ **ERROR** :\n(`{er}`)")
        else:
            m.reply("❖ You Dont Have Delete message Permission")

    elif text.startswith(".file_info"):
        getcontext().prec = 3
        try:
            if m.reply_to_message.document:
                m.edit_text(f"""❖ Name ⤳ (`{m.reply_to_message.document.file_name}`)
❖ Type ⤳ (`{m.reply_to_message.document.mime_type}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.document.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Date ⤳ (`{m.reply_to_message.document.date}`)
❖ File iD ⤳ (`{m.reply_to_message.document.file_id}`)""")

            elif m.reply_to_message.photo:
                m.edit_text(f"""❖ Size ⤳ (`{m.reply_to_message.photo.width}×{m.reply_to_message.photo.height}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.photo.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Date ⤳ (`{m.reply_to_message.photo.date}`)
❖ File iD ⤳ (`{m.reply_to_message.photo.file_id}`)""")

            elif m.reply_to_message.video:
                m.edit_text(f"""❖ Type ⤳ (`{m.reply_to_message.video.mime_type}`)
❖ Size ⤳ (`{m.reply_to_message.video.width}×{m.reply_to_message.video.height}`)
❖ Duration ⤳ (`{m.reply_to_message.video.duration}s`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.video.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Date ⤳ (`{m.reply_to_message.video.date}`)
❖ Support Streaming ⤳ (`{m.reply_to_message.video.supports_streaming}`)
❖ File iD ⤳ (`{m.reply_to_message.video.file_id}`)""")

            elif m.reply_to_message.animation:
                m.edit_text(f"""❖ Size ⤳ (`{m.reply_to_message.animation.width}×{m.reply_to_message.animation.height}`)
❖ Type ⤳ (`{m.reply_to_message.animation.mime_type}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.animation.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Duration ⤳ (`{m.reply_to_message.animation.duration}s`)
❖ Date ⤳ (`{m.reply_to_message.animation.date}`)
❖ File iD ⤳ (`{m.reply_to_message.animation.file_id}`)""")

            elif m.reply_to_message.sticker:
                m.edit_text(f"""❖ Size ⤳ (`{m.reply_to_message.sticker.width}×{m.reply_to_message.sticker.height}`)
❖ Name ⤳ (`{m.reply_to_message.sticker.file_name}`)
❖ Type ⤳ (`{m.reply_to_message.sticker.mime_type}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.sticker.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Emoji ⤳ (`{m.reply_to_message.sticker.emoji}`)
❖ Is Animated ⤳ (`{m.reply_to_message.sticker.is_animated}`)
❖ Is Video ⤳ (`{m.reply_to_message.sticker.is_video}`)
❖ Sticker Set ⤳ (`{"https://t.me/addstickers/"+m.reply_to_message.sticker.set_name if m.reply_to_message.sticker.set_name else "--"}`)
❖ Date ⤳ (`{m.reply_to_message.sticker.date}`)
❖ File iD ⤳ (`{m.reply_to_message.sticker.file_id}`)""")

            elif m.reply_to_message.voice:
                m.edit_text(f"""❖ Type ⤳ (`{m.reply_to_message.voice.mime_type}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.voice.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Duration ⤳ (`{m.reply_to_message.voice.duration}s`)
❖ Date ⤳ (`{m.reply_to_message.voice.date}`)
❖ File iD ⤳ (`{m.reply_to_message.voice.file_id}`)""")

            elif m.reply_to_message.audio:
                m.edit_text(f"""❖ Title ⤳ (`{m.reply_to_message.audio.title}`)
❖ Performer ⤳ (`{m.reply_to_message.audio.performer}`)
❖ Type ⤳ (`{m.reply_to_message.audio.mime_type}`)
❖ File Name ⤳ (`{m.reply_to_message.audio.file_name}`)
❖ File Size ⤳ (`{Decimal(int(m.reply_to_message.audio.file_size))/Decimal(1024)/Decimal(1024)}ᴍʙ`)
❖ Duration ⤳ (`{m.reply_to_message.audio.duration}s`)
❖ Date ⤳ (`{m.reply_to_message.audio.date}`)
❖ File iD ⤳ (`{m.reply_to_message.audio.file_id}`)""")

            elif m.reply_to_message.text:
                m.edit_text(f"**Please Reply To A Media/file**")
        except Exception as er:
            m.edit_text(er)

    elif text.startswith((".first_message","تنظیم کامنت اول")):
        try:
            data = load_data()
            if m.reply_to_message.animation:
                
                data["firstcommentmsg"] = f"animation:{m.reply_to_message.animation.file.id}"
                save_data(data)
                m.reply("**Gif** Successfully Saved")
                
            elif m.reply_to_message.sticker:
                data["firstcommentmsg"] = f"sticker:{m.reply_to_message.sticker.file.id}"
                save_data(data)
                m.reply("**Sticker** Successfully Saved")
                
            elif m.reply_to_message.text:
                data["firstcommentmsg"] = f"text:{m.reply_to_message.text}"
                save_data(data)
                m.reply("**Text** Successfully Saved")
                
            else:
                m.reply("Please Reply to **Gif** or **Sticker** or **Text**")
        except Exception as er:
            m.edit_text(er)

    elif text == ".status":
        getcontext().prec = 3
        try:
            start = time()
            pv = 0
            group = []
            Channel = 0
            ch_creator = 0
            gp_creator = 0
            Bot = 0
            for ii in app.get_dialogs():
                
                if ii.chat.type in ['ChatType.GROUP','ChatType.SUPERGROUP']:
                    group.append(ii.chat.id)
                    
                    if ii.chat.is_creator == True:
                        gp_creator+=1
                    
                elif ii.chat.type == "ChatType.PRIVATE":
                    pv+=1
                    
                elif ii.chat.type == "ChatType.CHANNEL":
                    Channel+=1
                    if ii.chat.is_creator == True:
                        ch_creator+=1
                        
                elif ii.chat.type == "ChatType.BOT":
                    Bot+=1
            blocked = app.invoke(GetBlocked(offset=0,limit=0))
            stickered = app.invoke(GetAllStickers(hash=0))
            end = time()
            m.reply(f"""**Private Chats:** `{pv}`
  •• `Bots: {Bot}`
**Groups:** `{len(group)}`
  •• `Creator: {gp_creator}`
**Channels:** `{Channel}`
  •• `Creator: {ch_creator}`
**Blocked Users:** `{blocked.count}`
**Total Stickers Pack Installed:** `{len(list(stickered.sets))}`
its Took: {Decimal(end) - Decimal(start)}s""")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text == ".tadmin":
        try:
            b = "❖ **Admins** :\n\n"
            c = 1
            k = 0
            a = app.get_chat_members(m.chat.id, filter=enums.ChatMembersFilter.ADMINISTRATORS)
            
            for i in a:
                if i.user.is_deleted == False:
                    b += "├"+str(c)+" ↬ ["+(i.user.mention if i.user.id else "--")+"]\n"
                    c += 1
                else:
                    k += 1
                    
            if k != 0:
                b += f"├ **Deleted Account Admin** : `{k}`\n└— **Count** : `{k + c - 1}`"
            else:
                b += f"└—  \n **Count** : `{k + c - 1}`"
            m.reply(b)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".game"):
        try:
            games = ["Neon Blaster","Neon Blaster 2","Block Buster","Gravity Ninja","Hexonix","Geometry Run 3D","Disco Ball","Tube Runner","Little Plane","MotoFx 2","Space Traveler","Groovy Ski"]
            jdkh = choice(games)
            m.edit_text(f"**Game name:** `{jdkh}`")
            result = app.get_inline_bot_results("gamee", jdkh)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".bazi"):
        try:
            games = ["Math Battle","Corsairs","LumberJack"]
            jdkh = choice(games)
            m.edit_text(f"**Game name:** `{jdkh}`")
            result = app.get_inline_bot_results("gamebot", jdkh)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".hehe"):
        try:
            games = ["2048","Flappy Bird","Hextris"]
            jdkh = choice(games)
            m.edit_text(f"**Game name:** `{jdkh}`")
            result = app.get_inline_bot_results("awesomebot", jdkh)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".acc"):
        try:
            games = ["0"]
            jdkh = choice(games)
            result = app.get_inline_bot_results("creationdatebot", jdkh)
            app.send_inline_bot_result(m.chat.id, result.query_id, result.results[0].id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")
   
    elif text.startswith(".inf"):
        try:
            if text.split()[1] == "@this":
                user = m.chat.id
            else:
                user = text.split()[1]
                user = app.get_chat(user)
            if user.photo:
                down = app.download_media(user.photo.big_file_id)
                app.send_photo(m.chat.id , down , f"""__Chat info__

❖ **Title** : `{user.title}`
❖ **ID** : `{user.id}`
❖ **Username** : `@{user.username if user.username else '--'}`
❖ **Members** : `{user.members_count}`
❖ **Dc ID** : `{user.dc_id}`
❖ **Is Creator** : `{user.is_creator}`
❖ **Is Verified** : `{user.is_verified}`
❖ **Is Restricted** : `{user.is_restricted}`
❖ **Is Scam** : `{user.is_scam}`
❖ **Is Fake** : `{user.is_fake}`
❖ **Sticker Set** : `{"https://t.me/addstickers/"+user.sticker_set_name if user.sticker_set_name else "--"}`
❖ **Description** : `{user.description}`""", reply_to_message_id=m.id)
                os.remove(down)
            else:
                app.send_message(m.chat.id , f"""__Chat info__

❖ **Title** : `{user.title}`
❖ **ID** : `{user.id}`
❖ **Username** : `@{user.username if user.username else '--'}`
❖ **Members** : `{user.members_count}`
❖ **Dc ID** : `{user.dc_id}`
❖ **Is Creator** : `{user.is_creator}`
❖ **Is Verified** : `{user.is_verified}`
❖ **Is Restricted** : `{user.is_restricted}`
❖ **Is Scam** : `{user.is_scam}`
❖ **Is Fake** : `{user.is_fake}`
❖ **Sticker Set** : `{"https://t.me/addstickers/"+user.sticker_set_name if user.sticker_set_name else "--"}`
❖ **Description** : `{user.description}`""", reply_to_message_id=m.id)
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".id"):
        try:
            user_id_get = (m.reply_to_message.chat.id if m.reply_to_message else app.get_users(text.split()[1]).id)
            user = app.invoke(functions.users.GetFullUser(id=app.resolve_peer(user_id_get)))
            count_photo = app.get_chat_photos_count(user_id_get)
            kiri = app.get_users(user_id_get)
            if kiri.photo:
                down = app.download_media(kiri.photo.big_file_id)
                app.send_photo(m.chat.id , down , f"""__Hi Boss, look at `{user.users[0].first_name if user.users[0].first_name else "--"}` information__

❖ **Name** : `{user.users[0].first_name if user.users[0].first_name else "--"}`
❖ **LastName** : `{user.users[0].last_name if user.users[0].last_name else "--"}`
❖ **Id** : `{user.users[0].id if user.users[0].id else "--"}`
❖ **Username** : `@{user.users[0].username if user.users[0].username else "--"}`
❖ **BIO** : `{user.full_user.about if user.full_user.about else "--"}`
❖ **Profile Picture Count** : `{count_photo}`
❖ **Contact** : `{user.users[0].contact}`
❖ **Common Chats Count** : `{user.full_user.common_chats_count if user.full_user.common_chats_count else "0"}`
❖ **Can pin message** : `{user.full_user.can_pin_message}`
❖ **Scam** : `{user.users[0].scam}`
❖ **Premium** : `{user.users[0].premium}`
❖ **Bot** : `{user.users[0].bot}`
❖ **Verified** : `{user.users[0].verified}`
❖ **Deleted** : `{user.users[0].deleted}`
❖ **restricted** : `{user.users[0].restricted}`
❖ **support** : `{user.users[0].support}`
❖ **Phone Calls Available** : `{user.full_user.phone_calls_available}`
❖ **Phone Calls Private** : `{user.full_user.phone_calls_private}`
❖ **Video Calls Available** : `{user.full_user.video_calls_available}`
❖ **Access hash** : `{user.users[0].access_hash}`
❖ **Blocked** : `{user.full_user.blocked}`
`{f"❖ **Current ChatID**: {m.chat.id}" if m.chat.id != user.users[0].id else ""}`""" , reply_to_message_id=m.id)
                os.remove(down)
            else:
                app.send_message(m.chat.id , f"""__User info__

❖ **Name** : `{user.users[0].first_name if user.users[0].first_name else "--"}`
❖ **LastName** : `{user.users[0].last_name if user.users[0].last_name else "--"}`
❖ **Id** : `{user.users[0].id if user.users[0].id else "--"}`
❖ **Username** : `@{user.users[0].username if user.users[0].username else "--"}`
❖ **BIO** : `{user.full_user.about if user.full_user.about else "--"}`
❖ **Profile Picture Count** : `{count_photo}`
❖ **Contact** : `{user.users[0].contact}`
❖ **Status** : `{user.users[0].status}`
❖ **Common Chats Count** : `{user.full_user.common_chats_count if user.full_user.common_chats_count else "0"}`
❖ **Can pin message** : `{user.full_user.can_pin_message}`
❖ **Scam** : `{user.users[0].scam}`
❖ **Premium** : `{user.users[0].premium}`
❖ **Bot** : `{user.users[0].bot}`
❖ **Verified** : `{user.users[0].verified}`
❖ **Deleted** : `{user.users[0].deleted}`
❖ **restricted** : `{user.users[0].restricted}`
❖ **support** : `{user.users[0].support}`
❖ **Phone Calls Available** : `{user.full_user.phone_calls_available}`
❖ **Phone Calls Private** : `{user.full_user.phone_calls_private}`
❖ **Video Calls Available** : `{user.full_user.video_calls_available}`
❖ **Access hash** : `{user.users[0].access_hash}`
❖ **Blocked** : `{user.full_user.blocked}`
`{f"❖ **Current ChatID**: {m.chat.id}" if m.chat.id != user.users[0].id else ""}`""" , reply_to_message_id=m.id)
        except errors.exceptions.bad_request_400.UsernameNotOccupied:
            app.send_message(m.chat.id , f"❖ User Not Valid ❖")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".pp"):
        try:
            user_id_get = (m.reply_to_message.chat.id if m.reply_to_message else app.get_users(text.split()[1]).id)
            user = app.invoke(functions.users.GetFullUser(id=app.resolve_peer(user_id_get)))
            count_photo = app.get_chat_photos_count(user_id_get)
            kiri = app.get_users(user_id_get)
            if kiri.photo:
                down = app.download_media(kiri.photo.big_file_id)
                app.send_photo(m.chat.id , down , f"""__Hi Boss, look at `{user.users[0].first_name if user.users[0].first_name else "--"}` information__

❖ **Name** : `{user.users[0].first_name if user.users[0].first_name else "--"}`
❖ **LastName** : `{user.users[0].last_name if user.users[0].last_name else "--"}`
❖ **Id** : `{user.users[0].id if user.users[0].id else "--"}`
❖ **Username** : `@{user.users[0].username if user.users[0].username else "--"}`
❖ **BIO** : `{user.full_user.about if user.full_user.about else "--"}`
❖ **Profile Picture Count** : `{count_photo}`
""" , reply_to_message_id=m.id)
                os.remove(down)
            else:
                app.send_message(m.chat.id , f"""__User info__

❖ **Name** : `{user.users[0].first_name if user.users[0].first_name else "--"}`
❖ **LastName** : `{user.users[0].last_name if user.users[0].last_name else "--"}`
❖ **Id** : `{user.users[0].id if user.users[0].id else "--"}`
❖ **Username** : `@{user.users[0].username if user.users[0].username else "--"}`
❖ **BIO** : `{user.full_user.about if user.full_user.about else "--"}`
❖ **Profile Picture Count** : `{count_photo}`
""" , reply_to_message_id=m.id)
        except errors.exceptions.bad_request_400.UsernameNotOccupied:
            app.send_message(m.chat.id , f"❖ User Not Valid ❖")
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".i"):
        try:
            user_id_get = (m.reply_to_message.chat.id if m.reply_to_message else app.get_users(text.split()[1]).id)
            user = app.invoke(functions.users.GetFullUser(id=app.resolve_peer(user_id_get)))
            app.unblock_user("creationdatebot")
            response = app.send_message("creationdatebot" , f"/id {user_id_get}")
            sleep(3)
            spambot_msg = response.id + 1
            status = app.get_messages(chat_id="creationdatebot", message_ids=spambot_msg)
            app.send_message(m.chat.id , f"""
❖ **ID** : `{user.users[0].id if user.users[0].id else "--"}`
❖ **Creation Date** : `{status.text}`
""" , reply_to_message_id=m.id)
        except errors.exceptions.bad_request_400.UsernameNotOccupied:
            app.send_message(m.chat.id , f"❖ User Not Valid ❖")

    elif text.startswith((".mute","سکوت")):
        try:
            if m.reply_to_message:
                if m.reply_to_message.chat.id not in mutey:
                    if m.reply_to_message.chat.id != app.get_me().id:
                        mutey.append(m.reply_to_message.chat.id)
                        app.edit_message_text(m.chat.id , m.id , f'❖ {m.reply_to_message.from_user.mention} Added To Mute List')
                    else:
                        app.edit_message_text(m.chat.id , m.id , f'❖ This User {m.reply_to_message.from_user.mention} Already in mutes List')
                else :
                    if app.get_users(text.split()[1]).id not in mutey :
                        if app.get_users(text.split()[1]).id != app.get_me().id:
                            mutey.append(app.get_users(text.split()[1]).id)
                            app.edit_message_text(m.chat.id , m.id , f'❖ <a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a> Added To Mute List')
                        else:
                            app.edit_message_text(m.chat.id , m.id , f'❖ This User <a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a> Already in Mute List')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith((".unmute","حذف سکوت")):
        try:
            if m.reply_to_message:
                if m.reply_to_message.chat.id in mutey:
                    mutey.remove(m.reply_to_message.chat.id)
                    app.edit_message_text(m.chat.id , m.id , f'❖ User {m.reply_to_message.from_user.mention} Removed From Mute list')
                else:
                    app.edit_message_text(m.chat.id , m.id , f'❖ This User {m.reply_to_message.from_user.mention} is Not in Mute list')
            else :
                if app.get_users(text.split()[1]).id in mutey :
                    mutey.remove(app.get_users(text.split()[1]).id)
                    app.edit_message_text(m.chat.id , m.id , f'❖ User <a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a> Removed From mute list')
                else:
                    app.edit_message_text(m.chat.id , m.id , f'❖ This User <a href=tg://user?id={app.get_users(text.split()[1]).id}>{app.get_users(text.split()[1]).first_name}</a> is Not exist in mute list')
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text == ".clearenemy" :
        een = ""
        t_een = 1
        if len(enemy) >= 1:
            for user in enemy:
                een += f"{t_een} - <a href=tg://user?id={user}>{app.get_users(user).first_name}</a>\n"
                t_een += 1
                app.edit_message_text(m.chat.id , m.id , f"❖ Enemy List is cleaned\n{een}")
                enemy.clear()
        else:
            app.edit_message_text(m.chat.id , m.id , f"❖ Enemy List is Empty ") 
  
    elif text == ".clearlove" :
        een = ""
        t_een = 1
        if len(love) >= 1:
            for user in love:
                een += f"{t_een} - <a href=tg://user?id={user}>{app.get_users(user).first_name}</a>\n"
                t_een += 1
                app.edit_message_text(m.chat.id , m.id , f"❖ LOVE List is cleaned\n{een}")
                love.clear()
        else:
            app.edit_message_text(m.chat.id , m.id , f"❖ LOVE List is Empty ") 
  
    elif text == ".allunmute":
        eem = ""
        t_eem = 1
        if len(mutey) >= 1:
            for user in mutey:
                eem += f"{t_eem} - <a href=tg://user?id={user}>{app.get_users(user).first_name}</a>\n"
                t_eem += 1
                app.edit_message_text(m.chat.id , m.id , f"❖ Mute List is cleaned\n{eem}")
                mutey.clear()
        else:
            app.edit_message_text(m.chat.id , m.id , f"❖ Mute List is Empty ") 

    elif text.startswith(".limit_del"):
        b = int(text.split()[1])
        if type(b) == int:
            json_database.update({"limitDel":b})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Anti Del Member Limit Successfully Updated to {b} ❖")
        else:
            m.edit_text(f"❖ Please Enter A Number ❖")

    elif text.startswith(".fontname"):
        if text.split()[1] == "on":
            json_database.update({"fontname":"on"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Fontname is **ON**") 
        elif text.split()[1] == "off":
            json_database.update({"fontname":"off"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Fontname is **OFF**")
        else:
            m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")

    elif text.startswith(".welcome"): 
        s = ""
        try:
            if text.split()[1] == "on":
                json_database.update({"welcome":"on"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text(f"❖ Welcome Mode is **ON**") 
                
            elif text.split()[1] == "off":
                json_database.update({"welcome":"off"})
                write(DATA_FILE, json.dumps(json_database))
                m.edit_text(f"❖ Welcome Mode is **OFF**")
                
            elif text.split()[1] == None:
                m.edit_text(f"**Error**\n❖ `.welcome` ⤳ (`ᴏɴ ᴏʀ ᴏғғ`)\n├⤳`add` (`-100 + **ᴄʜᴀᴛ-ɪᴅ`)\n├⤳`del` (`-100 + **ᴄʜᴀᴛ-ɪᴅ`)\n├⤳`clear`\n├⤳`list`")
                
        except Exception as er:
            m.edit_text(f"❖ **ERROR** :\n(`{er}`)")

    elif text.startswith(".firstcom"):
        if text.split()[1] == "on":
            json_database.update({"firstcom":"on"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ First Comment is **ON**")
            
        elif text.split()[1] == "off":
            json_database.update({"firstcom":"off"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ First Comment is **OFF**")
        else:
            m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")
   
    elif text.startswith(".anti_fuck"):
        if text.split()[1] == "on":
            json_database.update({"anti_del":"on"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Anti Delete Member Mode  is **ON**")
        
        elif text.split()[1] == "off":
            json_database.update({"anti_del":"off"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Anti Delete Member Mode **OFF**")
        else:
            m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")   
   
    elif text.startswith(".on_off_status"):
        mh = ""
        a = load_data()
        pairs = a.items()
        for key, value in pairs:
            mh += f"❖ {key} -> {value}\n"
            m.edit_text(f"{mh}")

    elif text.startswith("پاسخگویی روشن"):
        json_database.update({"autoan":"on"})
        write(DATA_FILE, json.dumps(json_database))
        m.edit_text(f"❖ Auto Answer is **ON**")
        
    elif text.startswith("پاسخگویی خاموش"):
        json_database.update({"autoan":"off"})
        write(DATA_FILE, json.dumps(json_database))
        m.edit_text(f"❖ Auto Answer is **OFF**")

    elif text.startswith(".answer"):
        if text.split()[1] == "on":
            json_database.update({"autoan":"on"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Auto Answer is **ON**") 
            
        elif text.split()[1] == "off":
            json_database.update({"autoan":"off"})
            write(DATA_FILE, json.dumps(json_database))
            m.edit_text(f"❖ Auto Answer is **OFF**")
        else:
            m.edit_text(f"❖ ʀᴇsᴜʟᴛs [ `ᴇʀʀᴏʀ` ] ❖")

    elif text.startswith("افزودن پاسخ"):
        an = text.replace("افزودن پاسخ" , "")[1::].split(":")[0]
        en = text.replace("افزودن پاسخ" , "")[1::].split(":")[1]
        answer.append(an)
        javab.append(en)
        m.edit_text(f"❖ Answer Successfully Added\n[{an} -> {en}]") 

    elif text.startswith(".addan"):
        an = text.replace(".addan" , "")[1::].split(":")[0]
        en = text.replace(".addan" , "")[1::].split(":")[1]
        answer.append(an)
        javab.append(en)
        m.edit_text(f"❖ Answer Successfully Added\n[{an} -> {en}]") 
   
    elif text.startswith(".anclear"):
        if len(answer) >= 1:
            answer.clear()
            javab.clear()
            m.edit_text(f"❖ Successful!\nAnswer List Cleared") 
        else:
            app.edit_message_text(m.chat.id , m.id , f"❖ Answer List is Empty ")  
   
    elif text.startswith(".anlist"):
        s = ""
        op = 1
        if len(answer) >= 1:
            for i in range(0,int(len(answer))):
                s += f"❖ {op}: {answer[i]} -> {javab[i]}\n"
                op += 1
            m.edit_text(f"❖ **Answer List:**\n{s}") 
        else:
            app.edit_message_text(m.chat.id , m.id , f"❖ Answer List is Empty ") 
   
    elif text.startswith(".tas"):
        if 0 < int(text.split()[1]) < 7:   
            app.delete_messages(m.chat.id , m.id)
            while True:
                msg = app.send_dice(m.chat.id, "🎲")
                if msg.dice.value != int(text.split()[1]):
                    msg.delete()
                else:
                    break
        else:
            m.edit_text(f"Please Send A Number Between 1 To 6")
    
    elif text.startswith(".dart"):
        app.delete_messages(m.chat.id , m.id)
        while True:
            msg = app.send_dice(m.chat.id, "🎯")
            if msg.dice.value != 6:
                msg.delete()
            else:
                break

    elif text.startswith(".bowling"):
        app.delete_messages(m.chat.id , m.id) 
        while True:
            msg = app.send_dice(m.chat.id, "🎳")
            if msg.dice.value != 6:
                msg.delete()
            else:
                break

    elif text.startswith(".basketball"):
        app.delete_messages(m.chat.id , m.id)
        while True:
            msg = app.send_dice(m.chat.id, "🏀")
            if msg.dice.value != 4:
                msg.delete()
            else:
                break

    elif text.startswith(".football"):
        if int(text.split()[1]) == 1 or int(text.split()[1]) == 4:   
            app.delete_messages(m.chat.id , m.id)
            while True:
                msg = app.send_dice(m.chat.id, "⚽")
                if msg.dice.value != int(text.split()[1]):
                    msg.delete()
                else:
                    break
        else:
            m.edit_text(f"Please Send A Number Between 1 To 4")

    elif "پنل" == text:
        bot_results = app.get_inline_bot_results(bot_id, "panel")
        app.send_inline_bot_result(m.chat.id ,bot_results.query_id, bot_results.results[0].id)

# ======================== • Ser Scheduler • =========================== #

scheduler = AsyncIOScheduler()
scheduler.add_job(job, "interval", seconds=5)
scheduler.add_job(antidelmember, "interval", seconds=5)
scheduler.add_job(mak, "interval", hours=2)
async def start_scheduler():
    scheduler.start()

# =========================== • Main Start • =========================== #

app.loop.create_task(start_scheduler())
print("Starting The Bot . . .")
app.start()
print("Self Bot Is Started . . .")
idle()
app.stop()