1

I'm trying to follow this answer using Telethon to download a specific number of messages from a telegram group. I had to modify the code because there were multiple errors and warnings and the library and its classes had also changed since then. This is what I have got so far:

import os
import sys
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerChat

session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
chat_id = <chat_id>

os.chdir(sys.path[0])

if f"{session_name}.session" in os.listdir():
    os.remove(f"{session_name}.session")

client = TelegramClient(session_name, api_id, api_hash)
await client.connect()
chat = InputPeerChat(chat_id)


client.get_messages(chat, limit=10)

however, running the above code on Jupyter I just get:

<coroutine object MessageMethods.get_messages at 0x1049c8cb0>

I tried to use the for msg in messages part to extract/parse the information, but I get the error:

TypeError: 'coroutine' object is not iterable

I would appreciate if you could help me know what is the canonical and concise way to download the specific number of last messages in a telegram group given the chat ID.

Foad S. Farimani
  • 12,396
  • 15
  • 78
  • 193
  • 1
    The type indicates it's a coroutine, and thus should be awaited. You forgot to `await`. Also note that question and answer is very old, I have left a comment in the currently accepted answer there. – Lonami Apr 02 '20 at 12:31
  • @Lonami would you please elaborate in an answer? – Foad S. Farimani Apr 02 '20 at 12:35
  • @Lonami and I'm afraid there are no accepted answers [here](https://stackoverflow.com/questions/44467293/how-can-i-download-the-chat-history-of-a-group-in-telegram)! – Foad S. Farimani Apr 02 '20 at 12:36

1 Answers1

0

Just set the entitiy like from whom to retrieve the message history and no need to construct InputPeer object.

from telethon.sync import TelegramClient

session_name = '<session_name>'
api_id = <api_id>
api_hash = '<api_hash>'

#chat = <chat id>
#chat = <user id>
#chat = 'https://t.me/group_invite_link'
chat = 'me'

client = TelegramClient(session_name, api_id, api_hash)
client.start()

messages = client.get_messages(chat, limit=5)
print(messages)

client.disconnect()

Goodarzi
  • 46
  • 5
  • Thanks man!! This is the best solution to my problem. Just wondering what format this is is. I need it in a pandas Dataframe – lorenzkort Oct 13 '20 at 15:58