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

泪湿孤枕 提交于 2020-06-28 09:39:08

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/58890931/is-it-possible-to-create-a-telethon-client-starting-from-auth-key-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!