Bot freezes when given Spotify link
05:16 23 Aug 2026

I built a Telegram bot for downloading content from YouTube, Instagram, SoundCloud, and Spotify. It works fine for YouTube, but when downloading from Instagram and SoundCloud, it throws an error—though it does eventually provide the file. However, when I provide a Spotify link, the bot freezes, and I have to stop it via the CMD window.

This is my bot's code:

import asyncio
import hashlib
import os
import shutil
import subprocess
import sys
import time
from typing import Optional

import requests
import yt_dlp
from parth_dl import get_info as parth_get_info
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes, MessageHandler, filters

TOKEN = "My Telgram Bot Token"
DOWNLOAD_DIR = "downloads"
os.makedirs(DOWNLOAD_DIR, exist_ok=True)

REQUEST_TIMEOUT_SECONDS = 90
SPOTIFY_TIMEOUT_SECONDS = 240
CALLBACK_TTL_SECONDS = 1800

active_downloads = {}
callback_data_store = {}


def normalize_url(url: str) -> str:
    if not isinstance(url, str):
        return ""
    return url.strip().split()[0].strip()


def make_callback_token(url: str) -> str:
    token = hashlib.md5(url.encode("utf-8")).hexdigest()[:16]
    callback_data_store[token] = {
        "url": url,
        "expires_at": time.time() + CALLBACK_TTL_SECONDS,
    }
    return token


def resolve_callback_url(token: str) -> Optional[str]:
    entry = callback_data_store.get(token)
    if not entry:
        return None
    if time.time() > entry.get("expires_at", 0):
        callback_data_store.pop(token, None)
        return None
    return entry.get("url")


def is_youtube(url: str) -> bool:
    url = normalize_url(url).lower()
    return "youtube.com" in url or "youtu.be" in url


def is_instagram(url: str) -> bool:
    url = normalize_url(url).lower()
    return "instagram.com" in url


def is_soundcloud(url: str) -> bool:
    url = normalize_url(url).lower()
    return "soundcloud.com" in url or "snd.sc" in url or "sndcld.com" in url


def is_spotify(url: str) -> bool:
    url = normalize_url(url).lower()
    return "spotify.com" in url or "spoti.fi" in url or "open.spotify.com" in url


def format_size(size):
    if not size:
        return "نامشخص"
    size = float(size)
    if size < 1024:
        return f"{int(size)} B"
    if size < 1024 ** 2:
        return f"{size / 1024:.1f} KB"
    if size < 1024 ** 3:
        return f"{size / (1024 ** 2):.1f} MB"
    return f"{size / (1024 ** 3):.2f} GB"


def progress_bar(percent: float, length: int = 12) -> str:
    filled = int(length * percent / 100)
    return "█" * filled + "░" * (length - filled)


def clean_dir(path: str):
    os.makedirs(path, exist_ok=True)
    for root, _, files in os.walk(path):
        for filename in files:
            try:
                os.remove(os.path.join(root, filename))
            except OSError:
                pass


def find_downloaded_file(path: str, preferred_name: str = "") -> str:
    if not os.path.exists(path):
        return ""
    if os.path.isfile(path):
        return path

    valid_exts = (
        ".mp3", ".m4a", ".m4b", ".webm", ".ogg", ".wav", ".aac",
        ".jpg", ".jpeg", ".png", ".webp", ".mp4", ".mov",
    )
    candidates = []

    for root, _, files in os.walk(path):
        for filename in files:
            full_path = os.path.join(root, filename)
            if not os.path.isfile(full_path):
                continue
            lower_name = filename.lower()
            if preferred_name and lower_name == preferred_name.lower():
                return full_path
            if lower_name.endswith(valid_exts) and os.path.getsize(full_path) > 0:
                candidates.append(full_path)

    if candidates:
        return max(candidates, key=os.path.getmtime)
    return ""


def safe_parth_get_info(url: str, timeout: int = REQUEST_TIMEOUT_SECONDS, retries: int = 3):
    import concurrent.futures

    last_error = None
    normalized = normalize_url(url)
    for attempt in range(retries):
        try:
            with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(parth_get_info, normalized)
                return future.result(timeout=timeout)
        except Exception as exc:
            last_error = exc
            if attempt < retries - 1:
                time.sleep(2 ** attempt)
                continue
    raise last_error


