Search code examples
pythontelegramtelethon

Python script stops responding when receiving saved messages


I am writing a script to download all of my saved messages from telegram using Telethon library to interact with Telegram's API.

But as soon as any method from the library gets called, the script gets stuck in some kind of a loop or is waiting for some response.

Any idea what could be the issue?

Here is a snippet of a code I run:

from telethon import TelegramClient
import asyncio

api_id = 12345678
api_hash = '' #hash value

client = TelegramClient('name', api_id, api_hash)
client.start()

async def main():
    saved = open('saved_messages.txt', 'a')
    me = await client.get_me()
    async for message in client.get_messages('me'):
        saved.write(f'{message.text}\n')
        print(message.id, message.text)
    saved.close()

asyncio.run(main())

All the code is from the quick-start.

What am I doing wrong? Please help.

I tried looking up the problem to see if anyone had already faced it but found nothing.


Solution

  • There are 2 issues, to begin:

    async for message in client.get_messages('me'):
    

    Isn't valid. You'll need to await client.get_messages, so make it:

    me = await client.get_me()
    messages = await client.get_messages('me', limit=100)
    for message in messages:
        ....
    

    Note the limit=100, otherwise you'll just receive the latest saved message


    As second, you'll need to use the event_loop from asyncio:

    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    

    This way I get a saved_messages.txt with the expected content.


    Full code:

    from telethon import TelegramClient
    import asyncio
    
    saved = open('saved_messages.txt', 'a')
    
    client = TelegramClient('anon', '1', '2')
    client.start()
    
    async def main():
        me = await client.get_me()
        messages = await client.get_messages('me', limit=100)
        for message in messages:
            saved.write(f'{message.text}\n')
            print(message.id, message.text)
        saved.close()
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())