I have a Telegram bot that processes video files sent by users. The bot works perfectly when handling one or two files, but crashes when multiple large files are sent simultaneously.
Current setup:
I register the handler like this:
app.add_handler(MessageHandler(filters.VIDEO, process_video_handler, filters.User(username="@myuser")))
My handler function:
async def process_video_handler(update, context):
try:
video_name = update.message.video.file_name
video_name = sanitize_name(video_name)
status_msg = f"<b>{video_name}</b> received successfully"
await update.message.reply_text(status_msg, parse_mode=ParseMode.HTML)
video_file = await context.bot.get_file(update.message.video)
if not video_name:
parsed_url = urlparse(video_file.file_path)
video_name = os.path.basename(parsed_url.path)
await update.message.reply_text(f"<b>{video_name}</b> ready for download", parse_mode=ParseMode.HTML)
await video_file.download_to_drive(video_name)
await update.message.reply_text(f"<b>{video_name}</b> downloaded successfully", parse_mode=ParseMode.HTML)
file_exists = await check_remote_file(video_name, update)
status = "already exists" if file_exists else "needs upload"
await update.message.reply_text(f"<b>{video_name}</b> {status}", parse_mode=ParseMode.HTML)
if not file_exists:
upload_success = await upload_to_server(video_name, update)
result = "uploaded successfully" if upload_success else "upload failed"
await update.message.reply_text(f"<b>{video_name}</b> {result}", parse_mode=ParseMode.HTML)
except Exception as error:
error_msg = f"Processing failed: {str(error)}"
await update.message.reply_text(error_msg, parse_mode=ParseMode.HTML)
The problem: When users send multiple large videos at once, the bot goes offline and downloads fail. I tried using multiprocessing but couldn’t get it working properly.
What’s the best way to handle multiple concurrent downloads without crashing the bot? Should I use queues, limit concurrent downloads, or is there a better approach?