def get_youtube_info(url: str):
    options = {
        "quiet": True,
        "no_warnings": True,
        "skip_download": True,
        "noplaylist": True,
    }
    with yt_dlp.YoutubeDL(options) as ydl:
        return ydl.extract_info(normalize_url(url), download=False)


def get_youtube_qualities(url: str):
    info = get_youtube_info(url)
    qualities = set()
    for fmt in info.get("formats", []):
        height = fmt.get("height")
        if height in [144, 240, 360, 480, 720, 1080]:
            qualities.add(height)
    return info.get("title", "YouTube Video"), sorted(qualities, reverse=True)


def get_audio_info(url: str):
    if is_spotify(url):
        return {"title": "Spotify Audio", "uploader": "Spotify"}

    options = {
        "quiet": True,
        "no_warnings": True,
        "skip_download": True,
        "noplaylist": True,
        "socket_timeout": REQUEST_TIMEOUT_SECONDS,
    }
    with yt_dlp.YoutubeDL(options) as ydl:
        return ydl.extract_info(normalize_url(url), download=False)


def download_image_from_url(url: str, output_path: str):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
        "Referer": "https://www.instagram.com/",
    }
    response = requests.get(url, headers=headers, timeout=30, stream=True)
    response.raise_for_status()
    with open(output_path, "wb") as file:
        for chunk in response.iter_content(chunk_size=65536):
            if chunk:
                file.write(chunk)
    return output_path


def download_instagram_images(url: str, job_id: str):
    info = safe_parth_get_info(url, timeout=REQUEST_TIMEOUT_SECONDS, retries=2)
    if not isinstance(info, dict):
        raise Exception("Instagram metadata not available")

    images = info.get("images") or []
    if not images:
        raise Exception("No Instagram images found")

    folder = os.path.join(DOWNLOAD_DIR, f"instagram_{job_id}")
    os.makedirs(folder, exist_ok=True)
    clean_dir(folder)

    downloaded_files = []
    for index, item in enumerate(images, start=1):
        if active_downloads.get(job_id, {}).get("cancelled"):
            raise Exception("Download cancelled")

        image_url = item.get("url") if isinstance(item, dict) else str(item)
        if not image_url:
            continue

        ext = os.path.splitext(image_url.split("?", 1)[0])[1].lower() or ".jpg"
        filename = os.path.join(folder, f"image_{index:02d}{ext}")
        download_image_from_url(image_url, filename)
        downloaded_files.append(filename)

        if job_id in active_downloads:
            active_downloads[job_id]["percent"] = f"{(index / len(images)) * 100:.0f}%"

    return downloaded_files


def download_youtube_video(url: str, quality: int, job_id: str):
    output = os.path.join(DOWNLOAD_DIR, "%(title)s.%(ext)s")

    def progress_hook(data):
        if data.get("status") != "downloading":
            return
        if job_id in active_downloads:
            active_downloads[job_id]["percent"] = data.get("_percent_str", "0%").strip()
            active_downloads[job_id]["speed"] = data.get("_speed_str", "نامشخص").strip()
            active_downloads[job_id]["eta"] = data.get("_eta_str", "؟").strip()
        if active_downloads.get(job_id, {}).get("cancelled"):
            raise yt_dlp.utils.DownloadCancelled("Download cancelled by user")

    options = {
        "format": f"bestvideo[height<={quality}]+bestaudio/best[height<={quality}]",
        "outtmpl": output,
        "merge_output_format": "mp4",
        "noplaylist": True,
        "quiet": True,
        "no_warnings": True,
        "progress_hooks": [progress_hook],
    }

    with yt_dlp.YoutubeDL(options) as ydl:
        info = ydl.extract_info(normalize_url(url), download=True)
        filename = ydl.prepare_filename(info)

    base, _ = os.path.splitext(filename)
    mp4_file = base + ".mp4"
    if os.path.exists(mp4_file):
        return mp4_file
    return filename


