From d3b391e52972b3aaef3f862dac958c8db26279f2 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Sun, 9 Mar 2025 04:49:22 +0000 Subject: [PATCH] add support for multilink download and rate limiting --- bot.py | 95 +++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 65 insertions(+), 30 deletions(-) diff --git a/bot.py b/bot.py index 0f3b7e0..1d85ef9 100644 --- a/bot.py +++ b/bot.py @@ -23,6 +23,10 @@ YT_DLP_PATH = './yt-dlp' AUTH_PASSWORD = os.getenv('BOT_AUTH_PASSWORD') AUTHORIZED_USERS_FILE = 'authorized_users.txt' +# Rate limiting configuration +RATE_LIMIT_WINDOW = 60 # Time window in seconds +MAX_REQUESTS_PER_WINDOW = 5 # Maximum requests allowed per user in the time window + # Setup logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', @@ -49,6 +53,28 @@ def save_authorized_users(): def is_user_authorized(user_id: int) -> bool: return str(user_id) in AUTHORIZED_USERS +# Rate limiting tracker +user_request_tracker = {} + +# Check if user is rate-limited +def is_rate_limited(user_id: int) -> bool: + current_time = time.time() + if user_id not in user_request_tracker: + user_request_tracker[user_id] = [] + + # Remove old requests outside the time window + user_request_tracker[user_id] = [ + t for t in user_request_tracker[user_id] if current_time - t <= RATE_LIMIT_WINDOW + ] + + # Check if the user has exceeded the limit + if len(user_request_tracker[user_id]) >= MAX_REQUESTS_PER_WINDOW: + return True + + # Add the current request timestamp + user_request_tracker[user_id].append(current_time) + return False + # Command: /start async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Welcome! Use /help to see available commands.") @@ -60,7 +86,7 @@ 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. +Send one or more TikTok video URLs (separated by new lines) to download the videos. """ await update.message.reply_text(help_text) @@ -88,44 +114,53 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("You are not authorized. Use /authenticate to authorize.") return + # Check rate limiting + if is_rate_limited(user_id): + await update.message.reply_text("You are sending too many requests. Please try again later.") + 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.") + # Split the message into multiple lines and process each URL + urls = message.text.strip().split('\n') + valid_urls = [url.strip() for url in urls if is_valid_tiktok_url(url.strip())] + + if not valid_urls: + await message.reply_text("Please send valid TikTok video URLs.") return - video_path = None - try: - video_path = await download_video(url) - if not video_path: - raise Exception("Download failed") + for url in valid_urls: + 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)}") + # 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: + # 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)}") + 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)}") + finally: + if video_path and os.path.exists(video_path): + try: + print("skipping delete") + # 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: