Full-featured Telegram client library for Python 3
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
File upload and download operations with progress tracking, including sending media, documents, photos, and handling various file formats in Telethon.
Upload files to Telegram for later use or immediate sending.
async def upload_file(
self,
file,
*,
part_size_kb: int = None,
file_name: str = None,
use_cache: bool = True,
progress_callback=None
) -> Union[types.InputFile, types.InputFileBig]:
"""
Upload a file to Telegram servers for later use.
Parameters:
- file: File path, bytes, or file-like object to upload
- part_size_kb: Upload chunk size in KB (auto-determined if None)
- file_name: Name for the file (auto-detected if None)
- use_cache: Use cached upload if file already uploaded
- progress_callback: Callback for upload progress updates
Returns:
InputFile or InputFileBig object for use in other methods
Progress callback signature:
def callback(current_bytes: int, total_bytes: int):
percent = current_bytes / total_bytes * 100
print(f"Uploaded {percent:.1f}%")
"""Send files with messages including various media types and options.
async def send_file(
self,
entity,
file,
*,
caption: str = '',
force_document: bool = False,
clear_draft: bool = False,
parse_mode=(),
thumb=None,
reply_to=None,
attributes=None,
allow_cache: bool = True,
voice_note: bool = False,
video_note: bool = False,
buttons=None,
silent: bool = None,
background: bool = None,
supports_streaming: bool = False,
schedule=None,
comment_to=None,
ttl: int = None,
file_name: str = None,
mime_type: str = None,
thumb_file_name: str = None,
progress_callback=None,
nosound_video: bool = False
) -> types.Message:
"""
Send a file as a message to an entity.
Parameters:
- entity: Target chat, channel, or user
- file: File path, bytes, URL, or InputFile object
- caption: Text caption for the file
- force_document: Send as document instead of media
- clear_draft: Clear draft after sending
- parse_mode: Caption formatting ('md', 'html')
- thumb: Custom thumbnail file
- reply_to: Message to reply to
- attributes: Custom file attributes
- allow_cache: Use cached upload if available
- voice_note: Send as voice message
- video_note: Send as video note (circular video)
- buttons: Inline keyboard buttons
- silent: Send without notification
- background: Send in background (channels)
- supports_streaming: Enable streaming for videos
- schedule: Schedule for later delivery
- comment_to: Reply in channel comments
- ttl: Self-destruct timer in seconds
- file_name: Override detected file name
- mime_type: Override detected MIME type
- thumb_file_name: Thumbnail file name
- progress_callback: Upload progress callback
- nosound_video: Mark video as having no sound
Returns:
Message object containing the sent file
Raises:
- FilePartMissingError: If upload incomplete
- MediaInvalidError: If file format unsupported
- FileTooLargeError: If file exceeds size limits
"""Download files from messages with various options and progress tracking.
async def download_file(
self,
input_location,
file=None,
*,
part_size_kb: int = None,
file_size: int = None,
progress_callback=None,
dc_id: int = None,
key=None,
iv=None
) -> bytes:
"""
Download a file from Telegram servers.
Parameters:
- input_location: InputFileLocation or similar object
- file: Output file path or file-like object (None for bytes)
- part_size_kb: Download chunk size in KB
- file_size: Expected file size for progress tracking
- progress_callback: Download progress callback
- dc_id: Specific datacenter ID to use
- key: Decryption key for encrypted files
- iv: Initialization vector for encrypted files
Returns:
bytes: File contents if file=None, otherwise None
Progress callback signature:
def callback(current_bytes: int, total_bytes: int):
percent = current_bytes / total_bytes * 100
print(f"Downloaded {percent:.1f}%")
"""
async def download_media(
self,
message,
file=None,
*,
thumb: Union[int, types.TypePhotoSize] = None,
progress_callback=None
) -> str:
"""
Download media from a message.
Parameters:
- message: Message object containing media
- file: Output file path (auto-generated if None)
- thumb: Download specific thumbnail size
- progress_callback: Download progress callback
Returns:
str: Path to downloaded file
Raises:
- MediaEmptyError: If message has no media
- FileReferenceExpiredError: If file reference expired
"""
async def download_profile_photo(
self,
entity,
file=None,
*,
download_big: bool = True,
thumb: int = None
) -> str:
"""
Download profile photo of a user or chat.
Parameters:
- entity: User, chat, or channel
- file: Output file path (auto-generated if None)
- download_big: Download high resolution version
- thumb: Download specific thumbnail (-1 for big, 0 for small)
Returns:
str: Path to downloaded profile photo
"""Stream large files efficiently with iterator-based download.
def iter_download(
self,
file,
*,
offset: int = 0,
stride: int = None,
limit: int = None,
chunk_size: int = None,
request_size: int = None,
file_size: int = None,
dc_id: int = None
):
"""
Iterate over file chunks for streaming download.
Parameters:
- file: InputFileLocation or message with media
- offset: Start downloading from this byte offset
- stride: Download every nth chunk (for sampling)
- limit: Maximum number of chunks to download
- chunk_size: Size of each chunk in bytes
- request_size: Size of each API request in bytes
- file_size: Total file size for optimization
- dc_id: Specific datacenter to use
Yields:
bytes: File chunks in order
Usage:
async for chunk in client.iter_download(message.media):
# Process chunk (save to file, analyze, etc.)
process_chunk(chunk)
"""Control file metadata and attributes for uploads.
def get_attributes(
file,
*,
mime_type: str = None,
attributes: List = None,
force_document: bool = False,
voice_note: bool = False,
video_note: bool = False,
supports_streaming: bool = False,
**kwargs
) -> List[types.TypeDocumentAttribute]:
"""
Generate appropriate attributes for a file upload.
Parameters:
- file: File object or path
- mime_type: Override MIME type
- attributes: Custom attributes list
- force_document: Force document attributes
- voice_note: Add voice message attributes
- video_note: Add video note attributes
- supports_streaming: Add streaming support
Returns:
List of DocumentAttribute objects
"""import asyncio
from telethon import TelegramClient
async def basic_file_operations():
client = TelegramClient('session', api_id, api_hash)
await client.start()
chat = 'username'
# Send a photo
await client.send_file(chat, 'photo.jpg', caption='Check out this photo!')
# Send a document
await client.send_file(
chat,
'document.pdf',
force_document=True,
caption='Important document'
)
# Send from URL
await client.send_file(
chat,
'https://example.com/image.jpg',
caption='Image from URL'
)
# Send voice note
await client.send_file(
chat,
'audio.mp3',
voice_note=True
)
await client.disconnect()
asyncio.run(basic_file_operations())async def upload_with_progress():
client = TelegramClient('session', api_id, api_hash)
await client.start()
def progress_callback(current, total):
percent = current / total * 100
print(f"\rUpload progress: {percent:.1f}%", end='', flush=True)
# Upload large file with progress tracking
await client.send_file(
'username',
'large_video.mp4',
caption='Large video file',
progress_callback=progress_callback,
supports_streaming=True
)
print("\nUpload complete!")
await client.disconnect()import os
async def download_files():
client = TelegramClient('session', api_id, api_hash)
await client.start()
chat = 'username'
def download_progress(current, total):
percent = current / total * 100
print(f"\rDownload progress: {percent:.1f}%", end='', flush=True)
# Download media from recent messages
async for message in client.iter_messages(chat, limit=10):
if message.media:
# Download to specific file
file_path = await client.download_media(
message,
file=f"downloads/{message.id}",
progress_callback=download_progress
)
print(f"\nDownloaded: {file_path}")
# Get file info
file_size = os.path.getsize(file_path)
print(f"File size: {file_size} bytes")
await client.disconnect()async def stream_large_file():
client = TelegramClient('session', api_id, api_hash)
await client.start()
# Get a message with large media
async for message in client.iter_messages('username', limit=50):
if message.media and hasattr(message.media, 'document'):
doc = message.media.document
if doc.size > 10 * 1024 * 1024: # > 10MB
print(f"Streaming file: {doc.size} bytes")
# Stream download to file
with open('streamed_file.bin', 'wb') as f:
async for chunk in client.iter_download(message.media):
f.write(chunk)
print(f"Downloaded {f.tell()} bytes", end='\r')
print(f"\nStreaming complete!")
break
await client.disconnect()from telethon.tl.types import DocumentAttributeFilename, DocumentAttributeVideo
import mimetypes
async def advanced_file_handling():
client = TelegramClient('session', api_id, api_hash)
await client.start()
# Send file with custom attributes
custom_attributes = [
DocumentAttributeFilename(file_name='custom_name.mp4'),
DocumentAttributeVideo(
duration=120, # 2 minutes
w=1920, # 1920px width
h=1080, # 1080px height
supports_streaming=True
)
]
await client.send_file(
'username',
'video.mp4',
attributes=custom_attributes,
thumb='thumbnail.jpg', # Custom thumbnail
caption='Video with custom attributes'
)
# Pre-upload file for multiple uses
uploaded_file = await client.upload_file('document.pdf')
# Use pre-uploaded file multiple times
await client.send_file('user1', uploaded_file, caption='For user 1')
await client.send_file('user2', uploaded_file, caption='For user 2')
# Download profile photos
async for dialog in client.iter_dialogs(limit=10):
if dialog.entity.photo:
photo_path = await client.download_profile_photo(
dialog.entity,
file=f'profiles/{dialog.id}_profile.jpg'
)
print(f"Downloaded profile photo: {photo_path}")
await client.disconnect()from telethon import utils
async def file_type_detection():
client = TelegramClient('session', api_id, api_hash)
await client.start()
# Check recent media messages
async for message in client.iter_messages('username', limit=20):
if message.media:
print(f"Message {message.id}:")
# Check media type
if utils.is_image(message.media):
print(" - Type: Image")
elif utils.is_video(message.media):
print(" - Type: Video")
elif utils.is_audio(message.media):
print(" - Type: Audio")
elif utils.is_gif(message.media):
print(" - Type: GIF")
else:
print(" - Type: Document")
# Get file extension
extension = utils.get_extension(message.media)
print(f" - Extension: {extension}")
await client.disconnect()from typing import Union, List, Optional, Callable, BinaryIO
from telethon.tl import types
import io
FileLike = Union[str, bytes, BinaryIO, io.IOBase]
ProgressCallback = Callable[[int, int], None]
AttributeList = List[types.TypeDocumentAttribute]
class InputSizedFile:
"""File input with size information"""
file: types.InputFile
size: int
name: str
class UploadProgress:
"""Upload progress information"""
current: int
total: int
percentage: floatInstall with Tessl CLI
npx tessl i tessl/pypi-telethon