Search code examples
pythontelegramtelethon

Telethon: how to get information about yourself correctly?


I want to write my own client for the Telegram messenger in Python. I use the Telethon library. I took the code example from their main page:

 from telethon import TelegramClient

 api_id = my_id
 api_hash = 'my_hash'

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

 print(client.get_me().stringify())

This code should output information about me to the console. When I run this code I get the error:

 AttributeError: 'coroutine' object has no attribute 'stringify'

in line

 print(client.get_me().stringify())

How to fix this error? How to receive information about yourself?


Solution

  • This is happening because get_me() is a coroutine in the Telethon library, and you need to await it to get the result. You can use the await keyword to asynchronously await the result.

    Try this:

    from telethon import TelegramClient
    
    api_id = my_id
    api_hash = 'my_hash'
    
    async def main():
        client = TelegramClient('Test2Session', api_id, api_hash)
        await client.start()
    
        me = await client.get_me()
        print(me.stringify())
    
    if __name__ == '__main__':
        import asyncio
        asyncio.run(main())