import os import logging import subprocess import re import time import json from urllib.parse import urlparse from telegram import Update from telegram.ext import ( ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters ) from dotenv import load_dotenv load_dotenv() # Configuration API_TOKEN = os.getenv('TELEGRAM_API_TOKEN') DOWNLOAD_DIR = './downloads' YT_DLP_PATH = './yt-dlp' AUTH_PASSWORD = os.getenv('BOT_AUTH_PASSWORD') AUTHORIZED_USERS_FILE = 'authorized_users.txt' # Setup logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # Load authorized users def load_authorized_users(): if not os.path.exists(AUTHORIZED_USERS_FILE): return set() with open(AUTHORIZED_USERS_FILE, 'r') as f: return set(line.strip() for line in f if line.strip()) AUTHORIZED_USERS = load_authorized_users() # Save authorized users def save_authorized_users(): with open(AUTHORIZED_USERS_FILE, 'w') as f: for user_id in AUTHORIZED_USERS: f.write(f"{user_id}\n") # Helper to check if user is authorized def is_user_authorized(user_id: int) -> bool: return str(user_id) in AUTHORIZED_USERS # Command: /start async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Welcome! Use /help to see available commands.") # Command: /help async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): help_text = """ Available Commands: /start - Start the bot /help - Show this help message /authenticate - Authenticate with the bot using a password Send a TikTok video URL to download the video. """ await update.message.reply_text(help_text) # Command: /authenticate async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.message.from_user.id args = context.args if not args or len(args) != 1: await update.message.reply_text("Usage: /authenticate ") return password = args[0] if password == AUTH_PASSWORD: AUTHORIZED_USERS.add(str(user_id)) save_authorized_users() await update.message.reply_text("Authentication successful! You can now use the bot.") else: await update.message.reply_text("Authentication failed. Incorrect password.") # Handle TikTok URLs async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.message.from_user.id if not is_user_authorized(user_id): await update.message.reply_text("You are not authorized. Use /authenticate to authorize.") return message = update.message if not message or not message.text: return url = message.text.strip() if not is_valid_tiktok_url(url): await message.reply_text("Please send a valid TikTok video URL.") return video_path = None try: video_path = await download_video(url) if not video_path: raise Exception("Download failed") # Open the file properly with a context manager with open(video_path, 'rb') as video_file: try: await message.reply_video(video=video_file) except Exception as send_error: # logger.error(f"Error sending video: {str(send_error)}") # Check file size file_size = os.path.getsize(video_path) / (1024 * 1024) # Size in MB if file_size > 50: await message.reply_text(f"Video is too large ({file_size:.1f}MB). Telegram has a 50MB limit.") else: await message.reply_text(f"Failed to send video: {str(send_error)}") except Exception as e: logger.error(f"Error processing {url}: {str(e)}") await message.reply_text(f"Failed to process video: {str(e)}") finally: if video_path and os.path.exists(video_path): try: os.remove(video_path) except Exception as del_error: logger.error(f"Error removing file {video_path}: {str(del_error)}") # Validate TikTok URL def is_valid_tiktok_url(url: str) -> bool: parsed = urlparse(url) return ( parsed.scheme in ['http', 'https'] and 'tiktok.com' in parsed.netloc and '/video/' in parsed.path ) # Download TikTok video using yt-dlp async def download_video(url: str) -> str: os.makedirs(DOWNLOAD_DIR, exist_ok=True) # First, get metadata to extract the publish date metadata_cmd = [ YT_DLP_PATH, '--no-check-certificate', '--dump-json', url ] metadata_result = subprocess.run(metadata_cmd, capture_output=True, text=True) # Default template without date output_template = os.path.join(DOWNLOAD_DIR, '%(id)s.%(ext)s') # Try to extract date from metadata try: if metadata_result.returncode == 0: metadata = json.loads(metadata_result.stdout) # Extract the upload date if available if 'upload_date' in metadata: # Format is typically YYYYMMDD upload_date = metadata['upload_date'] # You can reformat it if you want (e.g., YYYY-MM-DD) formatted_date = f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:8]}" # Update the output template to include the date output_template = os.path.join(DOWNLOAD_DIR, f"{formatted_date}_%(id)s.%(ext)s") logger.info(f"Using date format: {formatted_date}") except Exception as e: logger.error(f"Error parsing metadata: {str(e)}") # Continue with the default template if there's an error # Download the video with the determined output template cmd = [ YT_DLP_PATH, '--no-check-certificate', '--format', 'best', '--verbose', '-o', output_template, url ] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: logger.error(f"yt-dlp error: {result.stderr}") return None # Look for the file path in both stdout and stderr full_output = result.stdout + result.stderr # Try to find the destination file filename = None for line in full_output.split('\n'): if '[download]' in line and 'Destination:' in line: parts = line.split('Destination:') if len(parts) > 1: filename = parts[1].strip() break # If we couldn't find it with the above method, try alternative approaches if not filename: # Look for the "[download] ... has already been downloaded" message for line in full_output.split('\n'): if '[download]' in line and 'has already been downloaded' in line: match = re.search(r'\[download\] (.*?) has already been downloaded', line) if match: filename = match.group(1) break # If we still couldn't find it, try to find any file in the download directory that was recently created if not filename: try: files = [os.path.join(DOWNLOAD_DIR, f) for f in os.listdir(DOWNLOAD_DIR)] if files: newest_file = max(files, key=os.path.getctime) if time.time() - os.path.getctime(newest_file) < 30: filename = newest_file except Exception as e: logger.error(f"Error finding recent files: {str(e)}") logger.info(f"Found filename: {filename}") if not filename or not os.path.exists(filename): logger.error(f"Full yt-dlp output: {full_output}") raise Exception("Failed to retrieve downloaded file") return filename if __name__ == '__main__': if not API_TOKEN: raise ValueError("TELEGRAM_API_TOKEN environment variable not set") app = ApplicationBuilder().token(API_TOKEN).build() # Add handlers app.add_handler(CommandHandler("start", start)) app.add_handler(CommandHandler("help", help_command)) app.add_handler(CommandHandler("authenticate", authenticate)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) logger.info("Starting bot...") app.run_polling()