skip to Main Content

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'}

2

Answers


  1. Chosen as BEST ANSWER

    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'}
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search