Is there a way in Telethon to get messages from chats along with the sender name, date and time?

Viewed 2941

I could get messages from chats but I need to add sender name, date and time along with the message.

1 Answers

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
Related