def download_instagram_media(url: str, job_id: str):
    try:
        info = safe_parth_get_info(url, timeout=REQUEST_TIMEOUT_SECONDS, retries=2)
    except Exception:
        info = {}

    if isinstance(info, dict) and info.get("images"):
        files = download_instagram_images(url, job_id)
        if files:
            return files[0]

    output_dir = os.path.join(DOWNLOAD_DIR, f"instagram_video_{job_id}")
    os.makedirs(output_dir, exist_ok=True)
    clean_dir(output_dir)

    def progress_hook(data):
        if data.get("status") != "downloading":
            return
        if job_id in active_downloads:
            active_downloads[job_id]["percent"] = data.get("_percent_str", "0%").strip()
            active_downloads[job_id]["speed"] = data.get("_speed_str", "نامشخص").strip()
            active_downloads[job_id]["eta"] = data.get("_eta_str", "؟").strip()
        if active_downloads.get(job_id, {}).get("cancelled"):
            raise yt_dlp.utils.DownloadCancelled("Download cancelled by user")

    options = {
        "format": "best",
        "outtmpl": os.path.join(output_dir, "%(title)s.%(ext)s"),
        "noplaylist": True,
        "quiet": True,
        "no_warnings": True,
        "socket_timeout": REQUEST_TIMEOUT_SECONDS,
        "progress_hooks": [progress_hook],
        "http_headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
            "Referer": "https://www.instagram.com/",
        },
    }

    with yt_dlp.YoutubeDL(options) as ydl:
        info = ydl.extract_info(normalize_url(url), download=True)
        if info is None:
            raise Exception("Instagram info not found")

    candidate = find_downloaded_file(output_dir)
    if candidate:
        return candidate

    raise FileNotFoundError("Instagram file not found after download")


def find_valid_audio_file(path: str) -> str:
    if not os.path.exists(path):
        return ""

    valid_exts = (".mp3", ".m4a", ".m4b", ".webm", ".ogg", ".wav", ".aac")
    candidates = []
    for root, _, files in os.walk(path):
        for filename in files:
            lower_name = filename.lower()
            if lower_name.endswith(valid_exts):
                full_path = os.path.join(root, filename)
                if os.path.getsize(full_path) > 0:
                    candidates.append(full_path)
    if candidates:
        return max(candidates, key=os.path.getmtime)
    return ""


def download_spotify(url: str, job_id: str):
    temp_dir = os.path.join(DOWNLOAD_DIR, f"spotify_{job_id}")
    os.makedirs(temp_dir, exist_ok=True)
    clean_dir(temp_dir)

    normalized_url = normalize_url(url)
    for source in ["youtube", "youtube-music", "soundcloud"]:
        cmd = [
            sys.executable,
            "-m",
            "spotdl",
            "download",
            normalized_url,
            "--output",
            temp_dir,
            "--format",
            "mp3",
            "--overwrite",
            "skip",
            "--bitrate",
            "320k",
            "--audio",
            source,
            "--max-retries",
            "1",
            "--log-level",
            "ERROR",
        ]

        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                check=False,
                timeout=SPOTIFY_TIMEOUT_SECONDS,
            )
        except subprocess.TimeoutExpired:
            continue

        output_text = (result.stderr or "") + "\n" + (result.stdout or "")
        if result.returncode == 0 and "No results found" not in output_text and "LookupError" not in output_text:
            file_path = find_valid_audio_file(temp_dir)
            if file_path:
                return file_path

    fallback_dir = os.path.join(DOWNLOAD_DIR, f"spotify_fallback_{job_id}")
    os.makedirs(fallback_dir, exist_ok=True)
    clean_dir(fallback_dir)

    ydl_opts = {
        "format": "bestaudio/best",
        "outtmpl": os.path.join(fallback_dir, "%(title)s.%(ext)s"),
        "noplaylist": True,
        "quiet": True,
        "no_warnings": True,
        "socket_timeout": REQUEST_TIMEOUT_SECONDS,
        "extract_flat": False,
    }

    try:
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(normalized_url, download=True)
            if info is not None:
                file_path = find_valid_audio_file(fallback_dir)
                if file_path:
                    return file_path
    except Exception:
        pass

    raise Exception("Spotify link not found or no matching track was available")


def download_soundcloud(url: str, job_id: str):
    temp_dir = os.path.join(DOWNLOAD_DIR, f"soundcloud_{job_id}")
    os.makedirs(temp_dir, exist_ok=True)
    clean_dir(temp_dir)

    output = os.path.join(temp_dir, "%(title)s.%(ext)s")
    options = {
        "format": "bestaudio/best",
        "outtmpl": output,
        "noplaylist": True,
        "quiet": True,
        "no_warnings": True,
        "socket_timeout": REQUEST_TIMEOUT_SECONDS,
        "extract_flat": False,
        "http_headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
            "Referer": "https://soundcloud.com/",
        },
    }

    info = None
    with yt_dlp.YoutubeDL(options) as ydl:
        info = ydl.extract_info(normalize_url(url), download=True)

    if info is None:
        raise Exception("Audio info not found")

    file_path = find_valid_audio_file(temp_dir)
    if file_path:
        return file_path

    prepared = yt_dlp.YoutubeDL({"quiet": True, "skip_download": True}).prepare_filename(info)
    if prepared and os.path.exists(prepared):
        return prepared

    raise FileNotFoundError("SoundCloud file not found after download")


