Add duplicate detection and failed-download tracking
Skip already-downloaded TikTok IDs across runs Log failed URLs to ./failed.txt for later retry
This commit is contained in:
1 parent
d7da49c922
commit
7c71ed6df8
6 files changed
+333
-102
No files matched your search
@@ -1,28 +1,34 @@
|
||||
import os
|
||||
import logging
|
||||
import time
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from urllib.parse import urlparse
|
||||
from telegram import BotCommand
|
||||
from telegram import Update
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from telegram import BotCommand, Update
|
||||
from telegram.ext import (
|
||||
ApplicationBuilder,
|
||||
CommandHandler,
|
||||
MessageHandler,
|
||||
ContextTypes,
|
||||
filters
|
||||
MessageHandler,
|
||||
filters,
|
||||
)
|
||||
|
||||
from downloader import (
|
||||
download_video,
|
||||
extract_tiktok_id,
|
||||
load_downloaded_ids,
|
||||
log_failed_url,
|
||||
save_downloaded_id,
|
||||
)
|
||||
from dotenv import load_dotenv
|
||||
from downloader import download_video
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Configuration
|
||||
API_TOKEN = os.getenv('TELEGRAM_API_TOKEN')
|
||||
AUTH_PASSWORD = os.getenv('BOT_AUTH_PASSWORD')
|
||||
AUTHORIZED_USERS_FILE = 'authorized_users.txt'
|
||||
API_TOKEN = os.getenv("TELEGRAM_API_TOKEN")
|
||||
AUTH_PASSWORD = os.getenv("BOT_AUTH_PASSWORD")
|
||||
AUTHORIZED_USERS_FILE = "authorized_users.txt"
|
||||
DELETE_AFTER_SEND = False
|
||||
|
||||
# Rate limiting configuration
|
||||
@@ -31,33 +37,38 @@ MAX_REQUESTS_PER_WINDOW = 5 # Maximum requests allowed per user in the time win
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO
|
||||
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:
|
||||
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:
|
||||
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
|
||||
|
||||
|
||||
# Rate limiting tracker
|
||||
user_request_tracker = {}
|
||||
|
||||
|
||||
# Check if user is rate-limited
|
||||
def is_rate_limited(user_id: int) -> bool:
|
||||
current_time = time.time()
|
||||
@@ -66,7 +77,9 @@ def is_rate_limited(user_id: int) -> bool:
|
||||
|
||||
# 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
|
||||
t
|
||||
for t in user_request_tracker[user_id]
|
||||
if current_time - t <= RATE_LIMIT_WINDOW
|
||||
]
|
||||
|
||||
# Check if the user has exceeded the limit
|
||||
@@ -77,16 +90,19 @@ 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:
|
||||
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.")
|
||||
|
||||
|
||||
# Command: /help
|
||||
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
help_text = """
|
||||
@@ -98,6 +114,7 @@ Send one or more TikTok video URLs (separated by new lines) to download the vide
|
||||
"""
|
||||
await update.message.reply_text(help_text)
|
||||
|
||||
|
||||
# Command: /authenticate <password>
|
||||
async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
user_id = update.message.from_user.id
|
||||
@@ -111,16 +128,21 @@ async def authenticate(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
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.")
|
||||
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
|
||||
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 <password> to authorize.")
|
||||
await update.message.reply_text(
|
||||
"You are not authorized. Use /authenticate <password> to authorize."
|
||||
)
|
||||
return
|
||||
|
||||
# Log the user's message
|
||||
@@ -128,7 +150,9 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
|
||||
# Check rate limiting
|
||||
if is_rate_limited(user_id):
|
||||
await update.message.reply_text("You are sending too many requests. Please try again later.")
|
||||
await update.message.reply_text(
|
||||
"You are sending too many requests. Please try again later."
|
||||
)
|
||||
return
|
||||
|
||||
message = update.message
|
||||
@@ -136,14 +160,22 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
return
|
||||
|
||||
# Split the message into multiple lines and process each URL
|
||||
urls = message.text.strip().split('\n')
|
||||
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
|
||||
|
||||
downloaded_ids = load_downloaded_ids()
|
||||
|
||||
for url in valid_urls:
|
||||
# Skip if already downloaded
|
||||
video_id = extract_tiktok_id(url)
|
||||
if video_id and video_id in downloaded_ids:
|
||||
logger.info(f"Skipping (already downloaded): {url}")
|
||||
continue
|
||||
|
||||
video_path = None
|
||||
try:
|
||||
# Run the synchronous download_video function in a separate thread
|
||||
@@ -151,40 +183,53 @@ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
if not video_path:
|
||||
raise Exception("Download failed")
|
||||
|
||||
# Mark as downloaded
|
||||
if video_id:
|
||||
save_downloaded_id(video_id)
|
||||
|
||||
# Open the file properly with a context manager
|
||||
with open(video_path, 'rb') as video_file:
|
||||
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
|
||||
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.")
|
||||
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)}")
|
||||
await message.reply_text(
|
||||
f"Failed to send video: {str(send_error)}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing {url}: {str(e)}")
|
||||
log_failed_url(url)
|
||||
await message.reply_text(f"Failed to process video: {str(e)}")
|
||||
|
||||
finally:
|
||||
if video_path and os.path.exists(video_path):
|
||||
try:
|
||||
if DELETE_AFTER_SEND:
|
||||
os.remove(video_path)
|
||||
if DELETE_AFTER_SEND == True:
|
||||
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
|
||||
parsed.scheme in ["http", "https"]
|
||||
and "tiktok.com" in parsed.netloc
|
||||
and ("/video/" in parsed.path or "/photo/" in parsed.path)
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not API_TOKEN:
|
||||
raise ValueError("TELEGRAM_API_TOKEN environment variable not set")
|
||||
|
||||
@@ -195,6 +240,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()
|
||||
app.run_polling()
|
||||
Reference in new issue
Block a user