Telegram Bot To Download Youtube Playlist -
pip install python-telegram-bot[job-queue] yt-dlp asyncio aiofiles mkdir downloads temp_files logs 3. Core Design & Architecture | Component | Responsibility | |-----------|----------------| | Telegram Handler | Receives messages, validates URLs, manages user state | | Download Worker | Uses yt-dlp to fetch playlist metadata & download files | | Queue Manager | Prevents overload; processes one playlist per user sequentially | | File Sender | Uploads files to Telegram with progress feedback | | Cleaner | Deletes local files after sending (or after 1 hour) | 4. Implementation Step-by-Step 4.1 Basic Bot Skeleton Create bot.py :
import logging from telegram.ext import Application, CommandHandler, MessageHandler, filters from config import BOT_TOKEN logging.basicConfig(level=logging.INFO) logger = logging.getLogger()
await context.bot.send_message(chat_id, "✅ Playlist download completed.") Add before sending: Telegram Bot To Download Youtube Playlist
async def handle_message(update, context): url = update.message.text.strip() if "youtube.com/playlist" not in url and "youtu.be" not in url: await update.message.reply_text("Please send a valid YouTube playlist URL.") return
async def process_playlist(chat_id, url, format_type, context): # Step 1: Get playlist entries loop = asyncio.get_event_loop() try: videos = await loop.run_in_executor(executor, get_playlist_info, url) except Exception as e: await context.bot.send_message(chat_id, f"Failed to fetch playlist: e") return if not videos: await context.bot.send_message(chat_id, "No videos found or playlist empty.") return InlineKeyboardButton("🎬 Video (MP4)"
async def start(update, context): await update.message.reply_text( "Send me a YouTube playlist URL.\n" "I'll download up to 15 videos (audio or video)." )
# Store URL in user_data context.user_data['playlist_url'] = url buttons = [[ InlineKeyboardButton("🎵 Audio (MP3)", callback_data="audio"), InlineKeyboardButton("🎬 Video (MP4)", callback_data="video") ]] await update.message.reply_text( "Choose format:", reply_markup=InlineKeyboardMarkup(buttons) ) def main(): app = Application.builder().token(BOT_TOKEN).build() app.add_handler(CommandHandler("start", start)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) app.run_polling() download=False) entries = info.get('entries'
def get_playlist_info(url): ydl_opts = 'quiet': True, 'extract_flat': True with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) entries = info.get('entries', []) return ['id': e['id'], 'title': e['title'], 'url': f"https://youtube.com/watch?v=e['id']" for e in entries[:15]] # limit to 15
app.add_handler(CallbackQueryHandler(format_choice)) Create downloader.py :
# Start download process in background context.application.create_task( process_playlist(update.effective_chat.id, url, choice, context) )