Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

ns nen&

  1. User

    ns nen&

  2. Assistant

    It seems your message is unclear. Could you please provide more context or clarify what you're asking? I'm here to help!

  3. User

    import asyncio import logging import time from typing import Dict, Any from aiogram import Dispatcher, types, F, Bot from aiogram.utils.keyboard import InlineKeyboardBuilder from aiogram.fsm.context import FSMContext

    from ..data import get_user_api_key from ..api import SmsHubAPI from ..utils import safe_edit_or_send_message, safe_delete_message from ..constants import SERVICE_DISPLAY_NAMES

    logger = logging.getLogger(name)

    Глобальная переменная для активаций

    user_activations: Dict[int, Dict[str, Dict[str, Any]]] = {}

    async def current_activations_handler(callback_query: types.CallbackQuery, state: FSMContext): try: await callback_query.answer() except Exception as e: logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_id = callback_query.from_user.id
    activations = user_activations.get(user_id, {})
    
    if not activations:
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
        keyboard.adjust(1)
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="У вас нет активных активаций.",
            state=state,
            reply_markup=keyboard.as_markup()
        )
        return
    
    keyboard = InlineKeyboardBuilder()
    for activation_id, data in activations.items():
        service_name = SERVICE_DISPLAY_NAMES.get(data['service'], data['service'])
        keyboard.button(
            text=f"{service_name} ({data['number']}) - {data['status']}",
            callback_data=f"manage_activation:{activation_id}"
        )
    keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
    keyboard.adjust(1)
    
    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text="Ваши текущие активации:",
        state=state,
        reply_markup=keyboard.as_markup()
    )
    

    async def manage_activation_handler(callback_query: types.CallbackQuery, state: FSMContext): try: await callback_query.answer() except Exception as e: logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_id = callback_query.from_user.id
    activation_id = callback_query.data.split(":")[1]
    activations = user_activations.get(user_id, {})
    activation = activations.get(activation_id)
    
    if not activation:
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация не найдена.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
        return
    
    service_name = SERVICE_DISPLAY_NAMES.get(activation['service'], activation['service'])
    
    keyboard = InlineKeyboardBuilder()
    
    if activation['status'] == 'Ожидание SMS':
        keyboard.button(text="❌ Отменить активацию", callback_data=f"cancel_activation:{activation_id}")
    elif activation['status'].startswith('Код получен'):
        keyboard.button(text="📂 Текущие активации", callback_data="current_activations")
        keyboard.button(text="✅ Завершить активацию", callback_data=f"complete_activation:{activation_id}")
    elif activation['status'].startswith('Ожидание повторного SMS'):
        keyboard.button(text="✅ Завершить активацию", callback_data=f"complete_activation:{activation_id}")
    else:
        keyboard.button(text="✅ Завершить активацию", callback_data=f"complete_activation:{activation_id}")
        keyboard.button(text="❌ Отменить активацию", callback_data=f"cancel_activation:{activation_id}")
    
    keyboard.button(text="🔙 Назад", callback_data="current_activations")
    keyboard.adjust(1)
    
    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=(
            f"*Активация:* {activation_id}\n"
            f"*Сервис:* {service_name}\n"
            f"*Номер:* `{activation['number']}`\n"
            f"*Статус:* {activation['status']}"
        ),
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown"
    )
    

    async def cancel_activation_handler(callback_query: types.CallbackQuery, state: FSMContext): try: await callback_query.answer() except Exception as e: logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_id = callback_query.from_user.id
    activation_id = callback_query.data.split(":")[1]
    user_api_key = get_user_api_key(user_id)
    smshub_api = SmsHubAPI(user_api_key)
    
    activations = user_activations.get(user_id, {})
    activation = activations.get(activation_id)
    
    if activation:
        task = activation.get('task')
        if task:
            task.cancel()
    
        result = await smshub_api.cancel_activation(activation_id)
        logger.info(f"Активация {activation_id} отменена на стороне API: {result}")
    
        del activations[activation_id]
    
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="🔙 Назад", callback_data="current_activations")
        keyboard.adjust(1)
    
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация успешно отменена.",
            state=state,
            reply_markup=keyboard.as_markup()
        )
    else:
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация не найдена.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
    

    async def request_another_sms_handler(callback_query: types.CallbackQuery, state: FSMContext): try: await callback_query.answer() except Exception as e: logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_id = callback_query.from_user.id
    activation_id = callback_query.data.split(":")[1]
    user_api_key = get_user_api_key(user_id)
    smshub_api = SmsHubAPI(user_api_key)
    activations = user_activations.get(user_id, {})
    activation = activations.get(activation_id)
    
    if not activation:
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация не найдена.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
        return
    
    result = await smshub_api.set_status(activation_id, status="3")
    if result == "ACCESS_RETRY_GET":
        task = activation.get('task')
        if task:
            task.cancel()
    
        task = asyncio.create_task(poll_for_sms(
            bot=callback_query.message.bot,
            user_id=user_id,
            chat_id=callback_query.from_user.id,
            activation_id=activation_id,
            smshub_api=smshub_api
        ))
        activation['task'] = task
        activation['status'] = 'Ожидание повторного SMS'
    
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Запрошен повторный SMS. Ожидание SMS...",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
    else:
        logger.error(f"Не удалось запросить повторное SMS. Ответ: {result}")
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Не удалось запросить повторный SMS. Попробуйте снова.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
    

    async def complete_activation_handler(callback_query: types.CallbackQuery, state: FSMContext): try: await callback_query.answer() except Exception as e: logger.warning(f"Не удалось ответить на callback_query: {e}")

    user_id = callback_query.from_user.id
    activation_id = callback_query.data.split(":")[1]
    user_api_key = get_user_api_key(user_id)
    smshub_api = SmsHubAPI(user_api_key)
    activations = user_activations.get(user_id, {})
    activation = activations.get(activation_id)
    
    if not activation:
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация не найдена.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
        return
    
    result = await smshub_api.set_status(activation_id, status="6")
    if result == "ACCESS_ACTIVATION":
        task = activation.get('task')
        if task:
            task.cancel()
    
        del activations[activation_id]
    
        keyboard = InlineKeyboardBuilder()
        keyboard.button(text="🔙 Назад", callback_data="current_activations")
        keyboard.adjust(1)
    
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Активация успешно завершена.",
            state=state,
            reply_markup=keyboard.as_markup()
        )
    else:
        logger.error(f"Не удалось завершить активацию. Ответ: {result}")
        await safe_edit_or_send_message(
            message=callback_query.message,
            new_text="Не удалось завершить активацию. Попробуйте снова.",
            state=state,
            reply_markup=callback_query.message.reply_markup
        )
    

    async def poll_for_sms(bot: Bot, user_id: int, chat_id: int, activation_id: str, smshub_api: SmsHubAPI): activations = user_activations.get(user_id, {}) activation = activations.get(activation_id)

    if not activation:
        logger.error(f"Активация {activation_id} не найдена для пользователя {user_id}.")
        return
    
    try:
        max_wait_time = 300
        poll_interval = 3
        elapsed_time = 0
    
        while elapsed_time < max_wait_time:
            await asyncio.sleep(poll_interval)
            elapsed_time += poll_interval
    
            status_response = await smshub_api.get_status(activation_id)
            if not status_response:
                logger.error("Нет ответа при запросе статуса активации.")
                await bot.send_message(chat_id, "Не удалось получить статус активации. Попробуйте позже.")
                return
    
            status_parts = status_response.split(":", 1)
            status = status_parts[0]
    
            if status == "STATUS_WAIT_CODE":
                logger.debug(f"Ожидание SMS кода для активации {activation_id}.")
                activation['last_update'] = time.time()
                continue
            elif status.startswith("STATUS_WAIT_RETRY"):
                last_code = status_parts[1] if len(status_parts) > 1 else "нет предыдущего кода"
                logger.info(f"Ожидание повторного SMS кода, последний код: {last_code}")
                activation['status'] = f'Ожидание повторного SMS (последний код: {last_code})'
                activation['last_update'] = time.time()
                continue
            elif status == "STATUS_CANCEL":
                await bot.send_message(chat_id, "Активация была отменена.")
                activation['status'] = 'Активация отменена'
                return
            elif status == "STATUS_OK":
                code = status_parts[1] if len(status_parts) > 1 else "Код не получен"
                logger.info(f"Получен код активации для {activation_id}: {code}")
                activation['status'] = f'Код получен: {code}'
                activation['last_update'] = time.time()
    
                # Создаем инлайн-клавиатуру
                keyboard = InlineKeyboardBuilder()
                keyboard.button(text="📂 Текущие активации", callback_data="current_activations")
                keyboard.button(text="✅ Завершить активацию", callback_data=f"complete_activation:{activation_id}")
                keyboard.adjust(1)
    
                # Удаляем предыдущее сообщение, чтобы с новыми появилось уведомление
                previous_message_id = activation.get("message_id")
                await safe_delete_message(bot, chat_id, previous_message_id)
    
                # Отправляем новое сообщение
                sent_message = await bot.send_message(
                    chat_id=chat_id,
                    text=f"Код активации для номера `{activation['number']}`: `{code}`",
                    reply_markup=keyboard.as_markup(),
                    parse_mode="Markdown"
                )
                activation['message_id'] = sent_message.message_id
    
                return
            else:
                logger.error(f"Непредвиденный статус активации: {status_response}")
                activation['status'] = f'Неизвестный статус: {status}'
                await bot.send_message(chat_id, f"Неизвестный статус активации: {status}")
                return
    except asyncio.CancelledError:
        logger.info(f"Задача poll_for_sms для активации {activation_id} была отменена.")
    except Exception as e:
        logger.error(f"Ошибка в poll_for_sms: {e}")
        activation['status'] = 'Ошибка при получении SMS'
        await bot.send_message(chat_id, "Произошла ошибка при получении SMS.")
    

    def register_activation_handlers(dp: Dispatcher): dp.callback_query.register(current_activations_handler, F.data == "current_activations") dp.callback_query.register(manage_activation_handler, F.data.startswith("manage_activation")) dp.callback_query.register(cancel_activation_handler, F.data.startswith("cancel_activation")) dp.callback_query.register(request_another_sms_handler, F.data.startswith("request_another_sms")) dp.callback_query.register(complete_activation_handler, F.data.startswith("complete_activation"))

  4. Assistant

    This code appears to be a part of a Telegram bot implementation using the aiogram library. It manages user activations, allowing users to perform various actions related to SMS activation processes, including checking current activations, managing individual activations, requesting additional SMS codes, canceling activations, and completing them.

    Let's break down the main components and functionality of this code:

    Key Components

    1. Imports and Dependencies:

      • The code imports necessary modules from aiogram for working with Telegram bots.
      • It also imports custom utilities and constants presumably defined in other parts of the application.
    2. Global Variables:

      • user_activations: A dictionary to store active user activations, indexed by user ID.
    3. Handlers:

      • Various async functions act as handlers for different callback queries (like button presses) made by users.
      • Each handler performs specific actions based on the current status of user activations.

    Handlers Breakdown

    • current_activations_handler:

      • Responds to a request for the current activations of a user.
      • If no activations are found, it sends a message informing the user.
      • If activations exist, it builds a reply markup with information about each activation.
    • manage_activation_handler:

      • Manages an individual activation based on the activation ID provided in the callback data.
      • Shows the status and options to complete or cancel the activation.
    • cancel_activation_handler:

      • Cancels the specified activation through the external API and updates the user's activation list.
    • request_another_sms_handler:

      • Requests another SMS code for a specified activation.
      • If successful, it starts polling for the code.
    • complete_activation_handler:

      • Finalizes the activation process and updates the activation's status accordingly.
    • poll_for_sms:

      • A background task that periodically checks for an incoming SMS code.
      • Depending on the status returned by the API, it updates the user about the activation process, or informs them of errors.

    Keyboard and Message Management

    • The code uses InlineKeyboardBuilder to create inline keyboards that allow users to navigate between different functionalities easily.
    • The safe_edit_or_send_message and safe_delete_message functions (presumably defined elsewhere) are used for safely managing Telegram messages, ensuring that users see the most relevant and up-to-date information.

    Registration of Handlers

    • The register_activation_handlers function binds the defined handlers to the dispatcher. Each handler is linked to specific callback data patterns, allowing it to respond appropriately when users interact with the bot.

    Observations and Recommendations

    • Logging: The implementation includes logging for various operations, providing valuable insights for debugging and operational monitoring.
    • Error Handling: The code includes error handling for network/API responses, suggesting a robust approach to managing issues that may arise during execution.
    • Async Handling: The use of async functions ensures that the bot can handle multiple users and requests simultaneously, which is crucial for a responsive bot experience.

    This bot setup is a good example of how to handle asynchronous processes in a real-world application, particularly in a field like SMS-based activations.