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
# 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()
await context.bot.send_message(chat_id, "✅ Playlist download completed.") Add before sending:
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
# Start download process in background context.application.create_task( process_playlist(update.effective_chat.id, url, choice, context) )
Add to main:
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 :
if == " main ": main() 4.2 Add Inline Keyboard & Callback from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import CallbackQueryHandler async def format_choice(update: Update, context): query = update.callback_query await query.answer() choice = query.data # 'audio' or 'video' context.user_data['format'] = choice url = context.user_data['playlist_url']
await query.edit_message_text(f"⏳ Fetching playlist: url\nThis may take a moment...")
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)." )
with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) # return actual file path info = ydl.extract_info(video_url, download=False) filename = ydl.prepare_filename(info).replace('.webm', '.mp4') return filename
def download_audio(video_url, output_path): ydl_opts = 'outtmpl': f'output_path/%(title)s.%(ext)s', 'format': 'bestaudio/best', 'postprocessors': [ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', ], 'quiet': True,
import logging from telegram.ext import Application, CommandHandler, MessageHandler, filters from config import BOT_TOKEN logging.basicConfig(level=logging.INFO) logger = logging.getLogger()
def progress_hook(d): if d['status'] == 'downloading': percent = d.get('_percent_str', '0%').strip() # send update via callback (store chat_id in closure) 6.1 Running as a Service (systemd) Create /etc/systemd/system/ytdlbot.service :
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
# 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()
await context.bot.send_message(chat_id, "✅ Playlist download completed.") Add before sending:
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 Telegram Bot To Download Youtube Playlist
# Start download process in background context.application.create_task( process_playlist(update.effective_chat.id, url, choice, context) )
Add to main:
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 : def get_playlist_info(url): ydl_opts = 'quiet': True
if == " main ": main() 4.2 Add Inline Keyboard & Callback from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import CallbackQueryHandler async def format_choice(update: Update, context): query = update.callback_query await query.answer() choice = query.data # 'audio' or 'video' context.user_data['format'] = choice url = context.user_data['playlist_url']
await query.edit_message_text(f"⏳ Fetching playlist: url\nThis may take a moment...")
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)." ) download=False) entries = info.get('entries'
with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) # return actual file path info = ydl.extract_info(video_url, download=False) filename = ydl.prepare_filename(info).replace('.webm', '.mp4') return filename
def download_audio(video_url, output_path): ydl_opts = 'outtmpl': f'output_path/%(title)s.%(ext)s', 'format': 'bestaudio/best', 'postprocessors': [ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', ], 'quiet': True,
import logging from telegram.ext import Application, CommandHandler, MessageHandler, filters from config import BOT_TOKEN logging.basicConfig(level=logging.INFO) logger = logging.getLogger()
def progress_hook(d): if d['status'] == 'downloading': percent = d.get('_percent_str', '0%').strip() # send update via callback (store chat_id in closure) 6.1 Running as a Service (systemd) Create /etc/systemd/system/ytdlbot.service :