How do I authorize with a Telethon QR code?

Viewed 227

I'm trying to authorize in telethon via QR. In the docs of telegram I found the method exportLoginToken, which allows you to create a token for qr code. If I understand it correctly, the desktop telegram client uses this mechanics. You scan the qr from an authorized device and the session opens on the pc.

Telethon also has it. Example from the documentation:

with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.auth.ExportLoginTokenRequest(
    api_id=42,
    api_hash='some string here',
    except_ids=[42]
))
print(result.stringify())

If we don't have an active session, it will create one when we enter as telethon. For this we need a number and a code. Or an active session and a connected client The telethon docs say: Note that you must be connected before invoking this, as with any other request.

So in order to create an authorization token on the new device I must already be authorized? How do I get a token for the qr code on a device that has no active sessions?

1 Answers

When the documentation says that you must be connected, it means that you must call the method TelegramClient.connect which connects you to telegram.

So if you do this, it will work out:

import telethon
from telethon import TelegramClient
from qrcode import QRCode
from base64 import urlsafe_b64encode as base64url

qr = QRCode()

def gen_qr(token:str):
    qr.clear()
    qr.add_data(token)
    qr.print_ascii()

def display_url_as_qr(url):
    print(url)  # do whatever to show url as a qr to the user
    gen_qr(url)

async def main(client: telethon.TelegramClient):
    if(not client.is_connected()):
        await client.connect()
    client.connect()
    qr_login = await client.qr_login()
    print(client.is_connected())
    r = False
    while not r:
        display_url_as_qr(qr_login.url)
        # Important! You need to wait for the login to complete!
        try:
            r = await qr_login.wait(10)
        except:
            await qr_login.recreate()

TELEGRAM_API_ID=
TELEGRAM_API_HASH=

client = TelegramClient("SessionName", TELEGRAM_API_ID, TELEGRAM_API_HASH)
client.loop.run_until_complete(main(client))
Related