Files
TikDown/bot.py
T

200 lines
6.7 KiB
Python

import os
import logging
import time
import asyncio
from datetime import datetime
from urllib.parse import urlparse
from telegram import BotCommand
from telegram import Update
from telegram.ext import (
ApplicationBuilder,
CommandHandler,
MessageHandler,
ContextTypes,
filters
)
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'
DELETE_AFTER_SEND = False
# 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',
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
# 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
# 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.")
# 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 <password> - Authenticate with the bot using a password
Send one or more TikTok video URLs (separated by new lines) to download the videos.
"""
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
args = context.args
if not args or len(args) != 1:
await update.message.reply_text("Usage: /authenticate <password>")
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
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.")
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.")
return
message = update.message
if not message or not message.text:
return
# 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
for url in valid_urls:
video_path = None
try:
# 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")
# 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)}")
finally:
if video_path and os.path.exists(video_path):
try:
if DELETE_AFTER_SEND:
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
)
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()