3

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Dr.Die_OXide
  • 300
  • 2
  • 18

1 Answers1

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
  • 2
    When 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