def download_audio(url: str, job_id: str):
    url = normalize_url(url)
    if is_spotify(url):
        return download_spotify(url, job_id)
    return download_soundcloud(url, job_id)


async def update_progress(message, job_id: str, title: str, size_text: str):
    last_text = ""
    while job_id in active_downloads:
        job = active_downloads[job_id]
        if job.get("finished") or job.get("cancelled"):
            break

        percent_text = str(job.get("percent", "0%"))
        try:
            percent = float(percent_text.replace("%", ""))
        except Exception:
            percent = 0

        text = (
            f"⬇️ در حال دانلود...\n\n"
            f"🎬 {title[:80]}\n\n"
            f"{progress_bar(percent)} {percent_text}\n\n"
            f"📦 حجم: {size_text}\n"
            f"⚡ سرعت: {job.get('speed', 'نامشخص')}\n"
            f"⏱ زمان باقی‌مانده: {job.get('eta', '؟')}"
        )

        if text != last_text:
            try:
                await message.edit_text(
                    text,
                    reply_markup=InlineKeyboardMarkup([
                        [InlineKeyboardButton("❌ لغو دانلود", callback_data=f"cancel|{job_id}")]
                    ]),
                )
                last_text = text
            except Exception:
                pass

        await asyncio.sleep(2)


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "سلام داش 👋\n\n"
        "🔗 لینک YouTube، Instagram، SoundCloud یا Spotify را بفرست.\n\n"
        "YouTube → انتخاب کیفیت\n"
        "Instagram → دانلود Reel / Video / Carousel\n"
        "SoundCloud / Spotify → دانلود آهنگ"
    )


async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    url = normalize_url(update.message.text.strip())
    if not any([is_youtube(url), is_instagram(url), is_soundcloud(url), is_spotify(url)]):
        await update.message.reply_text("❌ این لینک YouTube، Instagram، SoundCloud یا Spotify نیست.")
        return

    message = await update.message.reply_text("🔎 دارم اطلاعات فایل را پیدا می‌کنم...")

    try:
        if is_youtube(url):
            title, qualities = await asyncio.to_thread(get_youtube_qualities, url)
            if not qualities:
                await message.edit_text("❌ کیفیت قابل دانلودی پیدا نکردم.")
                return

            buttons = [
                [
                    InlineKeyboardButton(
                        f"🎬 {quality}p",
                        callback_data=f"yt|{quality}|{make_callback_token(url)}",
                    )
                ]
                for quality in qualities
            ]
            await message.edit_text(
                f"🎬 عنوان:\n{title}\n\n📺 کیفیت‌های موجود:\nیکی را انتخاب کن:",
                reply_markup=InlineKeyboardMarkup(buttons),
            )
            return

        if is_soundcloud(url) or is_spotify(url):
            title = "Audio"
            uploader = ""
            source_name = "SoundCloud" if is_soundcloud(url) else "Spotify"

            try:
                info = await asyncio.to_thread(get_audio_info, url)
                if isinstance(info, dict):
                    title = info.get("title", title)
                    uploader = info.get("uploader", uploader)
            except Exception:
                pass

            await message.edit_text(
                f"🎵 {source_name}\n\n"
                f"🎼 {str(title)[:120]}\n"
                f"🎤 {str(uploader)[:80]}\n\n"
                f"⬇️ در حال دانلود..."
            )

            filename = await asyncio.to_thread(
                download_audio,
                url,
                f"{source_name.lower()}_{update.effective_user.id}",
            )
            if not filename or not os.path.exists(filename):
                raise Exception(f"Downloaded {source_name} file not found")

            with open(filename, "rb") as audio_file:
                await update.message.reply_audio(
                    audio=audio_file,
                    title=str(title)[:255],
                    performer=str(uploader)[:255] if uploader else None,
                    caption=f"🎵 {title}",
                )

            os.remove(filename)
            await message.delete()
            return

        info = await asyncio.wait_for(asyncio.to_thread(safe_parth_get_info, url), timeout=REQUEST_TIMEOUT_SECONDS)
        if not isinstance(info, dict):
            raise Exception("Instagram metadata invalid")

        title = info.get("title", "Instagram")
        post_type = info.get("type", "")
        images = info.get("images") or []

        if post_type == "carousel":
            token = make_callback_token(url)
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton(f"📸 دانلود همه {len(images)} عکس", callback_data=f"igcarousel|{token}")]
            ])
            await message.edit_text(
                f"📸 این پست یک Carousel است.\n\n🎬 {title[:150]}\n\n🖼 تعداد عکس‌ها: {len(images)}",
                reply_markup=keyboard,
            )
        elif images:
            token = make_callback_token(url)
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton("📸 دانلود عکس", callback_data=f"igcarousel|{token}")]
            ])
            await message.edit_text(
                f"📸 عکس پیدا شد.\n\n🎬 {title[:150]}",
                reply_markup=keyboard,
            )
        else:
            token = make_callback_token(url)
            keyboard = InlineKeyboardMarkup([
                [InlineKeyboardButton("📥 دانلود Instagram", callback_data=f"ig|{token}")]
            ])
            await message.edit_text(f"🎬 {title[:150]}", reply_markup=keyboard)

    except Exception as exc:
        print("INFO ERROR:")
        print(exc)
        await message.edit_text(
            "❌ نتوانستم اطلاعات این لینک را دریافت کنم.\n\n"
            "اگر Instagram هست، ممکن است پست خصوصی یا محدود شده باشد."
        )


