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
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)