0
# File Handling
1
2
File upload and download operations with progress tracking, including sending media, documents, photos, and handling various file formats in Telethon.
3
4
## Capabilities
5
6
### File Upload
7
8
Upload files to Telegram for later use or immediate sending.
9
10
```python { .api }
11
async def upload_file(
12
self,
13
file,
14
*,
15
part_size_kb: int = None,
16
file_name: str = None,
17
use_cache: bool = True,
18
progress_callback=None
19
) -> Union[types.InputFile, types.InputFileBig]:
20
"""
21
Upload a file to Telegram servers for later use.
22
23
Parameters:
24
- file: File path, bytes, or file-like object to upload
25
- part_size_kb: Upload chunk size in KB (auto-determined if None)
26
- file_name: Name for the file (auto-detected if None)
27
- use_cache: Use cached upload if file already uploaded
28
- progress_callback: Callback for upload progress updates
29
30
Returns:
31
InputFile or InputFileBig object for use in other methods
32
33
Progress callback signature:
34
def callback(current_bytes: int, total_bytes: int):
35
percent = current_bytes / total_bytes * 100
36
print(f"Uploaded {percent:.1f}%")
37
"""
38
```
39
40
### Sending Files
41
42
Send files with messages including various media types and options.
43
44
```python { .api }
45
async def send_file(
46
self,
47
entity,
48
file,
49
*,
50
caption: str = '',
51
force_document: bool = False,
52
clear_draft: bool = False,
53
parse_mode=(),
54
thumb=None,
55
reply_to=None,
56
attributes=None,
57
allow_cache: bool = True,
58
voice_note: bool = False,
59
video_note: bool = False,
60
buttons=None,
61
silent: bool = None,
62
background: bool = None,
63
supports_streaming: bool = False,
64
schedule=None,
65
comment_to=None,
66
ttl: int = None,
67
file_name: str = None,
68
mime_type: str = None,
69
thumb_file_name: str = None,
70
progress_callback=None,
71
nosound_video: bool = False
72
) -> types.Message:
73
"""
74
Send a file as a message to an entity.
75
76
Parameters:
77
- entity: Target chat, channel, or user
78
- file: File path, bytes, URL, or InputFile object
79
- caption: Text caption for the file
80
- force_document: Send as document instead of media
81
- clear_draft: Clear draft after sending
82
- parse_mode: Caption formatting ('md', 'html')
83
- thumb: Custom thumbnail file
84
- reply_to: Message to reply to
85
- attributes: Custom file attributes
86
- allow_cache: Use cached upload if available
87
- voice_note: Send as voice message
88
- video_note: Send as video note (circular video)
89
- buttons: Inline keyboard buttons
90
- silent: Send without notification
91
- background: Send in background (channels)
92
- supports_streaming: Enable streaming for videos
93
- schedule: Schedule for later delivery
94
- comment_to: Reply in channel comments
95
- ttl: Self-destruct timer in seconds
96
- file_name: Override detected file name
97
- mime_type: Override detected MIME type
98
- thumb_file_name: Thumbnail file name
99
- progress_callback: Upload progress callback
100
- nosound_video: Mark video as having no sound
101
102
Returns:
103
Message object containing the sent file
104
105
Raises:
106
- FilePartMissingError: If upload incomplete
107
- MediaInvalidError: If file format unsupported
108
- FileTooLargeError: If file exceeds size limits
109
"""
110
```
111
112
### File Download
113
114
Download files from messages with various options and progress tracking.
115
116
```python { .api }
117
async def download_file(
118
self,
119
input_location,
120
file=None,
121
*,
122
part_size_kb: int = None,
123
file_size: int = None,
124
progress_callback=None,
125
dc_id: int = None,
126
key=None,
127
iv=None
128
) -> bytes:
129
"""
130
Download a file from Telegram servers.
131
132
Parameters:
133
- input_location: InputFileLocation or similar object
134
- file: Output file path or file-like object (None for bytes)
135
- part_size_kb: Download chunk size in KB
136
- file_size: Expected file size for progress tracking
137
- progress_callback: Download progress callback
138
- dc_id: Specific datacenter ID to use
139
- key: Decryption key for encrypted files
140
- iv: Initialization vector for encrypted files
141
142
Returns:
143
bytes: File contents if file=None, otherwise None
144
145
Progress callback signature:
146
def callback(current_bytes: int, total_bytes: int):
147
percent = current_bytes / total_bytes * 100
148
print(f"Downloaded {percent:.1f}%")
149
"""
150
151
async def download_media(
152
self,
153
message,
154
file=None,
155
*,
156
thumb: Union[int, types.TypePhotoSize] = None,
157
progress_callback=None
158
) -> str:
159
"""
160
Download media from a message.
161
162
Parameters:
163
- message: Message object containing media
164
- file: Output file path (auto-generated if None)
165
- thumb: Download specific thumbnail size
166
- progress_callback: Download progress callback
167
168
Returns:
169
str: Path to downloaded file
170
171
Raises:
172
- MediaEmptyError: If message has no media
173
- FileReferenceExpiredError: If file reference expired
174
"""
175
176
async def download_profile_photo(
177
self,
178
entity,
179
file=None,
180
*,
181
download_big: bool = True,
182
thumb: int = None
183
) -> str:
184
"""
185
Download profile photo of a user or chat.
186
187
Parameters:
188
- entity: User, chat, or channel
189
- file: Output file path (auto-generated if None)
190
- download_big: Download high resolution version
191
- thumb: Download specific thumbnail (-1 for big, 0 for small)
192
193
Returns:
194
str: Path to downloaded profile photo
195
"""
196
```
197
198
### Streaming Download
199
200
Stream large files efficiently with iterator-based download.
201
202
```python { .api }
203
def iter_download(
204
self,
205
file,
206
*,
207
offset: int = 0,
208
stride: int = None,
209
limit: int = None,
210
chunk_size: int = None,
211
request_size: int = None,
212
file_size: int = None,
213
dc_id: int = None
214
):
215
"""
216
Iterate over file chunks for streaming download.
217
218
Parameters:
219
- file: InputFileLocation or message with media
220
- offset: Start downloading from this byte offset
221
- stride: Download every nth chunk (for sampling)
222
- limit: Maximum number of chunks to download
223
- chunk_size: Size of each chunk in bytes
224
- request_size: Size of each API request in bytes
225
- file_size: Total file size for optimization
226
- dc_id: Specific datacenter to use
227
228
Yields:
229
bytes: File chunks in order
230
231
Usage:
232
async for chunk in client.iter_download(message.media):
233
# Process chunk (save to file, analyze, etc.)
234
process_chunk(chunk)
235
"""
236
```
237
238
### File Attributes
239
240
Control file metadata and attributes for uploads.
241
242
```python { .api }
243
def get_attributes(
244
file,
245
*,
246
mime_type: str = None,
247
attributes: List = None,
248
force_document: bool = False,
249
voice_note: bool = False,
250
video_note: bool = False,
251
supports_streaming: bool = False,
252
**kwargs
253
) -> List[types.TypeDocumentAttribute]:
254
"""
255
Generate appropriate attributes for a file upload.
256
257
Parameters:
258
- file: File object or path
259
- mime_type: Override MIME type
260
- attributes: Custom attributes list
261
- force_document: Force document attributes
262
- voice_note: Add voice message attributes
263
- video_note: Add video note attributes
264
- supports_streaming: Add streaming support
265
266
Returns:
267
List of DocumentAttribute objects
268
"""
269
```
270
271
## Usage Examples
272
273
### Basic File Operations
274
275
```python
276
import asyncio
277
from telethon import TelegramClient
278
279
async def basic_file_operations():
280
client = TelegramClient('session', api_id, api_hash)
281
await client.start()
282
283
chat = 'username'
284
285
# Send a photo
286
await client.send_file(chat, 'photo.jpg', caption='Check out this photo!')
287
288
# Send a document
289
await client.send_file(
290
chat,
291
'document.pdf',
292
force_document=True,
293
caption='Important document'
294
)
295
296
# Send from URL
297
await client.send_file(
298
chat,
299
'https://example.com/image.jpg',
300
caption='Image from URL'
301
)
302
303
# Send voice note
304
await client.send_file(
305
chat,
306
'audio.mp3',
307
voice_note=True
308
)
309
310
await client.disconnect()
311
312
asyncio.run(basic_file_operations())
313
```
314
315
### File Upload with Progress
316
317
```python
318
async def upload_with_progress():
319
client = TelegramClient('session', api_id, api_hash)
320
await client.start()
321
322
def progress_callback(current, total):
323
percent = current / total * 100
324
print(f"\rUpload progress: {percent:.1f}%", end='', flush=True)
325
326
# Upload large file with progress tracking
327
await client.send_file(
328
'username',
329
'large_video.mp4',
330
caption='Large video file',
331
progress_callback=progress_callback,
332
supports_streaming=True
333
)
334
335
print("\nUpload complete!")
336
await client.disconnect()
337
```
338
339
### Download Files from Messages
340
341
```python
342
import os
343
344
async def download_files():
345
client = TelegramClient('session', api_id, api_hash)
346
await client.start()
347
348
chat = 'username'
349
350
def download_progress(current, total):
351
percent = current / total * 100
352
print(f"\rDownload progress: {percent:.1f}%", end='', flush=True)
353
354
# Download media from recent messages
355
async for message in client.iter_messages(chat, limit=10):
356
if message.media:
357
# Download to specific file
358
file_path = await client.download_media(
359
message,
360
file=f"downloads/{message.id}",
361
progress_callback=download_progress
362
)
363
print(f"\nDownloaded: {file_path}")
364
365
# Get file info
366
file_size = os.path.getsize(file_path)
367
print(f"File size: {file_size} bytes")
368
369
await client.disconnect()
370
```
371
372
### Streaming Large Files
373
374
```python
375
async def stream_large_file():
376
client = TelegramClient('session', api_id, api_hash)
377
await client.start()
378
379
# Get a message with large media
380
async for message in client.iter_messages('username', limit=50):
381
if message.media and hasattr(message.media, 'document'):
382
doc = message.media.document
383
if doc.size > 10 * 1024 * 1024: # > 10MB
384
print(f"Streaming file: {doc.size} bytes")
385
386
# Stream download to file
387
with open('streamed_file.bin', 'wb') as f:
388
async for chunk in client.iter_download(message.media):
389
f.write(chunk)
390
print(f"Downloaded {f.tell()} bytes", end='\r')
391
392
print(f"\nStreaming complete!")
393
break
394
395
await client.disconnect()
396
```
397
398
### Advanced File Handling
399
400
```python
401
from telethon.tl.types import DocumentAttributeFilename, DocumentAttributeVideo
402
import mimetypes
403
404
async def advanced_file_handling():
405
client = TelegramClient('session', api_id, api_hash)
406
await client.start()
407
408
# Send file with custom attributes
409
custom_attributes = [
410
DocumentAttributeFilename(file_name='custom_name.mp4'),
411
DocumentAttributeVideo(
412
duration=120, # 2 minutes
413
w=1920, # 1920px width
414
h=1080, # 1080px height
415
supports_streaming=True
416
)
417
]
418
419
await client.send_file(
420
'username',
421
'video.mp4',
422
attributes=custom_attributes,
423
thumb='thumbnail.jpg', # Custom thumbnail
424
caption='Video with custom attributes'
425
)
426
427
# Pre-upload file for multiple uses
428
uploaded_file = await client.upload_file('document.pdf')
429
430
# Use pre-uploaded file multiple times
431
await client.send_file('user1', uploaded_file, caption='For user 1')
432
await client.send_file('user2', uploaded_file, caption='For user 2')
433
434
# Download profile photos
435
async for dialog in client.iter_dialogs(limit=10):
436
if dialog.entity.photo:
437
photo_path = await client.download_profile_photo(
438
dialog.entity,
439
file=f'profiles/{dialog.id}_profile.jpg'
440
)
441
print(f"Downloaded profile photo: {photo_path}")
442
443
await client.disconnect()
444
```
445
446
### File Type Detection
447
448
```python
449
from telethon import utils
450
451
async def file_type_detection():
452
client = TelegramClient('session', api_id, api_hash)
453
await client.start()
454
455
# Check recent media messages
456
async for message in client.iter_messages('username', limit=20):
457
if message.media:
458
print(f"Message {message.id}:")
459
460
# Check media type
461
if utils.is_image(message.media):
462
print(" - Type: Image")
463
elif utils.is_video(message.media):
464
print(" - Type: Video")
465
elif utils.is_audio(message.media):
466
print(" - Type: Audio")
467
elif utils.is_gif(message.media):
468
print(" - Type: GIF")
469
else:
470
print(" - Type: Document")
471
472
# Get file extension
473
extension = utils.get_extension(message.media)
474
print(f" - Extension: {extension}")
475
476
await client.disconnect()
477
```
478
479
## Types
480
481
```python { .api }
482
from typing import Union, List, Optional, Callable, BinaryIO
483
from telethon.tl import types
484
import io
485
486
FileLike = Union[str, bytes, BinaryIO, io.IOBase]
487
ProgressCallback = Callable[[int, int], None]
488
AttributeList = List[types.TypeDocumentAttribute]
489
490
class InputSizedFile:
491
"""File input with size information"""
492
file: types.InputFile
493
size: int
494
name: str
495
496
class UploadProgress:
497
"""Upload progress information"""
498
current: int
499
total: int
500
percentage: float
501
```