Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a telethon client starting from auth_key only?

The hello world of telethon looks like:

from telethon import TelegramClient

client = TelegramClient(name, api_id, api_hash)

async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello to myself!')

with client:
    client.loop.run_until_complete(main())

Like this it will ask me to sign in the first time, by providing phone and confirmation code. Next time it will reuse information stored locally.

What i want is to give it a auth_key and use that. So basically i want it to look like this: from telethon import TelegramClient

auth_key = "ca03d.....f8ed" # a long hex string

client = TelegramClient(name, api_id, api_hash, auth_key=auth_key)

async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello to myself!')

with client:
    client.loop.run_until_complete(main())
like image 925
tzador Avatar asked Oct 29 '25 12:10

tzador


1 Answers

While it is possible to use the auth_key directly, there are better options available, such as using StringSession as documented:

from telethon.sync import TelegramClient
from telethon.sessions import StringSession

# Generating a new one
with TelegramClient(StringSession(), api_id, api_hash) as client:
    print(client.session.save())

# Converting SQLite (or any) to StringSession
with TelegramClient(name, api_id, api_hash) as client:
    print(StringSession.save(client.session))

# Usage
string = '1aaNk8EX-YRfwoRsebUkugFvht6DUPi_Q25UOCzOAqzc...'
with TelegramClient(StringSession(string), api_id, api_hash) as client:
    client.loop.run_until_complete(client.send_message('me', 'Hi'))

Be careful not to share this string, as anyone would gain access to the account. This string contains the auth_key (as you wanted) along with other required information to perform a successful connection.

like image 106
Lonami Avatar answered Nov 01 '25 13:11

Lonami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!