Make a telegram boat where I can download file from URL given to the boat and send a file to user
Assistant
User
Use aiohttp instead of request lib
Assistant
User
Handle documents and stream able video for telegram
Assistant
User
Use API ID and API has
Assistant
Sure! You want a Telegram bot that accepts a URL from a user, downloads the file at that URL, and then sends the downloaded file back to the user. Below is a simple example written in Python using the python-telegram-bot library and requests to download the file.
import os
import requests
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN_HERE"
DOWNLOAD_PATH = "downloads"
# Ensure download directory exists
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Send me a file URL and I will download it and send the file back to you."
)
async def handle_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
url = update.message.text.strip()
# Basic check if it's an URL (can be improved)
if not (url.startswith("http://") or url.startswith("https://")):
await update.message.reply_text("Please send a valid URL starting with http:// or https://")
return
await update.message.reply_text(f"Downloading from: {url}")
try:
response = requests.get(url, stream=True, timeout=15)
response.raise_for_status()
# Try to get filename from URL or Content-Disposition header
local_filename = url.split("/")[-1]
if not local_filename:
local_filename = "downloaded_file"
# Full path of the file to save
file_path = os.path.join(DOWNLOAD_PATH, local_filename)
with open(file_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
# Send file to user
with open(file_path, "rb") as f:
await update.message.reply_document(document=f, filename=local_filename)
# Clean up downloaded file
os.remove(file_path)
except requests.exceptions.RequestException as e:
await update.message.reply_text(f"Failed to download the file. Error: {e}")
async def main():
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_url))
print("Bot started...")
await app.run_polling()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
How it works:
User sends /start to get a greeting message.
User sends a URL to a downloadable file.
Bot downloads the file and sends it back as a Telegram document.
After sending, the file is deleted from the server.
Notes:
This example is very basic and does not handle large files or unusual headers.
You might want to add more validations, file size limits, timeout handling, and handle errors gracefully.
Make sure your hosting environment has enough space and bandwidth for file downloads/uploads.
By default, Telegram limits file uploads to 50 MB for bots (as of writing). Bigger files won't upload.
If you want me to help you deploy this bot or add features, feel free to ask!
Certainly! Here is the updated version of the Telegram bot that downloads a file from a given URL using aiohttp (an async HTTP client library) instead of requests. This fits nicely into the async architecture of python-telegram-bot v20+.
Prerequisites
Make sure you have these installed:
bash
pip install python-telegram-bot aiohttp
Async Telegram bot with aiohttp
python
import os
import aiohttp
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN_HERE"
DOWNLOAD_PATH = "downloads"
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Send me a file URL and I will download it asynchronously and send the file back to you."
)
async def handle_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
url = update.message.text.strip()
if not (url.startswith("http://") or url.startswith("https://")):
await update.message.reply_text("Please send a valid URL starting with http:// or https://")
return
await update.message.reply_text(f"Downloading from: {url}")
local_filename = url.split("/")[-1] or "downloaded_file"
file_path = os.path.join(DOWNLOAD_PATH, local_filename)
try:
# Download the file asynchronously with aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=30) as resp:
resp.raise_for_status()
# Write to file in chunks
with open(file_path, "wb") as f:
async for chunk in resp.content.iter_chunked(8192):
f.write(chunk)
# Send file back to user
with open(file_path, "rb") as f:
await update.message.reply_document(document=f, filename=local_filename)
os.remove(file_path)
except aiohttp.ClientError as e:
await update.message.reply_text(f"Failed to download the file. Error: {e}")
except Exception as e:
await update.message.reply_text(f"Unexpected error: {e}")
async def main():
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_url))
print("Bot started...")
await app.run_polling()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
Explanation
Uses aiohttp.ClientSession and async context managers to download the file in chunks.
Files are saved to a "downloads" folder asynchronously.
Upon successful download, the bot sends the file as a Telegram document.
The file is then deleted from the disk.
Errors from HTTP requests or other unexpected exceptions are caught and messaged to the user.
If you want additional features like:
Handling filenames from Content-Disposition headers,
Logging,
File size limits,
Or concurrency controls,
just tell me!
Got it! You want a Telegram bot that:
Accepts a URL from a user.
Downloads the file asynchronously.
Sends it back either as a document or, if it’s a video, sends it as a streamable video (i.e., using send_video so Telegram players show it as video rather than just file).
What do we do here?
We'll detect whether the downloaded file is a video (by MIME type or extension).
If video, send the file with reply_video so Telegram shows the embedded video player.
Otherwise, send it as a regular document.
For MIME type detection, we'll use the python-magic library (wrapper for libmagic) or fallback to extension-based detection if you don't want to install it.
If you prefer extension based detection only, I also provide a fallback.
Updated Bot Code:
python
import os
import aiohttp
import magic # for mime detection
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN_HERE"
DOWNLOAD_PATH = "downloads"
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
VIDEO_MIME_PREFIX = "video/"
VIDEO_EXTENSIONS = {
".mp4", ".mkv", ".webm", ".avi", ".mov", ".flv", ".wmv", ".ts"
}
def is_video_file(filepath: str) -> bool:
try:
mime = magic.from_file(filepath, mime=True)
if mime and mime.startswith(VIDEO_MIME_PREFIX):
return True
except Exception:
pass
# fallback to extension check
ext = os.path.splitext(filepath)[1].lower()
return ext in VIDEO_EXTENSIONS
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Send me a file URL, and I'll download and send it back.\n"
"- Videos will be sent as videos (streamable).\n"
"- Other files will be sent as documents."
)
async def handle_url(update: Update, context: ContextTypes.DEFAULT_TYPE):
url = update.message.text.strip()
if not (url.startswith("http://") or url.startswith("https://")):
await update.message.reply_text("Please send a valid URL starting with http:// or https://")
return
await update.message.reply_text(f"Downloading from: {url}")
local_filename = url.split("/")[-1] or "downloaded_file"
file_path = os.path.join(DOWNLOAD_PATH, local_filename)
try:
# Download asynchronously
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=30) as resp:
resp.raise_for_status()
with open(file_path, "wb") as f:
async for chunk in resp.content.iter_chunked(8192):
f.write(chunk)
# Detect file type and send as video or document
if is_video_file(file_path):
with open(file_path, "rb") as f:
await update.message.reply_video(video=f, filename=local_filename)
else:
with open(file_path, "rb") as f:
await update.message.reply_document(document=f, filename=local_filename)
os.remove(file_path)
except aiohttp.ClientError as e:
await update.message.reply_text(f"Failed to download the file. Error: {e}")
except Exception as e:
await update.message.reply_text(f"Unexpected error: {e}")
async def main():
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_url))
print("Bot started...")
await app.run_polling()
if __name__ == "__main__":
import asyncio
asyncio.run(main())
What changed?
Added magic file type detection to identify videos by MIME type.
If video, call reply_video (streamable).
Else, call reply_document for other files.
Has fallback based on file extensions.
Error handling remains.
Notes
Streaming large files may take time depending on network speed.
Telegram file size limit for bots is typically 50 MB. Larger videos/documents will fail.
You can add file size limit checks if needed.
If you want me to add file size limits or support for thumbnail previews or support resumable downloads, just ask!
It looks like you're asking to use API ID and API Hash. These credentials are part of Telegram's MTProto API and generally required when using user clients (e.g., via Telethon or pyrogram), not regular bot tokens.
Clarification:
The previous examples use bot tokens that you get from BotFather, and are suited for Telegram Bots.
If you want to create a client bot or userbot using the Telegram Client API (MTProto), you need:
A bot that runs as a user client (userbot) using API ID/Hash?
Or do you want to authenticate a bot with these?(Bot tokens don't require API ID/Hash.)
Assuming you want an equivalent userbot that downloads a file from URL and sends a file to a user, here is how you do it with Pyrogram (one of the most popular MTProto client libraries in Python):
Example: using Pyrogram with API ID/API Hash
Install pyrogram + dependencies:
bash
pip install pyrogram tgcrypto aiohttp
pyrogram async userbot that downloads from URL and sends file
python
import os
import aiohttp
from pyrogram import Client, filters
from pyrogram.types import Message
api_id = YOUR_API_ID # int, from https://my.telegram.org
api_hash = "YOUR_API_HASH" # str, from https://my.telegram.org
session_name = "my_userbot" # Session file name
DOWNLOAD_PATH = "downloads"
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
# Helper to download file asynchronously using aiohttp
async def download_file(url: str, local_path: str):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
with open(local_path, "wb") as f:
async for chunk in response.content.iter_chunked(8192):
f.write(chunk)
app = Client(session_name, api_id=api_id, api_hash=api_hash)
@app.on_message(filters.command("start") & filters.private)
async def start(client: Client, message: Message):
await message.reply_text(
"Send me a file URL. I will download it and send it back to you."
)
@app.on_message(filters.text & filters.private)
async def handle_url(client: Client, message: Message):
url = message.text.strip()
if not (url.startswith("http://") or url.startswith("https://")):
await message.reply_text("Please send a valid URL starting with http:// or https://")
return
await message.reply_text(f"Downloading from: {url}")
filename = url.split("/")[-1] or "downloaded_file"
file_path = os.path.join(DOWNLOAD_PATH, filename)
try:
await download_file(url, file_path)
# Optional: detect video by extension and send video accordingly
video_exts = {".mp4", ".mkv", ".webm", ".avi", ".mov"}
ext = os.path.splitext(file_path)[1].lower()
if ext in video_exts:
await client.send_video(chat_id=message.chat.id, video=file_path, filename=filename)
else:
await client.send_document(chat_id=message.chat.id, document=file_path, filename=filename)
os.remove(file_path)
except Exception as e:
await message.reply_text(f"Failed to download or send file:\n{e}")
app.run()
Explanation:
You log in as a user using the session_name. On first run, Pyrogram will ask for your phone number + confirmation code.
The bot listens in private chats for text messages that are URLs.
It downloads the file asynchronously with aiohttp and sends back either a video or document.