[Python] Task was destroyed but it is pending

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

  1. Stack

    Stack Membro Participativo

    I am writing a bot to automate actions in Telegram and using the telethon library. I encountered a problem when authorizing an account. To create a .session file, you need to wait for the security code. The program should wait until the user sends this code, but for some reason an error occurs: "Task was destroyed but it is pending!".

    It occurs on

    code = await asyncio.wait_for(future_code, timeout=300)


    When I first encountered this error, I decided to transfer the code from another project of mine, where authorization worked successfully, but this did not help.

    Tell me what I am doing wrong?

    *I apologize for possible errors, I use Google translator.

    My authorization code looks like this:

    from aiogram import F, Router
    from aiogram.fsm.context import FSMContext
    from aiogram.types.callback_query import CallbackQuery
    from aiogram.types import Message

    from telethon.sync import TelegramClient
    from telethon.errors import PhoneCodeInvalidError, PhoneCodeExpiredError, SessionPasswordNeededError, PhoneNumberInvalidError

    import kb, asyncio, logging
    from asyncio import Future
    from utils import *
    from states import *

    router = Router()


    events = {}


    @router.callback_query(F.data == 'error_code')
    async def error_code_btn(clbck: CallbackQuery, state: FSMContext):
    await state.clear()
    await clbck.message.delete()

    user_id = clbck.from_user.id
    type_message = 'welcome_message'

    isMessage(user_id, type_message)

    reply = kb.admin_panel if await adb.get_admin(user_id) else kb.user_panel
    messages[type_message][user_id] = await clbck.message.answer("<b>⚜️ Главное меню:</b>", reply_markup=reply)
    await clbck.message.answer("❗️ <b>Проверьте правильность введенных данных и повторите попытку позже.</b>", reply_markup=kb.close)



    @router.callback_query(F.data == 'active-deactive')
    async def check_session(clbck: CallbackQuery, state: FSMContext):
    user_id = clbck.from_user.id
    type_message = 'input_account_info'
    type_message_delete = 'welcome_message'

    isMessage(user_id, type_message)
    await delete_type_message(user_id, type_message_delete)

    user = await udb.get_user(user_id)
    if user['auth']:
    udb.update_settings(id=user_id, active=True)
    # TODO: Вход в клиент
    else:

    form = "<b>⚒️ Скопируйте форму ниже, заполните поля и отправьте следующим сообщением:</b>\n" \
    "1. Номер телефона: 380...\n" \
    "2. Пароль от аккаунта: ...\n\n" \
    "<b>Примечание:</b> Если пароль отсутствует - отправьте символ \"-\"."

    await state.set_state(AuthData.account_info)
    messages[type_message][user_id] = await clbck.message.answer(form)


    @router.message(AuthData.account_info)
    async def get_account_info(msg: Message, state: FSMContext):
    user_id = msg.from_user.id

    await msg.delete()
    await state.update_data(account_info=msg.text)
    await start_session(user_id, state)


    async def start_session(user_id, state: FSMContext):
    config = load_config()
    data = await state.get_data()

    lines = data['account_info'].strip().split("\n")
    phone = lines[0].split(": ")[1]

    future_code = Future()
    future_pass = Future()
    events[user_id] = future_code
    events[user_id + 1] = future_pass

    asyncio.create_task(
    create_session(
    user_id,
    config['api_id'],
    config['api_hash'],
    phone,
    future_code,
    future_pass,
    ))

    messages['input_account_info'][user_id] = await messages['input_account_info'][user_id].edit_text(text="⚙️ <b>На аккаунт пришел код!</b>\nВведите его ниже:", reply_markup=kb.error_code)
    await state.set_state(AuthData.code)


    @router.message(AuthData.code)
    async def generate_code(msg: Message, state: FSMContext):
    await msg.delete()

    await state.update_data(code=msg.text)
    data = await state.get_data()
    await state.clear()

    await process_create(msg=msg, data=data)


    async def process_create(msg: Message, data: dict):
    user_id = msg.from_user.id
    lines = data['account_info'].strip().split("\n")

    code = data['code']
    password = lines[1].split(": ")[1]

    future_code = events.get(user_id)
    future_pass = events.get(user_id + 1)

    if future_code and future_pass:
    future_code.set_result(code)
    del events[user_id]
    future_pass.set_result(password)
    del events[user_id + 1]


    async def create_session(user_id, api_id, api_hash, phone, future_code, future_pass):
    client = TelegramClient(f'sessions/{user_id}', api_id, api_hash)
    await client.connect()

    if not await client.is_user_authorized():
    try:
    message = messages['input_account_info'][user_id]

    session = await client.send_code_request(phone)
    code = await asyncio.wait_for(future_code, timeout=300)
    password = await asyncio.wait_for(future_pass, timeout=300)

    try:
    await client.sign_in(
    phone=phone,
    code=code,
    phone_code_hash=session.phone_code_hash
    )
    await client.disconnect()
    except PhoneCodeInvalidError:
    await message.edit_text("❗️ <b>Произошла ошибка</b>\nКод не корректный.")
    return
    except PhoneCodeExpiredError:
    await message.edit_text("❗️ <b>Произошла ошибка</b>\nАвторизация основных аккаунтов не допускается. Telegram заблокировал вход.")
    return
    except SessionPasswordNeededError:
    await client.sign_in(password=password)
    await client.disconnect()
    return
    except PhoneNumberInvalidError:
    await message.edit_text("❗️ <b>Произошла ошибка</b>\nНомер введен не правильно.")
    return
    except Exception as e:
    logging.error(f"Failed to sign in: {e}")
    await client.disconnect()
    await message.edit_text("❗️ <b>Произошла ошибка</b>\nУбедитесь, что ввёли правильные данные аккаунта.")
    return

    logging.info(f".session файл успешно создан для {user_id}.")

    Continue reading...

Compartilhe esta Página