Andrey Epifantsev
Andrey Epifantsev

Reputation: 1104

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?

Upvotes: 0

Views: 635

Answers (2)

Gilillo
Gilillo

Reputation: 11

If you want to keep the oneliner you can only by changing the import to:

from telethon.sync import TelegramClient

With this, you don't have to await responses between method calls.
More info about telethon.sync.
So, in your code, this piece should work:

 from telethon.sync import TelegramClient

 api_id = my_id
 api_hash = 'my_hash'

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

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

Upvotes: 1

RAJ PATEL
RAJ PATEL

Reputation: 161

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())

Upvotes: 4

Related Questions