[Python] Pyrogram start() hangs after sign_in() — how to structure multiple userbot sessions...

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm developing a system using Pyrogram where multiple users can authenticate their own Telegram accounts directly through a Telegram bot, by sending their phone number and verification code via chat — without using the terminal. After logging in, each session begins monitoring a specific channel and saving all new messages into a MongoDB database.

    ✅ What I can already do: I can easily authenticate a single account using the terminal by calling send_code(), pasting the received code, and then calling sign_in(), followed by start(). From there, I can list channels and copy messages without issues.

    What I'm trying to do (and what's not working): Allow multiple users to authenticate their own accounts through a bot (with bot_token);

    They send their phone number and receive the verification code via the bot chat;

    After sending the code, the system logs in and starts the session;

    Then, the bot starts monitoring the user-selected channel.

    Current structure: await user_client.sign_in(phone_number, phone_code_hash, code)

    await user_client.start() # <- This hangs, the code stops here

    await message.reply("Authenticated successfully!") # This line is never reached

    What I want to know: Has anyone ever built something similar to this?

    Is there a proper way to manage multiple Client() sessions with Pyrogram, each running in parallel without conflicts?

    How can I make sure start() doesn't hang after sign_in() in this scenario?

    How can I handle on_message separately for each user session, without blocking the main bot?

    Is there any example of a scalable structure for this? (userbots with 100% authentication via bot, no terminal involved)

    import pyrogram
    from pyrogram import Client, filters
    from pyrogram.enums import ChatMembersFilter
    from pyrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, FloodWait
    from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ChatMemberUpdated

    app = Client(
    f'{Client_bot}',
    api_id=getenv('TELEGRAM_API_ID'),
    api_hash=getenv('TELEGRAM_API_HASH'),
    bot_token=getenv(bot_token),
    )

    # retornar_usuario e escrever_usuario #receives and writes to the database

    @app.on_message(filters.command("auth"))
    async def auth_command(client, message):
    id = message.chat.id
    phone_number = retornar_usuario(id, "Usuario", "Telefone")

    if not phone_number:
    await message.reply("No phone number found.")
    return

    session_name = f"{SESSION_DIR}/{id}"
    user_client = Client(
    session_name,
    api_id=getenv('TELEGRAM_API_ID'),
    api_hash=getenv('TELEGRAM_API_HASH'),
    phone_number=phone_number,
    no_updates=False
    )

    escrever_usuario(id, 'Usuario', 'Config', 'code')
    await message.reply("Please send the verification code you received on Telegram.")

    try:
    if os.path.exists(f"{session_name}.session"):
    os.remove(f"{session_name}.session")

    await user_client.connect()
    code = await user_client.send_code(phone_number)

    user_data[id] = {
    "phone_number": phone_number,
    "phone_code_hash": code.phone_code_hash,
    "client": user_client,
    "channels": [],
    "active": False,
    "connected": True
    }

    except Exception as e:
    await message.reply(f"Error: {str(e)}")
    await user_client.stop()

    @app.on_message()
    async def Query(client, message):
    id = message.chat.id
    messages = message.text

    Config = retornar_usuario(id, 'Usuario', 'Config')
    if Config == 'code':
    user_client = user_data[id]["client"]
    phone_number = user_data[id]["phone_number"]
    phone_code_hash = user_data[id]["phone_code_hash"]

    try:
    await user_client.sign_in(phone_number, phone_code_hash, messages)
    user_data[id]["active"] = True

    # This is where it hangs
    await user_client.start()

    await message.reply("Authenticated successfully!")
    escrever_usuario(id, 'Usuario', 'Config', 'authenticated')

    except Exception as e:
    await message.reply(f"Authentication error: {str(e)}")
    await user_client.stop()


    If anyone here has built something like this or has suggestions for a stable structure (using asyncio, multiprocessing, threads, or other patterns), I’d really appreciate your help!

    Thanks in advance!

    Continue reading...

Compartilhe esta Página