0
# Utilities & Helpers
1
2
Utility functions for entity resolution, input conversion, media type detection, and common Telegram operations in Telethon.
3
4
## Capabilities
5
6
### Entity Utilities
7
8
Convert between different entity types and resolve entities.
9
10
```python { .api }
11
def get_display_name(entity) -> str:
12
"""
13
Get human-readable display name for an entity.
14
15
Parameters:
16
- entity: User, Chat, Channel, or similar object
17
18
Returns:
19
str: Display name (first_name last_name for users, title for chats)
20
21
Examples:
22
- User: "John Doe"
23
- Chat: "My Group Chat"
24
- Channel: "News Channel"
25
"""
26
27
def get_input_peer(
28
entity,
29
allow_self: bool = True,
30
check_hash: bool = True
31
) -> types.TypeInputPeer:
32
"""
33
Convert entity to InputPeer for API calls.
34
35
Parameters:
36
- entity: User, Chat, Channel, ID, username, or phone
37
- allow_self: Allow InputPeerSelf for current user
38
- check_hash: Verify access hash validity
39
40
Returns:
41
InputPeerUser, InputPeerChat, InputPeerChannel, or InputPeerSelf
42
43
Raises:
44
- ValueError: If entity cannot be resolved
45
- TypeNotFoundError: If entity type unknown
46
"""
47
48
def get_input_channel(entity) -> types.InputChannel:
49
"""
50
Convert entity to InputChannel.
51
52
Parameters:
53
- entity: Channel, supergroup, or their ID/username
54
55
Returns:
56
InputChannel object
57
58
Raises:
59
- ValueError: If not a channel/supergroup
60
"""
61
62
def get_input_user(entity) -> types.InputUser:
63
"""
64
Convert entity to InputUser.
65
66
Parameters:
67
- entity: User object, ID, username, or phone number
68
69
Returns:
70
InputUser object
71
72
Raises:
73
- ValueError: If not a user
74
"""
75
76
def get_input_dialog(dialog) -> types.InputDialogPeer:
77
"""
78
Convert dialog to InputDialogPeer.
79
80
Parameters:
81
- dialog: Dialog object or entity
82
83
Returns:
84
InputDialogPeer object for dialog operations
85
"""
86
87
def get_peer_id(peer) -> int:
88
"""
89
Extract numeric ID from any peer type.
90
91
Parameters:
92
- peer: Any peer object, InputPeer, or entity
93
94
Returns:
95
int: Numeric peer ID
96
97
Note:
98
Channel/supergroup IDs are returned as negative values
99
"""
100
101
def get_input_entity(entity) -> types.TypeInputPeer:
102
"""
103
Alias for get_input_peer with default parameters.
104
105
Parameters:
106
- entity: Entity to convert
107
108
Returns:
109
InputPeer object
110
"""
111
```
112
113
### Media Utilities
114
115
Detect and handle different media types and file formats.
116
117
```python { .api }
118
def get_extension(media) -> str:
119
"""
120
Get file extension for media object.
121
122
Parameters:
123
- media: Media object (Document, Photo, etc.)
124
125
Returns:
126
str: File extension with dot (e.g., '.jpg', '.mp4', '.pdf')
127
"""
128
129
def is_image(file) -> bool:
130
"""
131
Check if file/media is an image.
132
133
Parameters:
134
- file: File path, media object, or message with media
135
136
Returns:
137
bool: True if image format
138
139
Supported formats: JPEG, PNG, GIF, WebP, BMP, TIFF, etc.
140
"""
141
142
def is_gif(file) -> bool:
143
"""
144
Check if file/media is a GIF animation.
145
146
Parameters:
147
- file: File path, media object, or message with media
148
149
Returns:
150
bool: True if GIF format
151
"""
152
153
def is_video(file) -> bool:
154
"""
155
Check if file/media is a video.
156
157
Parameters:
158
- file: File path, media object, or message with media
159
160
Returns:
161
bool: True if video format
162
163
Supported formats: MP4, AVI, MOV, MKV, WebM, etc.
164
"""
165
166
def is_audio(file) -> bool:
167
"""
168
Check if file/media is audio.
169
170
Parameters:
171
- file: File path, media object, or message with media
172
173
Returns:
174
bool: True if audio format
175
176
Supported formats: MP3, WAV, FLAC, OGG, M4A, etc.
177
"""
178
179
def get_input_document(document) -> types.InputDocument:
180
"""
181
Convert document to InputDocument.
182
183
Parameters:
184
- document: Document object or message with document
185
186
Returns:
187
InputDocument object for API calls
188
"""
189
190
def get_input_photo(photo) -> types.InputPhoto:
191
"""
192
Convert photo to InputPhoto.
193
194
Parameters:
195
- photo: Photo object or message with photo
196
197
Returns:
198
InputPhoto object for API calls
199
"""
200
201
def get_input_media(
202
file,
203
*,
204
thumb=None,
205
force_document: bool = False,
206
**kwargs
207
) -> types.TypeInputMedia:
208
"""
209
Convert file to appropriate InputMedia type.
210
211
Parameters:
212
- file: File path, bytes, or media object
213
- thumb: Thumbnail file
214
- force_document: Force InputMediaDocument instead of specific type
215
- **kwargs: Additional media attributes
216
217
Returns:
218
InputMediaPhoto, InputMediaDocument, or other InputMedia type
219
"""
220
221
def get_attributes(
222
file,
223
*,
224
mime_type: str = None,
225
attributes: List = None,
226
**kwargs
227
) -> List[types.TypeDocumentAttribute]:
228
"""
229
Generate document attributes for file.
230
231
Parameters:
232
- file: File path or file-like object
233
- mime_type: Override detected MIME type
234
- attributes: Custom attribute list
235
- **kwargs: Additional attribute parameters
236
237
Returns:
238
List of DocumentAttribute objects (filename, size, etc.)
239
"""
240
```
241
242
### Location Utilities
243
244
Handle geographical locations and file locations.
245
246
```python { .api }
247
def get_input_geo(geo) -> types.InputGeoPoint:
248
"""
249
Convert location to InputGeoPoint.
250
251
Parameters:
252
- geo: GeoPoint object or (latitude, longitude) tuple
253
254
Returns:
255
InputGeoPoint object
256
"""
257
258
def get_input_location(location) -> types.TypeInputFileLocation:
259
"""
260
Convert media to InputFileLocation for downloads.
261
262
Parameters:
263
- location: Media object, Document, Photo, etc.
264
265
Returns:
266
InputFileLocation for downloading the file
267
"""
268
269
def get_input_chat_photo(photo) -> Union[types.InputPhoto, types.InputFile]:
270
"""
271
Convert photo for use as chat profile photo.
272
273
Parameters:
274
- photo: Photo object or file
275
276
Returns:
277
InputPhoto or InputFile for setting as chat photo
278
"""
279
```
280
281
### Message Utilities
282
283
Work with message objects and IDs.
284
285
```python { .api }
286
def get_message_id(message) -> int:
287
"""
288
Extract message ID from message object or ID.
289
290
Parameters:
291
- message: Message object, ID, or InputMessage
292
293
Returns:
294
int: Message ID number
295
"""
296
297
def get_input_message(message) -> Union[int, types.InputMessage]:
298
"""
299
Convert message to InputMessage.
300
301
Parameters:
302
- message: Message object or ID
303
304
Returns:
305
InputMessage object or message ID
306
"""
307
```
308
309
### Text Processing
310
311
Handle text formatting and parsing.
312
313
```python { .api }
314
def sanitize_parse_mode(mode) -> object:
315
"""
316
Convert parse mode string to parser object.
317
318
Parameters:
319
- mode: 'md', 'markdown', 'html', or parser object
320
321
Returns:
322
Parser object for text formatting
323
"""
324
325
def parse_phone(phone) -> str:
326
"""
327
Normalize phone number format.
328
329
Parameters:
330
- phone: Phone number string
331
332
Returns:
333
str: Normalized phone number (international format)
334
335
Examples:
336
- "+1234567890" -> "+1234567890"
337
- "123-456-7890" -> "+11234567890"
338
- "(123) 456-7890" -> "+11234567890"
339
"""
340
341
def parse_username(username) -> str:
342
"""
343
Normalize username format.
344
345
Parameters:
346
- username: Username string (with or without @)
347
348
Returns:
349
str: Username without @ prefix
350
351
Examples:
352
- "@username" -> "username"
353
- "username" -> "username"
354
- "t.me/username" -> "username"
355
"""
356
```
357
358
### Collection Utilities
359
360
Work with lists and iterables.
361
362
```python { .api }
363
def chunks(iterable, size: int = 100):
364
"""
365
Split iterable into chunks of specified size.
366
367
Parameters:
368
- iterable: Any iterable object
369
- size: Maximum chunk size
370
371
Yields:
372
Lists of up to 'size' items
373
374
Usage:
375
for chunk in chunks(large_list, 50):
376
process_chunk(chunk)
377
"""
378
379
def is_list_like(obj) -> bool:
380
"""
381
Check if object behaves like a list.
382
383
Parameters:
384
- obj: Object to check
385
386
Returns:
387
bool: True if list-like (has __iter__ and __getitem__)
388
"""
389
```
390
391
### Call Utilities
392
393
Handle group call operations.
394
395
```python { .api }
396
def get_input_group_call(call) -> types.InputGroupCall:
397
"""
398
Convert group call to InputGroupCall.
399
400
Parameters:
401
- call: GroupCall object or call ID
402
403
Returns:
404
InputGroupCall object for API calls
405
"""
406
```
407
408
## Usage Examples
409
410
### Entity Resolution
411
412
```python
413
import asyncio
414
from telethon import TelegramClient, utils
415
416
async def entity_examples():
417
client = TelegramClient('session', api_id, api_hash)
418
await client.start()
419
420
# Different ways to reference entities
421
entities = [
422
'username', # Username
423
'@username', # Username with @
424
'+1234567890', # Phone number
425
123456789, # User ID
426
-100123456789, # Channel/supergroup ID
427
'https://t.me/username' # Telegram URL
428
]
429
430
for entity_ref in entities:
431
try:
432
# Get the entity
433
entity = await client.get_entity(entity_ref)
434
435
# Use utility functions
436
display_name = utils.get_display_name(entity)
437
peer_id = utils.get_peer_id(entity)
438
input_peer = utils.get_input_peer(entity)
439
440
print(f"Entity: {entity_ref}")
441
print(f" Display name: {display_name}")
442
print(f" Peer ID: {peer_id}")
443
print(f" Input peer type: {type(input_peer).__name__}")
444
print("---")
445
446
except Exception as e:
447
print(f"Could not resolve {entity_ref}: {e}")
448
449
await client.disconnect()
450
451
asyncio.run(entity_examples())
452
```
453
454
### Media Type Detection
455
456
```python
457
from telethon import utils
458
459
async def media_detection():
460
client = TelegramClient('session', api_id, api_hash)
461
await client.start()
462
463
chat = 'username'
464
465
# Check recent media messages
466
async for message in client.iter_messages(chat, limit=20):
467
if message.media:
468
print(f"Message {message.id}:")
469
470
# Detect media type
471
if utils.is_image(message.media):
472
print(" π· Image")
473
ext = utils.get_extension(message.media)
474
print(f" Extension: {ext}")
475
476
elif utils.is_video(message.media):
477
print(" π₯ Video")
478
if utils.is_gif(message.media):
479
print(" (Animated GIF)")
480
481
elif utils.is_audio(message.media):
482
print(" π΅ Audio")
483
484
else:
485
print(" π Document")
486
487
# Get file info
488
if hasattr(message.media, 'document'):
489
doc = message.media.document
490
print(f" Size: {doc.size} bytes")
491
print(f" MIME: {doc.mime_type}")
492
493
await client.disconnect()
494
```
495
496
### Text Processing
497
498
```python
499
from telethon import utils
500
501
def text_processing_examples():
502
# Phone number parsing
503
phones = [
504
"+1234567890",
505
"123-456-7890",
506
"(123) 456-7890",
507
"1.234.567.8900"
508
]
509
510
for phone in phones:
511
normalized = utils.parse_phone(phone)
512
print(f"Phone: {phone} -> {normalized}")
513
514
# Username parsing
515
usernames = [
516
"@username",
517
"username",
518
"t.me/username",
519
"https://t.me/username"
520
]
521
522
for username in usernames:
523
parsed = utils.parse_username(username)
524
print(f"Username: {username} -> {parsed}")
525
526
# Parse mode handling
527
modes = ['md', 'markdown', 'html', None]
528
for mode in modes:
529
parser = utils.sanitize_parse_mode(mode)
530
print(f"Parse mode: {mode} -> {type(parser).__name__}")
531
532
text_processing_examples()
533
```
534
535
### Collection Processing
536
537
```python
538
from telethon import utils
539
540
async def collection_examples():
541
client = TelegramClient('session', api_id, api_hash)
542
await client.start()
543
544
# Get a large list of messages
545
messages = await client.get_messages('username', limit=500)
546
547
# Process in chunks to avoid memory issues
548
for chunk in utils.chunks(messages, 50):
549
print(f"Processing chunk of {len(chunk)} messages")
550
551
# Process each chunk
552
for message in chunk:
553
if message.text:
554
# Do something with message
555
pass
556
557
# Check if various objects are list-like
558
test_objects = [
559
messages, # TotalList
560
[1, 2, 3], # Regular list
561
(1, 2, 3), # Tuple
562
"string", # String (iterable but not list-like)
563
42 # Number
564
]
565
566
for obj in test_objects:
567
is_list = utils.is_list_like(obj)
568
print(f"{type(obj).__name__}: list-like = {is_list}")
569
570
await client.disconnect()
571
```
572
573
### Advanced Entity Operations
574
575
```python
576
async def advanced_entity_ops():
577
client = TelegramClient('session', api_id, api_hash)
578
await client.start()
579
580
# Work with different entity types
581
entities = await client.get_dialogs(limit=10)
582
583
for dialog in entities:
584
entity = dialog.entity
585
586
try:
587
# Get various input types
588
input_peer = utils.get_input_peer(entity)
589
peer_id = utils.get_peer_id(entity)
590
display_name = utils.get_display_name(entity)
591
592
print(f"Entity: {display_name} (ID: {peer_id})")
593
594
# Check entity type and get specific input
595
if hasattr(entity, 'username'): # User or Channel
596
if entity.username:
597
print(f" Username: @{entity.username}")
598
599
if hasattr(entity, 'access_hash'): # Channel/User
600
if entity.megagroup or entity.broadcast:
601
input_channel = utils.get_input_channel(entity)
602
print(f" Input channel: {input_channel}")
603
elif not entity.bot:
604
input_user = utils.get_input_user(entity)
605
print(f" Input user: {input_user}")
606
607
# Get dialog input
608
input_dialog = utils.get_input_dialog(dialog)
609
print(f" Input dialog: {input_dialog}")
610
611
except Exception as e:
612
print(f"Error processing {display_name}: {e}")
613
614
print("---")
615
616
await client.disconnect()
617
```
618
619
### File and Media Utilities
620
621
```python
622
import os
623
from telethon import utils
624
625
async def file_utilities():
626
client = TelegramClient('session', api_id, api_hash)
627
await client.start()
628
629
# Send various file types and analyze
630
files_to_send = [
631
'image.jpg',
632
'video.mp4',
633
'audio.mp3',
634
'document.pdf'
635
]
636
637
chat = 'username'
638
639
for file_path in files_to_send:
640
if os.path.exists(file_path):
641
# Get attributes before sending
642
attributes = utils.get_attributes(file_path)
643
print(f"File: {file_path}")
644
print(f" Attributes: {len(attributes)}")
645
646
# Send file
647
message = await client.send_file(chat, file_path)
648
649
# Analyze sent media
650
if message.media:
651
ext = utils.get_extension(message.media)
652
print(f" Extension: {ext}")
653
654
# Get input versions for API calls
655
if utils.is_image(message.media):
656
input_photo = utils.get_input_photo(message.media)
657
print(f" Input photo: {input_photo}")
658
659
elif hasattr(message.media, 'document'):
660
input_doc = utils.get_input_document(message.media)
661
print(f" Input document: {input_doc}")
662
663
# Get file location for downloading
664
input_location = utils.get_input_location(message.media)
665
print(f" Input location: {input_location}")
666
667
print("---")
668
669
await client.disconnect()
670
```
671
672
## Types
673
674
```python { .api }
675
from typing import Union, List, Optional, Tuple, Any, Iterator
676
from telethon.tl import types
677
678
EntityLike = Union[int, str, types.User, types.Chat, types.Channel]
679
MediaLike = Union[types.Photo, types.Document, types.MessageMedia]
680
FileLike = Union[str, bytes, 'io.IOBase']
681
LocationLike = Union[types.GeoPoint, Tuple[float, float]]
682
PhoneNumber = str
683
Username = str
684
685
ParseMode = Union[str, object, None]
686
AttributeList = List[types.TypeDocumentAttribute]
687
ChunkIterator = Iterator[List[Any]]
688
```