Alex
Alex

Reputation: 41

FastAPI as backend for Telethon

I'm trying to make api auth with telethon work. I'm sending request to endpoint where telegram client is initialized and trying to send code request to telegram. But there is input() and I didn't find any solution to pass code as variable

@router.get('/code')
async def send_code_request(phone: str):
    client = get_telegram_client(phone)
    await client.start(phone)
    return {'msg': 'code sent'}

Upvotes: 2

Views: 2156

Answers (2)

Alex
Alex

Reputation: 41

I found easier solution, but there is one con - when authorizing via session sign_in() method is requiring to execute send_code_request() method first so there is will be 2 same code messages

async def get_telegram_client(session: str = None) -> TelegramClient:
return TelegramClient(
    StringSession(session),
    api_id=settings.TELEGRAM_API_ID,
    api_hash=settings.TELEGRAM_API_HASH
)

@router.post('/code')
async def send_authorizarion_code(payload: TelegramSendCode):
    client = await get_telegram_client()
    await client.connect()
    try:
        await client.send_code_request(payload.phone)
    except FloodWaitError as e:
        return {
            'FloodWaitError': {
                'phone_number': e.request.phone_number,
                'seconds': e.seconds
            }}
    else:
        return {
            'msg': 'code sent',
            'session': client.session.save()
        }


@router.post('/auth')
async def authorize(payload: TelegramAuth):
    client = await get_telegram_client(payload.session)
    await client.connect()
    await client.send_code_request(payload.phone)
    await client.sign_in(code=payload.code, phone=payload.phone)
    return {'msg': 'signed in'}

Upvotes: 1

painor
painor

Reputation: 1237

I'm assuming you're using .start() for that.

.start() accepts a callback that is by default input() you can pass your own input like so.

client.start(code_callback=your_callback) and your callback should should return the code.

This can all be found here in the start docs

Upvotes: 0

Related Questions