I could get messages from chats but I need to add sender name, date and time along with the message.
Asked
Active
Viewed 5,719 times
1 Answers
8
Yes. And everything is explained in the docs, looking through it or simply searching for messages leads you to iter_messages
.
Below the list of arguments the function takes, you have the instance the method returns. As an example:
# From most-recent to oldest
async for message in client.iter_messages(chat):
print(message.id, message.text)
# From oldest to most-recent
async for message in client.iter_messages(chat, reverse=True):
print(message.id, message.text)
# Filter by sender
async for message in client.iter_messages(chat, from_user='me'):
print(message.text)
# Server-side search with fuzzy text
async for message in client.iter_messages(chat, search='hello'):
print(message.id)
# Filter by message type:
from telethon.tl.types import InputMessagesFilterPhotos
async for message in client.iter_messages(chat, filter=InputMessagesFilterPhotos):
print(message.photo)
# Getting comments from a post in a channel:
async for message in client.iter_messages(channel, reply_to=123):
print(message.chat.title, message.text)
The returned Message instance has these attributes and methods you can use:
message.date
- The UTC+0 datetime object indicating when this message was sent. This will always be present except for empty messages.
message.get_sender()
- Returns sender but will make an API call to find the sender unless it’s already cached.
So given all of this you have:
async for message in client.iter_messages(chat):
date = message.date
sender = await message.get_sender()
name = sender.first_name

0stone0
- 34,288
- 4
- 39
- 64

Marcel Alexandru
- 460
- 1
- 6
- 10
-
2When using `iter_messages`, `message.sender` will always be present. `get_sender` is there for things like message events, where the `sender` might be missing. – Lonami Jul 27 '21 at 20:07