async def quality_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    data = query.data.split("|", 2)
    if len(data) < 3:
        return

    quality = int(data[1])
    token = data[2]
    url = resolve_callback_url(token) or token
    if not url:
        await query.edit_message_text("❌ لینک منقضی شده است. دوباره تلاش کنید.")
        return

    job_id = f"{update.effective_user.id}_{query.message.message_id}"
    active_downloads[job_id] = {
        "cancelled": False,
        "finished": False,
        "percent": "0%",
        "speed": "در حال شروع...",
        "eta": "؟",
    }

    try:
        info = await asyncio.to_thread(get_youtube_info, url)
        title = info.get("title", "YouTube")

        size_text = "در حال محاسبه..."
        for fmt in info.get("formats", []):
            if fmt.get("height") == quality and fmt.get("filesize"):
                size_text = format_size(fmt["filesize"])
                break

        await query.edit_message_text(
            f"⬇️ آماده دانلود...\n\n🎬 {title[:80]}\n📺 کیفیت: {quality}p\n📦 حجم: {size_text}"
        )

        progress_task = asyncio.create_task(update_progress(query.message, job_id, title, size_text))
        filename = await asyncio.to_thread(download_youtube_video, url, quality, job_id)

        active_downloads[job_id]["finished"] = True
        await progress_task

        if not os.path.exists(filename):
            raise Exception("Downloaded file not found")

        await query.message.edit_text("📤 دانلود کامل شد.\nدارم ویدیو را می‌فرستم...")
        with open(filename, "rb") as video:
            await query.message.reply_video(
                video=video,
                supports_streaming=True,
                caption=f"🎬 {title}\n📺 کیفیت: {quality}p",
            )
        os.remove(filename)
        await query.message.reply_text("✅ تمام شد!")

    except yt_dlp.utils.DownloadCancelled:
        try:
            await query.message.edit_text("❌ دانلود لغو شد.")
        except Exception:
            pass
    except Exception as exc:
        print("DOWNLOAD ERROR:")
        print(exc)
        try:
            await query.message.reply_text("❌ هنگام دانلود خطایی رخ داد.")
        except Exception:
            pass
    finally:
        active_downloads.pop(job_id, None)


