Hello! Can you improve it? Like add more abilities, more productivity, more ability to…
- User
Hello! Can you improve it? Like add more abilities, more productivity, more ability to work with ppls more than 2, etc. from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message, CallbackQuery import yt_dlp import os import subprocess import re import requests import json from typing import Dict, Optional import asyncio from datetime import datetime from urllib.parse import urlparse, parse_qs, urlencode, urlunparse
def clean_url(url: str) -> str: print(f"Original URL: {url}") parsed_url = urlparse(url) query_params = parse_qs(parsed_url.query) print(f"Parsed params: {query_params}")
filtered_params = {key: value for key, value in query_params.items() if key in ['v', 'list']} print(f"Filtered params: {filtered_params}") cleaned_url = urlunparse(( parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.params, urlencode(filtered_params, doseq=True), parsed_url.fragment )) print(f"Cleaned URL: {cleaned_url}") return cleaned_urlREQUIRED_DIRS = { "downloads": "downloads", "user_data": "user_data", "config": "config", "ffmpeg": "ffmpeg" }
API_ID = 22860593 API_HASH = "2c8e567c3ffd9fc454bb23fc89c90613" BOT_TOKEN = "7899250591:AAE5ofl1icrEwsmuC39oEEo4Q9SzHYghsN0"
TEMP_DIR = REQUIRED_DIRS["downloads"] USER_DATA_DIR = REQUIRED_DIRS["user_data"] USER_PREFS_FILE = os.path.join(USER_DATA_DIR, "user_preferences.json") QUALITIES = ["potato", "144p", "360p", "480p", "720p", "1080p"]
def load_translations(): try: with open(os.path.join('config', 'languages.json'), 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: return {}
TRANSLATIONS = load_translations()
class UserPreferences: def init(self): self.prefs = self._load_preferences()
def _load_preferences(self) -> Dict: if os.path.exists(USER_PREFS_FILE): with open(USER_PREFS_FILE, 'r', encoding='utf-8') as f: return json.load(f) return {} def _save_preferences(self): with open(USER_PREFS_FILE, 'w', encoding='utf-8') as f: json.dump(self.prefs, f, indent=4) def get_user_prefs(self, user_id: str) -> Dict: user_id = str(user_id) if user_id not in self.prefs: self.prefs[user_id] = {"lang": "en", "quality": "720p"} self._save_preferences() return self.prefs[user_id] def update_user_prefs(self, user_id: str, lang: Optional[str] = None, quality: Optional[str] = None): user_id = str(user_id) if user_id not in self.prefs: self.prefs[user_id] = {} if lang is not None: self.prefs[user_id]["lang"] = lang if quality is not None: self.prefs[user_id]["quality"] = quality self._save_preferences()user_prefs = UserPreferences() app = Client("tiktok_youtube_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
class ProgressBar: def init(self, message, user_id): self.message = message self.user_id = user_id self.last_update = datetime.now() self.last_percentage = 0
async def update(self, d): if d['status'] == 'downloading': downloaded = d.get('downloaded_bytes', 0) total = d.get('total_bytes', 0) or d.get('total_bytes_estimate', 0) if total > 0: percentage = int((downloaded * 100) / total) now = datetime.now() if (now - self.last_update).seconds >= 1 and percentage != self.last_percentage: try: await self.message.edit_text( get_text(self.user_id, "downloading", progress=percentage) ) self.last_update = now self.last_percentage = percentage except: passdef get_ffmpeg_path() -> str: common_paths = ["ffmpeg", r"C:\ffmpeg\bin\ffmpeg.exe", r"ffmpeg\ffmpeg.exe", os.path.join(os.path.dirname(file), "ffmpeg", "ffmpeg.exe")] for path in common_paths: try: subprocess.run([path, "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return path except (subprocess.SubprocessError, FileNotFoundError): continue raise FileNotFoundError("ffmpeg not found")
def get_text(user_id: int, key: str, **kwargs) -> str: prefs = user_prefs.get_user_prefs(str(user_id)) lang = prefs["lang"] if lang not in TRANSLATIONS: lang = "en" return TRANSLATIONS[lang][key].format(**kwargs)
def expand_short_url(url: str) -> str: try: response = requests.head(url, allow_redirects=True, timeout=10) return response.url except: return url
def extract_video_info(url: str) -> tuple: if 'vm.tiktok.com' in url: url = url.replace('vm.tiktok.com', 'vt.tiktok.com')
if 'tiktok.com' in url: if 'vt.tiktok.com' in url: url = expand_short_url(url) match = re.search(r'tiktok\.com/.+/video/(\d+)', url) return ('tiktok', match.group(1) if match else None, False) elif 'youtu.be' in url or 'youtube.com' in url: is_playlist = 'playlist' in url or 'list=' in url if 'youtu.be' in url: video_id = url.split('/')[-1].split('?')[0] else: match = re.search(r'(?:v=|/v/|/embed/|/watch\?v=)([^&\n?]+)', url) video_id = match.group(1) if match else None return ('youtube', video_id, is_playlist) return (None, None, False)def get_format_for_quality(quality: str, platform: str) -> str: if platform == 'youtube': quality_map = { "potato": "worst[ext=mp4]", "144p": "worst[height<=144][ext=mp4]", "360p": "bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360][ext=mp4]", "480p": "bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]", "720p": "bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]", "1080p": "bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080][ext=mp4]" } else: quality_map = { "potato": "worst[ext=mp4]", "144p": "worst[height<=144][ext=mp4]", "360p": "worst[height<=360][ext=mp4]", "480p": "worst[height<=480][ext=mp4]", "720p": "best[height<=720][ext=mp4]", "1080p": "best[height<=1080][ext=mp4]" } return quality_map.get(quality, "best[ext=mp4]")
import os
async def download_video(url: str, output_path: str, quality: str, platform: str, progress_callback=None) -> bool: if platform == 'tiktok' and 'vt.tiktok.com' in url: url = expand_short_url(url) format_string = get_format_for_quality(quality, platform)
cookies_path = os.path.join(os.getcwd(), 'cookies.txt') ydl_opts = { 'outtmpl': output_path, 'quiet': True, 'format': format_string, 'progress_hooks': [progress_callback] if progress_callback else None } if os.path.exists(cookies_path): ydl_opts['cookiefile'] = cookies_path try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except: return Falseasync def download_audio(url: str, output_path: str, progress_callback=None) -> bool: ydl_opts = { 'format': 'bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': output_path, 'progress_hooks': [progress_callback] if progress_callback else None, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', }], } try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except: return False
async def download_playlist(url: str, message: Message, user_id: int, quality: str): ydl_opts = { 'quiet': True, 'extract_flat': True, 'force_generic_extractor': False }
try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info(url, download=False) if 'entries' in result: total_videos = len(result['entries']) await message.reply_text(get_text(user_id, "playlist_detected", count=total_videos)) success_count = 0 for index, entry in enumerate(result['entries'], 1): if entry: video_url = f"https://www.youtube.com/watch?v={entry['id']}" status_message = await message.reply_text( get_text(user_id, "downloading_playlist", current=index, total=total_videos) ) progress_bar = ProgressBar(status_message, user_id) output_path = os.path.join(TEMP_DIR, f"playlist_{index}_{user_id}.mp4") if await download_video(video_url, output_path, quality, 'youtube', progress_bar.update): try: await message.reply_video(output_path) success_count += 1 except Exception as e: print(f"Error sending video: {e}") finally: if os.path.exists(output_path): os.remove(output_path) await status_message.delete() if success_count == total_videos: await message.reply_text(get_text(user_id, "playlist_complete")) else: await message.reply_text(get_text(user_id, "playlist_failed")) except Exception as e: print(f"Playlist download error: {e}") await message.reply_text(get_text(user_id, "download_failed"))def create_language_keyboard() -> InlineKeyboardMarkup: keyboard = [] row = [] for lang_code in TRANSLATIONS.keys(): row.append(InlineKeyboardButton(lang_code.upper(), callback_data=f"lang|{lang_code}")) if len(row) == 3: keyboard.append(row) row = [] if row: keyboard.append(row) return InlineKeyboardMarkup(keyboard)
def create_quality_keyboard() -> InlineKeyboardMarkup: keyboard = [] row = [] for quality in QUALITIES: row.append(InlineKeyboardButton(quality, callback_data=f"quality|{quality}")) if len(row) == 2: keyboard.append(row) row = [] if row: keyboard.append(row) return InlineKeyboardMarkup(keyboard)
def clean_url(url: str) -> str: parsed_url = urlparse(url) query_params = parse_qs(parsed_url.query) filtered_params = {key: value for key, value in query_params.items() if key == 'v'}
cleaned_url = urlunparse(( parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.params, urlencode(filtered_params, doseq=True), parsed_url.fragment )) return cleaned_urlREQUIRED_DIRS = { "downloads": "downloads", "user_data": "user_data", "config": "config", "ffmpeg": "ffmpeg" }
def setup_directories(): for dir_name in REQUIRED_DIRS.values(): os.makedirs(dir_name, exist_ok=True)
languages_file = os.path.join('config', 'languages.json') if not os.path.exists(languages_file): default_translations = { "en": { "start": "Welcome! Send me a TikTok or YouTube link to download.", "select_lang": "Please select your language:", "select_quality": "Please select video quality:", "settings_updated": "Settings updated successfully!", "current_settings": "Current settings:\nLanguage: {lang}\nQuality: {quality}", "invalid_url": "Invalid URL. Please send a TikTok or YouTube link.", "downloading": "Downloading... {progress}%", "processing": "Processing...", "download_failed": "Download failed. Please try again.", "ffmpeg_error": "Error processing video.", "choose_option": "Video ID: {video_id}\nChoose download option:", "with_sound": "With Sound", "without_sound": "Without Sound", "settings": "Settings", "audio_only": "Audio Only", "playlist_detected": "Playlist detected! Total videos: {count}", "downloading_playlist": "Downloading playlist... Video {current}/{total}", "playlist_complete": "Playlist download complete!", "playlist_failed": "Some videos in playlist failed to download." } } with open(languages_file, 'w', encoding='utf-8') as f: json.dump(default_translations, f, indent=4, ensure_ascii=False)API_ID = 22860593 API_HASH = "2c8e567c3ffd9fc454bb23fc89c90613" BOT_TOKEN = "7899250591:AAE5ofl1icrEwsmuC39oEEo4Q9SzHYghsN0"
TEMP_DIR = REQUIRED_DIRS["downloads"] USER_DATA_DIR = REQUIRED_DIRS["user_data"] USER_PREFS_FILE = os.path.join(USER_DATA_DIR, "user_preferences.json") QUALITIES = ["potato", "144p", "360p", "480p", "720p", "1080p"]
def load_translations(): try: with open(os.path.join('config', 'languages.json'), 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: return {}
TRANSLATIONS = load_translations()
class UserPreferences: def init(self): self.prefs = self._load_preferences()
def _load_preferences(self) -> Dict: if os.path.exists(USER_PREFS_FILE): with open(USER_PREFS_FILE, 'r', encoding='utf-8') as f: return json.load(f) return {} def _save_preferences(self): with open(USER_PREFS_FILE, 'w', encoding='utf-8') as f: json.dump(self.prefs, f, indent=4) def get_user_prefs(self, user_id: str) -> Dict: user_id = str(user_id) if user_id not in self.prefs: self.prefs[user_id] = {"lang": "en", "quality": "720p"} self._save_preferences() return self.prefs[user_id] def update_user_prefs(self, user_id: str, lang: Optional[str] = None, quality: Optional[str] = None): user_id = str(user_id) if user_id not in self.prefs: self.prefs[user_id] = {} if lang is not None: self.prefs[user_id]["lang"] = lang if quality is not None: self.prefs[user_id]["quality"] = quality self._save_preferences()user_prefs = UserPreferences() app = Client("tiktok_youtube_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
class ProgressBar: def init(self, message, user_id): self.message = message self.user_id = user_id self.last_update = datetime.now() self.last_percentage = 0
async def update(self, d): if d['status'] == 'downloading': downloaded = d.get('downloaded_bytes', 0) total = d.get('total_bytes', 0) or d.get('total_bytes_estimate', 0) if total > 0: percentage = int((downloaded * 100) / total) now = datetime.now() if (now - self.last_update).seconds >= 1 and percentage != self.last_percentage: try: await self.message.edit_text( get_text(self.user_id, "downloading", progress=percentage) ) self.last_update = now self.last_percentage = percentage except: passdef get_ffmpeg_path() -> str: common_paths = ["ffmpeg", r"C:\ffmpeg\bin\ffmpeg.exe", r"ffmpeg\ffmpeg.exe", os.path.join(os.path.dirname(file), "ffmpeg", "ffmpeg.exe")] for path in common_paths: try: subprocess.run([path, "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return path except (subprocess.SubprocessError, FileNotFoundError): continue raise FileNotFoundError("ffmpeg not found")
def get_text(user_id: int, key: str, **kwargs) -> str: prefs = user_prefs.get_user_prefs(str(user_id)) lang = prefs["lang"] if lang not in TRANSLATIONS: lang = "en" return TRANSLATIONS[lang][key].format(**kwargs)
def expand_short_url(url: str) -> str: try: response = requests.head(url, allow_redirects=True, timeout=10) return response.url except: return url
def extract_video_info(url: str) -> tuple: if 'vm.tiktok.com' in url: url = url.replace('vm.tiktok.com', 'vt.tiktok.com')
if 'tiktok.com' in url: if 'vt.tiktok.com' in url: url = expand_short_url(url) match = re.search(r'tiktok\.com/.+/video/(\d+)', url) return ('tiktok', match.group(1) if match else None, False) elif 'youtu.be' in url or 'youtube.com' in url: is_playlist = 'playlist' in url or 'list=' in url if 'youtu.be' in url: video_id = url.split('/')[-1].split('?')[0] else: match = re.search(r'(?:v=|/v/|/embed/|/watch\?v=)([^&\n?]+)', url) video_id = match.group(1) if match else None return ('youtube', video_id, is_playlist) return (None, None, False)def get_format_for_quality(quality: str, platform: str) -> str: if platform == 'youtube': quality_map = { "potato": "worst[ext=mp4]", "144p": "worst[height<=144][ext=mp4]", "360p": "bestvideo[height<=360][ext=mp4]+bestaudio[ext=m4a]/best[height<=360][ext=mp4]", "480p": "bestvideo[height<=480][ext=mp4]+bestaudio[ext=m4a]/best[height<=480][ext=mp4]", "720p": "bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]", "1080p": "bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080][ext=mp4]" } else: quality_map = { "potato": "worst[ext=mp4]", "144p": "worst[height<=144][ext=mp4]", "360p": "worst[height<=360][ext=mp4]", "480p": "worst[height<=480][ext=mp4]", "720p": "best[height<=720][ext=mp4]", "1080p": "best[height<=1080][ext=mp4]" } return quality_map.get(quality, "best[ext=mp4]")
import os
async def download_video(url: str, output_path: str, quality: str, platform: str, progress_callback=None) -> bool: if platform == 'tiktok' and 'vt.tiktok.com' in url: url = expand_short_url(url) format_string = get_format_for_quality(quality, platform)
cookies_path = os.path.join(os.getcwd(), 'cookies.txt') ydl_opts = { 'outtmpl': output_path, 'quiet': True, 'format': format_string, 'progress_hooks': [progress_callback] if progress_callback else None } if os.path.exists(cookies_path): ydl_opts['cookiefile'] = cookies_path try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except: return Falseasync def download_audio(url: str, output_path: str, progress_callback=None) -> bool: ydl_opts = { 'format': 'bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': output_path, 'progress_hooks': [progress_callback] if progress_callback else None, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', }], } try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) return True except: return False
async def download_playlist(url: str, message: Message, user_id: int, quality: str): ydl_opts = { 'quiet': True, 'extract_flat': True, 'force_generic_extractor': False }
try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: result = ydl.extract_info(url, download=False) if 'entries' in result: total_videos = len(result['entries']) await message.reply_text(get_text(user_id, "playlist_detected", count=total_videos)) success_count = 0 for index, entry in enumerate(result['entries'], 1): if entry: video_url = f"https://www.youtube.com/watch?v={entry['id']}" status_message = await message.reply_text( get_text(user_id, "downloading_playlist", current=index, total=total_videos) ) progress_bar = ProgressBar(status_message, user_id) output_path = os.path.join(TEMP_DIR, f"playlist_{index}_{user_id}.mp4") if await download_video(video_url, output_path, quality, 'youtube', progress_bar.update): try: await message.reply_video(output_path) success_count += 1 except Exception as e: print(f"Error sending video: {e}") finally: if os.path.exists(output_path): os.remove(output_path) await status_message.delete() if success_count == total_videos: await message.reply_text(get_text(user_id, "playlist_complete")) else: await message.reply_text(get_text(user_id, "playlist_failed")) except Exception as e: print(f"Playlist download error: {e}") await message.reply_text(get_text(user_id, "download_failed"))def create_language_keyboard() -> InlineKeyboardMarkup: keyboard = [] row = [] for lang_code in TRANSLATIONS.keys(): row.append(InlineKeyboardButton(lang_code.upper(), callback_data=f"lang|{lang_code}")) if len(row) == 3: keyboard.append(row) row = [] if row: keyboard.append(row) return InlineKeyboardMarkup(keyboard)
def create_quality_keyboard() -> InlineKeyboardMarkup: keyboard = [] row = [] for quality in QUALITIES: row.append(InlineKeyboardButton(quality, callback_data=f"quality|{quality}")) if len(row) == 2: keyboard.append(row) row = [] if row: keyboard.append(row) return InlineKeyboardMarkup(keyboard)
@app.on_callback_query() async def callback_handler(client: Client, callback_query: CallbackQuery): data = callback_query.data.split("|") action = data[0] user_id = callback_query.from_user.id
try: if action == "lang": lang = data[1] user_prefs.update_user_prefs(user_id, lang=lang) await callback_query.message.edit_text( get_text(user_id, "select_quality"), reply_markup=create_quality_keyboard() ) return if action == "quality": quality = data[1] user_prefs.update_user_prefs(user_id, quality=quality) prefs = user_prefs.get_user_prefs(str(user_id)) await callback_query.message.edit_text( get_text(user_id, "settings_updated") + "\n" + get_text(user_id, "current_settings", lang=prefs["lang"], quality=prefs["quality"]) ) return url = data[1] platform, video_id, is_playlist = extract_video_info(url) if not video_id and not is_playlist: await callback_query.message.edit_text(get_text(user_id, "invalid_url")) return current_prefs = user_prefs.get_user_prefs(str(user_id)) if is_playlist and platform == 'youtube': await download_playlist(url, callback_query.message, user_id, current_prefs["quality"]) return filename = f"{platform}_{video_id}_{user_id}" async def handle_video_download(): status_message = await callback_query.message.edit_text(get_text(user_id, "downloading", progress=0)) output_path = os.path.join(TEMP_DIR, f"{filename}.mp4") progress_bar = ProgressBar(status_message, user_id) try: if not await download_video(url, output_path, current_prefs["quality"], platform, progress_bar.update): await status_message.edit_text(get_text(user_id, "downloading_best_quality")) if not await download_video(url, output_path, "best", platform, progress_bar.update): await status_message.edit_text(get_text(user_id, "download_failed")) return await status_message.edit_text(get_text(user_id, "processing")) try: await callback_query.message.reply_video(output_path) finally: if os.path.exists(output_path): os.remove(output_path) except Exception as e: print(f"Error during video download: {e}") await status_message.edit_text(get_text(user_id, "unexpected_error")) async def handle_audio_download(): status_message = await callback_query.message.edit_text(get_text(user_id, "downloading", progress=0)) output_path = os.path.join(TEMP_DIR, f"{filename}.mp3") progress_bar = ProgressBar(status_message, user_id) try: if platform == 'youtube': if not await download_audio(url, output_path, progress_bar.update): await status_message.edit_text(get_text(user_id, "download_failed")) return if os.path.exists(output_path): try: await callback_query.message.reply_audio(output_path) finally: os.remove(output_path) else: await status_message.edit_text(get_text(user_id, "file_not_found")) else: await handle_video_download() except Exception as e: print(f"Error during audio download: {e}") await status_message.edit_text(get_text(user_id, "unexpected_error")) if action == "video": await handle_video_download() elif action == "audio": await handle_audio_download() except Exception as e: print(f"An error occurred: {e}") if callback_query.message: await callback_query.message.edit_text("An unexpected error occurred.")@app.on_message(filters.command(["start", "settings", "lang", "problems"]) | filters.regex(r"https?://(?:(?:www|vt|vm).)?(?:tiktok.com|youtube.com|youtu.be)/")) async def start(client: Client, message: Message): user_id = message.from_user.id
if message.command: if message.command[0] == "problems": try: with open("problems.txt", "r", encoding="utf-8") as file: problems_list = file.read() if problems_list.strip(): await message.reply_text(problems_list) else: await message.reply_text(get_text(user_id,"no_problems")) except FileNotFoundError: await message.reply_text(get_text(user_id,"no_problemsfile")) except Exception as e: await message.reply_text(get_text(user_id,"problem").format(str(e))) return if message.command[0] in ["settings", "lang"]: await message.reply_text( get_text(user_id, "select_lang"), reply_markup=create_language_keyboard() ) return await message.reply_text(get_text(user_id, "start")) else: url = message.text cleaned_url = clean_url(url) platform, video_id, is_playlist = extract_video_info(cleaned_url) if not video_id and not is_playlist: await message.reply_text(get_text(user_id, "invalid_url")) return if is_playlist and platform == 'youtube': current_prefs = user_prefs.get_user_prefs(str(user_id)) await download_playlist(cleaned_url, message, user_id, current_prefs["quality"]) return if platform == 'youtube': buttons = InlineKeyboardMarkup([ [ InlineKeyboardButton( get_text(user_id, "with_sound"), callback_data=f"video|{cleaned_url}" ), InlineKeyboardButton( get_text(user_id, "audio_only"), callback_data=f"audio|{cleaned_url}" ) ], [ InlineKeyboardButton( get_text(user_id, "settings"), callback_data="settings" ) ] ]) else: buttons = InlineKeyboardMarkup([ [ InlineKeyboardButton( get_text(user_id, "with_sound"), callback_data=f"video|{cleaned_url}" ), InlineKeyboardButton( get_text(user_id, "without_sound"), callback_data=f"audio|{cleaned_url}" ) ], [ InlineKeyboardButton( get_text(user_id, "settings"), callback_data="settings" ) ] ]) await message.reply_text( get_text(user_id, "choose_option", video_id=video_id), reply_markup=buttons )if name == "main": print("Bot now running!") setup_directories() app.run()
- Assistant
Hello! I'd be happy to help improve your Telegram bot code. From what you've shared, your bot allows users to download TikTok and YouTube videos, manage language and quality preferences, and handle playlists. I'll provide suggestions to enhance its capabilities, improve productivity, and ensure it can handle multiple users efficiently.
1. Clean Up Duplicate Code
Firstly, it looks like there are duplicate sections in your code. Cleaning up these duplicates will make your code more maintainable and reduce potential bugs.
Example of Duplicated Sections:
- The definition of
clean_url()appears twice. - Constants like
API_ID,API_HASH, andBOT_TOKENare defined multiple times. - The
UserPreferencesclass andload_translations()function are also duplicated.
Action: Remove the duplicated code sections to have a single, clean version of each function and class.
2. Improve Concurrency and Handle Multiple Users
To ensure your bot can handle multiple users simultaneously without issues, consider the following:
-
Avoid Global Variables: Ensure that any user-specific data is not stored in global variables that could be overwritten when another user interacts with the bot.
-
Use Asynchronous Functions Properly: Since you're using
asyncio, make sure all I/O operations, especially downloads and file handling, are awaited properly to prevent blocking other users. -
Thread Safety: If you're using libraries or resources that aren't thread-safe, make sure to use appropriate locks or consider alternatives.
Example Improvement:
Make sure each user's download is handled independently:
from threading import Semaphore download_semaphore = Semaphore(5) # Limit simultaneous downloads to 5 async def download_video(...): async with download_semaphore: # Download logic here
3. Enhance Download Capabilities
a. Support More Platforms
Expand your bot to support more platforms like Instagram, Vimeo, Facebook, etc.
yt_dlpsupports a wide range of sites.Implementation:
def extract_video_info(url: str) -> tuple: # Existing TikTok and YouTube detection # Add additional platform detections here if 'instagram.com' in url: return ('instagram', None, False) elif 'vimeo.com' in url: return ('vimeo', None, False) # ...b. Download Subtitles
Allow users to download subtitles if available.
Implementation:
async def download_subtitles(url: str, output_path: str, language: str = 'en'): ydl_opts = { 'writesubtitles': True, 'subtitleslangs': [language], 'skip_download': True, 'outtmpl': output_path, } # Download logic hereAdd options in your bot’s UI for users to select downloading subtitles.
c. Video Trimming
Allow users to specify start and end times to download only a portion of the video.
Implementation:
def get_video_trim_args(start_time: str, end_time: str) -> list: return ['-ss', start_time, '-to', end_time]Pass these arguments to
ffmpegduring the post-processing step.d. Audio Format Selection
Let users choose the audio format (MP3, AAC, WAV, etc.) when downloading audio.
Implementation:
async def download_audio(url: str, output_path: str, format: str = 'mp3'): ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': format, }], # Rest of the options }
4. Improve User Interaction
a. Progress Indicators
Utilize Telegram's built-in progress indicators when sending large files.
Implementation:
async def send_video(chat_id, video_path): await app.send_video( chat_id, video=video_path, progress=progress_callback, )b. Enhanced Inline Keyboards
Use more interactive elements in your bot's interface, such as inline queries or buttons with detailed options.
c. Handle Errors Gracefully
Ensure that any errors are caught and meaningful messages are sent back to the user.
5. Optimize Performance
a. Temporary File Management
Ensure temporary files are cleaned up promptly to save disk space.
Implementation:
import tempfile async def download_video(...): with tempfile.NamedTemporaryFile(delete=False) as temp_file: output_path = temp_file.name # Download logicb. Limit Download Size
Set a maximum file size limit to prevent the bot from attempting to download very large files that exceed Telegram's limits.
Implementation:
MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024 # 2 GB async def download_video(...): ydl_opts = { 'max_filesize': MAX_FILE_SIZE, # Rest of the options }
6. Refactor and Modularize Code
Organize your code into separate modules to improve readability and maintainability.
- bot.py # Main bot logic - download.py # Download functions - utils.py # Utility functions and helpers - config.py # Configuration and constants - handlers.py # Message and callback handlers
7. Use a Database for User Preferences
Instead of JSON files, use a lightweight database like SQLite for storing user preferences. This improves scalability and performance.
Implementation with SQLAlchemy:
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///user_prefs.db') Base = declarative_base() Session = sessionmaker(bind=engine) session = Session() class UserPreference(Base): __tablename__ = 'user_preferences' user_id = Column(Integer, primary_key=True) language = Column(String) quality = Column(String) # On startup Base.metadata.create_all(engine)
8. Implement Logging
Add logging to track bot activity and errors.
import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Use logger in your code logger.info("Bot started")
9. Handle Rate Limiting
To prevent hitting Telegram's rate limits, use
asyncio.sleep()or handling mechanisms provided by the Pyrogram library.
10. Ensure Compliance with Telegram's Terms
Make sure your bot complies with Telegram's terms of service, including avoiding sending large files that exceed their size limits.
Example of an Improved Function
Here's an example of how you might refactor your
download_videofunction to handle different platforms and include some of the above suggestions:async def download_video(url: str, user_id: int, format_option: str = 'video', start_time: str = None, end_time: str = None): platform, video_id, is_playlist = extract_video_info(url) output_ext = 'mp4' if format_option == 'video' else 'mp3' filename = f"{platform}_{video_id}_{user_id}.{output_ext}" output_path = os.path.join(TEMP_DIR, filename) ydl_opts = { 'outtmpl': output_path, 'format': get_format_for_quality(user_prefs.get_user_prefs(user_id)["quality"], platform), 'noplaylist': True, 'quiet': True, 'progress_hooks': [progress_callback], } if format_option == 'audio': ydl_opts['format'] = 'bestaudio/best' ydl_opts['postprocessors'] = [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', }] if start_time or end_time: ydl_opts['postprocessor_args'] = [] if start_time: ydl_opts['postprocessor_args'].extend(['-ss', start_time]) if end_time: ydl_opts['postprocessor_args'].extend(['-to', end_time]) try: with yt_dlp.YoutubeDL(ydl_opts) as ydl: await asyncio.get_event_loop().run_in_executor(None, ydl.download, [url]) return output_path except Exception as e: logger.error(f"Download failed: {e}") return None
11. Add User Authentication (Optional)
If you want to restrict access or add premium features, you can implement user authentication and manage user tiers.
12. Document Your Code
Add comments and docstrings to your functions and classes to explain their purpose and usage.
13. Deployment Considerations
-
Dockerize the Bot: Package your bot into a Docker container for consistent deployment.
-
Use a Robust Hosting Solution: Consider hosting your bot on a server that can handle the expected load, like DigitalOcean, AWS, or Heroku.
-
Set Up Monitoring: Use tools to monitor bot performance and uptime.
14. User Feedback and Support
Provide users with a way to report issues or request features, such as a
/feedbackcommand.
15. Regular Updates and Maintenance
-
Keep
yt_dlpand other dependencies updated to support the latest changes on supported platforms. -
Regularly test your bot to ensure all features work as expected.
By implementing these suggestions, your bot will have enhanced capabilities, improved productivity, and the ability to handle multiple users efficiently. Remember to test each new feature thoroughly before deploying it to ensure it works correctly and doesn't introduce new issues.
If you need code examples for specific features or further assistance, feel free to ask!
- The definition of