From 1cd6c34e89858dba7a6f305127c258cb6fc2ac3c Mon Sep 17 00:00:00 2001 From: X4Lo Date: Sun, 9 Mar 2025 05:11:44 +0000 Subject: [PATCH] separated the downloader server from the bot logic + added requests logging --- .gitignore | 3 +- __pycache__/downloader.cpython-39.pyc | Bin 0 -> 2884 bytes bot.py | 124 +++++------------------- downloader.py | 132 ++++++++++++++++++++++++++ 4 files changed, 156 insertions(+), 103 deletions(-) create mode 100644 __pycache__/downloader.cpython-39.pyc create mode 100644 downloader.py diff --git a/.gitignore b/.gitignore index 7324fb9..e369826 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ downloads youtube-dl* yt-dlp* authorized_users.txt -.env \ No newline at end of file +.env +*.log \ No newline at end of file diff --git a/__pycache__/downloader.cpython-39.pyc b/__pycache__/downloader.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c946beb3bcac9872c1ec3ac3c133777056e51b9 GIT binary patch literal 2884 zcma)8&2JmW6`$E%lFKEzq$FBj{>a9S3(+YVBM5?m5Y!rBj0O;F!Y%DogY;O3edpnPi%MbQ7F|G=CA^rRls9txu<`es&CsY}r%_RYMR-+Mdr z-tW!OEtM<;&kr~L(tojp&|jsp_{iCx!yEk*1VIG*sGYXBjg_voHPz~EUA0ErpvF;# zXdtshf2mT+*LYmrlTZfynbMc1dt)L+ntG>Y6l0Bf4a_ChvvxyUF`Txfhi!mk29bV(GOjSnWg zPW%zz^fB{AmQg-tK^Mz!oQ|F@DmI( zm}Fk+Qw@;WSq`w-Q*ElpaiSfWBnQF%j^}3BZcqM((KH7MZ~##z z6<$elX$n#lq#!@d{W=FJP_0aX+T9XaCM%?x=&(z3YN}nD7rV?Sd9^G36=okQ&sSh% zY5sMRe~dsc$gwpvmA(s!1!P)1#Vz!#H7%00qkyq1Ur9y``i5+tdws*N%vQW&W@61T+$KLd!N0*t0Sf57_*=_?r!}X&<2rlZU@sgv#~z`fGmgBV@1%v$P*5fA zvVPQ5J!uWq;cP{m)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 diff --git a/bot.py b/bot.py index 1d85ef9..537aee8 100644 --- a/bot.py +++ b/bot.py @@ -1,10 +1,11 @@ import os import logging -import subprocess -import re import time -import json +import asyncio +from datetime import datetime + from urllib.parse import urlparse +from telegram import BotCommand from telegram import Update from telegram.ext import ( ApplicationBuilder, @@ -14,14 +15,15 @@ from telegram.ext import ( filters ) from dotenv import load_dotenv +from downloader import download_video + 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' +DELETE_AFTER_SEND = False # Rate limiting configuration RATE_LIMIT_WINDOW = 60 # Time window in seconds @@ -75,6 +77,12 @@ def is_rate_limited(user_id: int) -> bool: user_request_tracker[user_id].append(current_time) return False +# Log user requests +def log_user_request(user_id: int, username: str, message: str): + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + with open('requests.log', 'a') as log_file: + log_file.write(f"[{timestamp}] {username} ({user_id}): {message}\n") + # Command: /start async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Welcome! Use /help to see available commands.") @@ -110,10 +118,14 @@ async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE): # Handle TikTok URLs async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.message.from_user.id + username = update.message.from_user.username or "UnknownUser" if not is_user_authorized(user_id): await update.message.reply_text("You are not authorized. Use /authenticate to authorize.") return + # Log the user's message + log_user_request(user_id, username, update.message.text) + # Check rate limiting if is_rate_limited(user_id): await update.message.reply_text("You are sending too many requests. Please try again later.") @@ -134,7 +146,8 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): for url in valid_urls: video_path = None try: - video_path = await download_video(url) + # Run the synchronous download_video function in a separate thread + video_path = await asyncio.to_thread(download_video, url) if not video_path: raise Exception("Download failed") @@ -157,8 +170,8 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): finally: if video_path and os.path.exists(video_path): try: - print("skipping delete") - # os.remove(video_path) + if DELETE_AFTER_SEND: + os.remove(video_path) except Exception as del_error: logger.error(f"Error removing file {video_path}: {str(del_error)}") @@ -171,99 +184,6 @@ def is_valid_tiktok_url(url: str) -> bool: '/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") @@ -275,6 +195,6 @@ if __name__ == '__main__': 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() \ No newline at end of file diff --git a/downloader.py b/downloader.py new file mode 100644 index 0000000..4e1c06c --- /dev/null +++ b/downloader.py @@ -0,0 +1,132 @@ +import os +import subprocess +import json +import re +import logging + +# Setup logging +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO +) +logger = logging.getLogger(__name__) + +DOWNLOAD_DIR = './downloads' +YT_DLP_PATH = './yt-dlp' + +def download_video(url: str) -> str: + """ + Downloads a TikTok video using yt-dlp. + + Args: + url (str): The TikTok video URL. + + Returns: + str: Path to the downloaded video file. + """ + 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__': + import sys + if len(sys.argv) != 2: + print("Usage: python downloader.py ") + sys.exit(1) + + url = sys.argv[1] + try: + video_path = download_video(url) + if video_path: + print(f"Video downloaded successfully: {video_path}") + else: + print("Download failed.") + except Exception as e: + print(f"Error: {str(e)}") \ No newline at end of file