async def instagram_selected(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    token = query.data.split("|", 1)[1]
    url = resolve_callback_url(token) or token
    if not url:
        await query.edit_message_text("❌ لینک منقضی شده است. دوباره تلاش کنید.")
        return

    job_id = f"{update.effective_user.id}_{query.message.message_id}"
    active_downloads[job_id] = {
        "cancelled": False,
        "finished": False,
        "percent": "0%",
        "speed": "در حال شروع...",
        "eta": "؟",
    }

    try:
        info = await asyncio.wait_for(asyncio.to_thread(safe_parth_get_info, url), timeout=REQUEST_TIMEOUT_SECONDS)
        title = info.get("title", "Instagram") if isinstance(info, dict) else "Instagram"

        await query.edit_message_text(f"⬇️ دانلود Instagram شروع شد...\n\n🎬 {title[:80]}")
        progress_task = asyncio.create_task(update_progress(query.message, job_id, title, "در حال محاسبه..."))

        filename = await asyncio.to_thread(download_instagram_media, url, job_id)
        active_downloads[job_id]["finished"] = True
        await progress_task

        if not os.path.exists(filename):
            raise Exception("Instagram file not found")

        extension = os.path.splitext(filename)[1].lower()
        await query.message.edit_text("📤 دانلود تمام شد.\nدارم فایل را می‌فرستم...")

        with open(filename, "rb") as media:
            if extension in [".jpg", ".jpeg", ".png", ".webp"]:
                await query.message.reply_photo(photo=media, caption=f"📸 {title}")
            else:
                await query.message.reply_video(video=media, supports_streaming=True, caption=f"🎬 {title}")

        os.remove(filename)
        await query.message.reply_text("✅ تمام شد!")

    except yt_dlp.utils.DownloadCancelled:
        try:
            await query.message.edit_text("❌ دانلود لغو شد.")
        except Exception:
            pass
    except Exception as exc:
        print("INSTAGRAM ERROR:")
        print(exc)
        await query.message.reply_text(
            "❌ نتوانستم این محتوای Instagram را دانلود کنم.\n\n"
            "ممکن است خصوصی باشد یا Instagram دسترسی را محدود کرده باشد."
        )
    finally:
        active_downloads.pop(job_id, None)


async def instagram_carousel(update, context):
    query = update.callback_query
    await query.answer()

    token = query.data.split("|", 1)[1]
    url = resolve_callback_url(token) or token
    if not url:
        await query.edit_message_text("❌ لینک منقضی شده است. دوباره تلاش کنید.")
        return

    job_id = f"{update.effective_user.id}_{query.message.message_id}"
    active_downloads[job_id] = {
        "cancelled": False,
        "finished": False,
        "percent": "0%",
        "speed": "در حال شروع...",
        "eta": "؟",
    }

    try:
        info = await asyncio.wait_for(asyncio.to_thread(safe_parth_get_info, url), timeout=REQUEST_TIMEOUT_SECONDS)
        images = info.get("images", []) if isinstance(info, dict) else []
        title = info.get("title", "Instagram") if isinstance(info, dict) else "Instagram"

        if not images:
            raise Exception("No Instagram images found")

        await query.edit_message_text(f"📸 پست شامل {len(images)} عکس است.\n\n⬇️ در حال دانلود...")

        files = await asyncio.to_thread(download_instagram_images, url, job_id)
        active_downloads[job_id]["finished"] = True

        await query.edit_message_text(f"📤 دانلود {len(files)} عکس کامل شد.\nدارم می‌فرستم...")
        for index, filename in enumerate(files, start=1):
            if os.path.exists(filename):
                with open(filename, "rb") as photo:
                    await query.message.reply_photo(photo=photo, caption=f"📸 {index}/{len(files)}\n{title[:100]}")

        await query.message.reply_text(f"✅ همه {len(files)} عکس ارسال شد.")
        folder = os.path.dirname(files[0]) if files else ""
        if folder:
            shutil.rmtree(folder, ignore_errors=True)

    except Exception as exc:
        print("INSTAGRAM CAROUSEL ERROR:")
        print(exc)
        await query.message.reply_text(f"❌ دانلود Instagram شکست خورد.\n\n{exc}")
    finally:
        active_downloads.pop(job_id, None)


async def cancel_download(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer("در حال لغو...")

    job_id = query.data.split("|", 1)[1]
    if job_id in active_downloads:
        active_downloads[job_id]["cancelled"] = True
        try:
            await query.edit_message_text("⛔ در حال لغو دانلود...")
        except Exception:
            pass
    else:
        await query.answer("این دانلود قبلاً تمام شده.")


def main():
    app = Application.builder().token(TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    app.add_handler(CallbackQueryHandler(quality_selected, pattern=r"^yt\|"))
    app.add_handler(CallbackQueryHandler(instagram_selected, pattern=r"^ig\|"))
    app.add_handler(CallbackQueryHandler(instagram_carousel, pattern=r"^igcarousel\|"))
    app.add_handler(CallbackQueryHandler(cancel_download, pattern=r"^cancel\|"))
    print("Bot is running...")
    app.run_polling()


if __name__ == "__main__":
    main()
python cmd bots telegram-bot