[Python] How to ensure receiving an SMS verification code from Telegram using Telethon?

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm currently working on a Python project where I need to authenticate a user via Telegram's API using the Telethon library. I intend to receive the authentication code via SMS, but I consistently receive a voice call instead. I'm looking for a way to force or ensure that Telegram sends the verification code through SMS.

    Here's the relevant part of my code:

    from telethon.sync import TelegramClient
    from telethon.errors import SessionPasswordNeededError, FloodWaitError

    api_id = 'your_api_id' # Replace with your actual API ID
    api_hash = 'your_api_hash' # Replace with your actual API hash
    phone_number = '+1234567890' # Replace with the phone number you're using

    client = TelegramClient('anon', api_id, api_hash)

    async def send_code_via_sms():
    await client.connect()
    if not await client.is_user_authorized():
    try:
    # Explicitly request the code via SMS
    result = await client.send_code_request(phone=phone_number, force_sms=True)
    print("Code request sent via SMS. Please check your messages.")
    # Proceed with handling the code
    code = input("Enter the code: ")
    await client.sign_in(phone=phone_number, code=code, phone_code_hash=result.phone_code_hash)
    print("Signed in successfully!")
    except FloodWaitError as e:
    print(f"Need to wait for {e.seconds} seconds before trying again.")
    except Exception as e:
    print(f"Failed to sign in: {e}")
    else:
    print("Already authorized!")


    Despite setting force_sms=True, the verification code still not coming via a SMS. I've checked the Telegram settings to ensure that the phone number is correct and that SMS notifications are enabled.

    Questions:

    1. How can I modify my Telethon script to ensure I receive the SMS instead of a voice call?
    2. Are there specific conditions under which Telegram decides to send a voice call instead of SMS, and can they be influenced programmatically? Thank you for any insights or suggestions you can provide!

    Continue reading...

Compartilhe esta Página