0

I am trying to do an small test using Telethon from a Thread but when requesting the authorization code to Telegram, it never arrives in my Telegram chat. Here is the code:

import asyncio
from threading import Thread

from telethon import TelegramClient
from telethon.sessions import StringSession

phone = "+5312345678"
api_id = 12345
api_hash = "xxxxxxxx"


def sync(func):
    def wrapper(*args, **kwargs):
        loop = asyncio.new_event_loop()
        loop.run_until_complete(func(*args, **kwargs))

    return wrapper


@sync
async def main():
    client = TelegramClient(StringSession(), api_id, api_hash)
    await client.connect()
    res = await client.send_code_request(phone)  # <- REQUESTED HERE (I also tried forcing SMS)
    await client.disconnect()  # no try/finally to keep example simple
    print("hash:", res.phone_code_hash)


Thread(target=main).start()

The code executes without errors and the hash is printed, but the code never arrives in Telegram, so my question is if there is something wrong with the code? am I doing something wrong in the usage of async Telethon API inside a thread or it is just Telegram blocking me for something similar to: Telegram does not send authorization code if the request was sent from telethon code hosted on Heroku

  • 1
    If the hash is printed, this means Telethon made the request, and is now up to Telegram to send the code (or not). Unfortunately, if Telegram decides to not send the code for any reason, Telethon cannot really "fix" this behavior. – Lonami Oct 17 '22 at 08:55
  • @Lonami, thanks, was thinking that maybe there was something wrong with my way of using the async stuff from within the Thread that caused connection to be dropped too soon or tasks to be pending, I sometimes saw after executing the script that the console reported that some tasks didn't finished – Asiel Diaz Benitez Oct 17 '22 at 15:02

1 Answers1

0

so, after some more tests, it seems the issue is because I am disconnecting right after requesting the code:

await client.disconnect()

and it seems Telegram doesn't sends the code if it detects the client dropped the connection right away after requesting it, maybe because it is suspicious (ex. an script requesting codes for a lot of users in a batch)