0
# Message Operations
1
2
Comprehensive message handling including sending, receiving, editing, deleting, forwarding, and reading messages with support for formatting, media, and interactive buttons.
3
4
## Capabilities
5
6
### Sending Messages
7
8
Send text messages with formatting, media attachments, buttons, and various options.
9
10
```python { .api }
11
async def send_message(
12
self,
13
entity,
14
message='',
15
*,
16
reply_to=None,
17
parse_mode=(),
18
link_preview: bool = True,
19
file=None,
20
thumb=None,
21
force_document: bool = False,
22
clear_draft: bool = False,
23
buttons=None,
24
silent: bool = None,
25
background: bool = None,
26
supports_streaming: bool = False,
27
schedule=None,
28
comment_to=None,
29
ttl: int = None
30
) -> Message:
31
"""
32
Send a message to an entity (user, chat, or channel).
33
34
Parameters:
35
- entity: Target user, chat, channel, or their username/ID
36
- message: Text message content
37
- reply_to: Message ID or Message object to reply to
38
- parse_mode: Text formatting ('md', 'html', or parser object)
39
- link_preview: Whether to show link previews
40
- file: File, photo, document, or media to send
41
- thumb: Custom thumbnail for documents
42
- force_document: Send as document instead of photo/video
43
- clear_draft: Clear the draft after sending
44
- buttons: Inline or reply keyboard buttons
45
- silent: Send silently (no notification)
46
- background: Send in background (for channels)
47
- supports_streaming: Enable streaming for videos
48
- schedule: Schedule message for future delivery
49
- comment_to: Reply to specific message in channel comments
50
- ttl: Time-to-live for self-destructing media
51
52
Returns:
53
Message: The sent message object
54
55
Raises:
56
- ChatWriteForbiddenError: If cannot write to chat
57
- MessageTooLongError: If message exceeds limits
58
- MediaInvalidError: If media is invalid
59
"""
60
```
61
62
### Retrieving Messages
63
64
Get messages from chats with various filtering and pagination options.
65
66
```python { .api }
67
async def get_messages(
68
self,
69
entity,
70
*args,
71
**kwargs
72
) -> TotalList:
73
"""
74
Get messages from an entity with all results loaded.
75
76
Parameters same as iter_messages().
77
78
Returns:
79
TotalList: List of Message objects with total count
80
"""
81
82
def iter_messages(
83
self,
84
entity,
85
limit: int = 1,
86
*,
87
offset_date: datetime = None,
88
offset_id: int = 0,
89
max_id: int = 0,
90
min_id: int = 0,
91
add_offset: int = 0,
92
search: str = None,
93
filter=None,
94
from_user=None,
95
batch_size: int = 100,
96
wait_time: int = None,
97
ids=None,
98
reverse: bool = False,
99
reply_to: int = None,
100
scheduled: bool = False
101
):
102
"""
103
Iterate through messages in an entity with memory-efficient pagination.
104
105
Parameters:
106
- entity: Chat, channel, or user to get messages from
107
- limit: Maximum number of messages to retrieve
108
- offset_date: Start from messages before this date
109
- offset_id: Start from this message ID
110
- max_id: Get messages with ID less than this
111
- min_id: Get messages with ID greater than this
112
- add_offset: Additional offset for pagination
113
- search: Search for messages containing this text
114
- filter: Filter messages by type (InputMessagesFilter)
115
- from_user: Only messages from this user
116
- batch_size: Number of messages per API request
117
- wait_time: Wait time between requests
118
- ids: Specific message IDs to retrieve
119
- reverse: Iterate in reverse chronological order
120
- reply_to: Only messages replying to this message ID
121
- scheduled: Get scheduled messages instead
122
123
Yields:
124
Message: Individual message objects
125
"""
126
```
127
128
### Message Editing
129
130
Edit existing messages with new content, formatting, or media.
131
132
```python { .api }
133
async def edit_message(
134
self,
135
entity,
136
message=None,
137
text: str = None,
138
*,
139
parse_mode=(),
140
link_preview: bool = True,
141
file=None,
142
thumb=None,
143
force_document: bool = False,
144
buttons=None,
145
schedule=None
146
) -> Message:
147
"""
148
Edit an existing message's content or media.
149
150
Parameters:
151
- entity: Chat where the message is located
152
- message: Message ID or Message object to edit
153
- text: New text content (None to keep current)
154
- parse_mode: Text formatting ('md', 'html', or parser object)
155
- link_preview: Whether to show link previews
156
- file: New file/media to replace current media
157
- thumb: New thumbnail for documents
158
- force_document: Send new media as document
159
- buttons: New button layout
160
- schedule: Reschedule the message
161
162
Returns:
163
Message: The edited message object
164
165
Raises:
166
- MessageNotModifiedError: If no changes made
167
- MessageEditTimeExpiredError: If edit window expired
168
- MessageAuthorRequiredError: If not message author
169
"""
170
```
171
172
### Message Deletion
173
174
Delete messages from chats with options for revocation.
175
176
```python { .api }
177
async def delete_messages(
178
self,
179
entity,
180
message_ids,
181
*,
182
revoke: bool = True
183
) -> List[types.messages.AffectedMessages]:
184
"""
185
Delete messages from a chat.
186
187
Parameters:
188
- entity: Chat containing the messages
189
- message_ids: List of message IDs or Message objects to delete
190
- revoke: Delete for all participants (vs. just yourself)
191
192
Returns:
193
List of AffectedMessages objects with deletion results
194
195
Raises:
196
- MessageDeleteForbiddenError: If cannot delete messages
197
- MessageIdInvalidError: If message ID doesn't exist
198
"""
199
```
200
201
### Message Forwarding
202
203
Forward messages between chats with various options.
204
205
```python { .api }
206
async def forward_messages(
207
self,
208
entity,
209
messages,
210
from_peer=None,
211
*,
212
background: bool = None,
213
with_my_score: bool = None,
214
silent: bool = None,
215
as_album: bool = None,
216
schedule=None,
217
noforwards: bool = None,
218
drop_author: bool = None,
219
drop_media_captions: bool = None
220
) -> List[Message]:
221
"""
222
Forward messages to another chat.
223
224
Parameters:
225
- entity: Target chat to forward to
226
- messages: Message IDs or Message objects to forward
227
- from_peer: Source chat (auto-detected if not provided)
228
- background: Forward in background (channels only)
229
- with_my_score: Include sender's game score
230
- silent: Forward silently (no notification)
231
- as_album: Group messages as album
232
- schedule: Schedule forwarded messages
233
- noforwards: Prevent further forwarding
234
- drop_author: Don't show original author
235
- drop_media_captions: Remove media captions
236
237
Returns:
238
List[Message]: The forwarded message objects
239
"""
240
```
241
242
### Message Reading
243
244
Mark messages as read and manage read status.
245
246
```python { .api }
247
async def send_read_acknowledge(
248
self,
249
entity,
250
message=None,
251
*,
252
max_id: int = None,
253
clear_mentions: bool = False
254
) -> bool:
255
"""
256
Mark messages as read in a chat.
257
258
Parameters:
259
- entity: Chat to mark messages as read
260
- message: Specific message to mark as read (marks all up to this)
261
- max_id: Mark all messages up to this ID as read
262
- clear_mentions: Also clear mention notifications
263
264
Returns:
265
bool: True if read status updated successfully
266
"""
267
```
268
269
### Message Pinning
270
271
Pin and unpin messages in chats.
272
273
```python { .api }
274
async def pin_message(
275
self,
276
entity,
277
message=None,
278
*,
279
notify: bool = False,
280
pm_oneside: bool = False
281
) -> types.Updates:
282
"""
283
Pin a message in a chat.
284
285
Parameters:
286
- entity: Chat to pin message in
287
- message: Message ID or Message object to pin
288
- notify: Send notification about pinned message
289
- pm_oneside: Pin only for yourself (private chats)
290
291
Returns:
292
Updates object with pin result
293
294
Raises:
295
- ChatAdminRequiredError: If admin rights required
296
- MessageIdInvalidError: If message doesn't exist
297
"""
298
299
async def unpin_message(
300
self,
301
entity,
302
message=None,
303
*,
304
notify: bool = False
305
) -> types.Updates:
306
"""
307
Unpin a message or all messages in a chat.
308
309
Parameters:
310
- entity: Chat to unpin message in
311
- message: Specific message to unpin (None for all)
312
- notify: Send notification about unpinned message
313
314
Returns:
315
Updates object with unpin result
316
"""
317
```
318
319
### Message Formatting
320
321
Control text formatting and parsing modes.
322
323
```python { .api }
324
@property
325
def parse_mode(self) -> str:
326
"""Get current parse mode ('md', 'html', or None)."""
327
328
@parse_mode.setter
329
def parse_mode(self, mode: str):
330
"""
331
Set default parse mode for messages.
332
333
Parameters:
334
- mode: 'md' for Markdown, 'html' for HTML, None for plain text
335
"""
336
```
337
338
## Usage Examples
339
340
### Basic Message Sending
341
342
```python
343
import asyncio
344
from telethon import TelegramClient
345
346
async def send_basic_messages():
347
client = TelegramClient('session', api_id, api_hash)
348
await client.start()
349
350
# Send simple text message
351
await client.send_message('username', 'Hello, World!')
352
353
# Send with formatting
354
await client.send_message(
355
'username',
356
'**Bold text** and *italic text*',
357
parse_mode='md'
358
)
359
360
# Send with HTML formatting
361
await client.send_message(
362
'username',
363
'<b>Bold</b> and <i>italic</i> text',
364
parse_mode='html'
365
)
366
367
await client.disconnect()
368
369
asyncio.run(send_basic_messages())
370
```
371
372
### Advanced Message Operations
373
374
```python
375
from telethon import Button
376
from datetime import datetime, timedelta
377
378
async def advanced_messaging():
379
client = TelegramClient('session', api_id, api_hash)
380
await client.start()
381
382
# Send message with buttons
383
await client.send_message(
384
'username',
385
'Choose an option:',
386
buttons=[
387
[Button.inline('Option 1', b'opt1')],
388
[Button.inline('Option 2', b'opt2')],
389
[Button.url('Visit Website', 'https://example.com')]
390
]
391
)
392
393
# Send scheduled message (1 hour from now)
394
schedule_time = datetime.now() + timedelta(hours=1)
395
await client.send_message(
396
'username',
397
'This message was scheduled!',
398
schedule=schedule_time
399
)
400
401
# Send silent message
402
await client.send_message(
403
'username',
404
'This won\'t notify the user',
405
silent=True
406
)
407
408
# Reply to a message
409
async for message in client.iter_messages('username', limit=1):
410
await client.send_message(
411
'username',
412
'This is a reply!',
413
reply_to=message.id
414
)
415
break
416
417
await client.disconnect()
418
```
419
420
### Message Retrieval and Search
421
422
```python
423
async def retrieve_messages():
424
client = TelegramClient('session', api_id, api_hash)
425
await client.start()
426
427
chat = 'username'
428
429
# Get recent messages
430
messages = await client.get_messages(chat, limit=10)
431
for msg in messages:
432
print(f"{msg.sender.first_name}: {msg.text}")
433
434
# Search for specific text
435
async for message in client.iter_messages(chat, search='hello'):
436
print(f"Found: {message.text}")
437
438
# Get messages from specific user
439
async for message in client.iter_messages(chat, from_user='specific_user'):
440
print(f"From specific user: {message.text}")
441
442
# Get media messages only
443
from telethon.tl.types import InputMessagesFilterPhotos
444
async for message in client.iter_messages(chat, filter=InputMessagesFilterPhotos):
445
print(f"Photo message: {message.id}")
446
447
await client.disconnect()
448
```
449
450
### Message Editing and Management
451
452
```python
453
async def manage_messages():
454
client = TelegramClient('session', api_id, api_hash)
455
await client.start()
456
457
chat = 'username'
458
459
# Send a message
460
message = await client.send_message(chat, 'Original message')
461
462
# Edit the message
463
await client.edit_message(
464
chat,
465
message.id,
466
'Edited message with **formatting**',
467
parse_mode='md'
468
)
469
470
# Pin the message
471
await client.pin_message(chat, message, notify=True)
472
473
# Forward to another chat
474
await client.forward_messages('another_chat', message)
475
476
# Mark as read
477
await client.send_read_acknowledge(chat, message)
478
479
# Delete the message (after 5 seconds)
480
await asyncio.sleep(5)
481
await client.delete_messages(chat, [message.id])
482
483
await client.disconnect()
484
```
485
486
## Types
487
488
```python { .api }
489
from typing import Union, List, Optional, Any
490
from datetime import datetime
491
from telethon.tl import types
492
from telethon import custom
493
494
EntityLike = Union[int, str, types.User, types.Chat, types.Channel]
495
MessageLike = Union[int, types.Message, custom.Message]
496
ButtonLike = Union[Button, List[Button], List[List[Button]]]
497
FileLike = Union[str, bytes, types.Document, types.Photo]
498
ParseMode = Union[str, object, None]
499
500
class Message:
501
"""Enhanced message object with utility methods"""
502
id: int
503
text: str
504
date: datetime
505
sender: types.User
506
chat: Union[types.User, types.Chat, types.Channel]
507
media: Optional[Any]
508
reply_to_msg_id: Optional[int]
509
510
class TotalList(List):
511
"""List with total count attribute"""
512
total: int
513
```