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 .start import send_main_menu
from ..constants import SERVICE_DISPLAY_NAMES
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}")
Assistant
User
ты модешь прислать мне готовые исправленные коды?
Assistant
Я понимаю ваше желание получить исправленный код, но без полного контекста всей программы и того, как вы вызываете функции, будет трудно предоставить точное решение. Однако, я могу предложить улучшения и советы по коду, который вы предоставили.
import asyncio
import logging
import time
import json
from pathlib import Path
from typing import Optional, List, Tuple
from aiogram import Dispatcher, types, F
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
Импорт дополнительных модулей
from ..data import get_user_api_key, get_user_operator, get_user_country
from ..api import SmsHubAPI
from ..utils import get_usd_to_rub_rate, safe_edit_or_send_message
from .start import send_main_menu
from .activation import user_activations, poll_for_sms
from ..constants import OPERATOR_DISPLAY_NAMES, COUNTRIES, SERVICE_DISPLAY_NAMES
logger = logging.getLogger(name)
class SmsOrderState(StatesGroup):
waiting_for_service = State()
waiting_for_max_price = State()
if page_number < len(services_pages):
current_page = services_pages[page_number]
# Добавляет кнопки сервисов в сетке 3x6
for code, name in current_page:
keyboard.button(text=name, callback_data=f"service_select:{code}")
# Настраивает кнопки навигации
if page_number == 0:
# Первая страница - только кнопка "Вперед"
keyboard.adjust(3) # Устраиваем сервисные кнопки в 3 столбца
keyboard.row(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"service_page:{page_number + 1}"))
elif page_number == len(services_pages) - 1:
# Последняя страница - только кнопка "Назад"
keyboard.adjust(3)
keyboard.row(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"service_page:{page_number - 1}"))
else:
# Промежуточные страницы - кнопки "Назад" и "Вперед"
keyboard.adjust(3)
keyboard.row(
types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"service_page:{page_number - 1}"),
types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"service_page:{page_number + 1}")
)
# Кнопка "Назад в меню" на всех страницах
keyboard.row(types.InlineKeyboardButton(text="🔙 Назад в меню", callback_data="back_to_main_menu"))
return keyboard
async def get_sms_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
code
user_api_key = get_user_api_key(callback_query.from_user.id)
if not user_api_key:
keyboard = InlineKeyboardBuilder()
keyboard.button(text="⚙️ Настройки", callback_data="settings")
keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
keyboard.adjust(1)
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Пожалуйста, сначала настройте ваш API ключ в разделе 'Настройки'.",
state=state,
reply_markup=keyboard.as_markup()
)
return
logger.info(f"Пользователь {callback_query.from_user.id} начал процесс получения номера.")
keyboard = build_service_keyboard()
await state.update_data(cancel_request=False, current_task=None)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=(
"Выберите сервис, нажав на кнопку ниже.\n"
"Если вы хотите, вы также можете ввести полное название сервиса или хотя бы часть его названия, чтобы получить результаты поиска."
),
state=state,
reply_markup=keyboard.as_markup()
)
await state.set_state(SmsOrderState.waiting_for_service)
async def go_back_to_service_selection(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
logger.info(f"Пользователь {callback_query.from_user.id} отменил операцию.")
code
await state.update_data(cancel_request=True)
data = await state.get_data()
current_task = data.get('current_task')
if current_task:
current_task.cancel()
keyboard = build_service_keyboard()
await safe_edit_or_send_message(
message=callback_query.message,
new_text=(
"Выберите сервис, нажав на кнопку ниже.\n"
"Если вы хотите, вы также можете ввести полное название сервиса или хотя бы часть его названия, чтобы получить результаты поиска."
),
state=state,
reply_markup=keyboard.as_markup()
)
await state.update_data(cancel_request=False)
await state.set_state(SmsOrderState.waiting_for_service)
async def back_to_main_menu(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
logger.info(f"Пользователь {callback_query.from_user.id} вернулся в главное меню.")
async def service_page_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
code
page_number = int(callback_query.data.split(":")[1])
keyboard = build_service_keyboard(page_number)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=(
"Выберите сервис, нажав на кнопку ниже.\n"
"Если вы хотите, вы также можете ввести полное название сервиса или хотя бы часть его названия, чтобы получить результаты поиска."
),
state=state,
reply_markup=keyboard.as_markup()
)
async def service_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
async def service_handler(message: types.Message, state: FSMContext, service_code: Optional[str] = None, user_id: Optional[int] = None):
try:
await message.delete()
except Exception as e:
logger.error(f"Не удалось удалить сообщение пользователя: {e}")
code
user_input = message.text.strip().lower()
if user_id is None:
user_id = message.from_user.id
logger.info(f"Пользователь {user_id} ввел сервис: {user_input}")
service_code = next((code for code, name in SERVICE_DISPLAY_NAMES.items() if name.lower() == user_input or code.lower() == user_input), None)
if service_code is None:
matched_services = [(code, name) for code, name in SERVICE_DISPLAY_NAMES.items() if user_input in name.lower()]
if matched_services:
keyboard = InlineKeyboardBuilder()
for code, name in matched_services:
keyboard.button(text=name, callback_data=f"service_select:{code}")
keyboard.adjust(3)
keyboard.button(text="🔙 Назад", callback_data="service_page:0")
await safe_edit_or_send_message(
message=message,
new_text="Пожалуйста, выберите один из представленных сервисов:",
state=state,
reply_markup=keyboard.as_markup()
)
return
else:
keyboard = InlineKeyboardBuilder()
keyboard.button(text="🔙 Назад к сервисам", callback_data="service_page:0")
await safe_edit_or_send_message(
message=message,
new_text="Сервис не найден. Попробуйте ввести код или полное название сервиса.",
state=state,
reply_markup=keyboard.as_markup()
)
return
else:
await state.update_data(selected_service=service_code, cancel_request=False)
task = asyncio.create_task(service_handler_logic(message, state, user_id=user_id, service_code=service_code))
await state.update_data(current_task=task)
import logging
import time
import aiohttp
from aiogram import Bot, types
from aiogram.exceptions import TelegramBadRequest
from aiogram.fsm.context import FSMContext
from aiogram import Dispatcher
from typing import Optional
async def get_usd_to_rub_rate() -> Optional[float]:
global _cached_usd_to_rub_rate, _cached_usd_to_rub_rate_time
now = time.time()
code
# Используем кэш, если данные актуальны
if _cached_usd_to_rub_rate and (now - _cached_usd_to_rub_rate_time < USD_TO_RUB_RATE_TTL):
logger.info("Возврат курса из кэша")
return _cached_usd_to_rub_rate
# Получение данных о курсе валют
try:
async with aiohttp.ClientSession() as session:
async with session.get(EXCHANGE_RATE_API_URL) as response:
data = await response.json()
rate = data.get('rates', {}).get('RUB')
if rate:
_cached_usd_to_rub_rate = rate
_cached_usd_to_rub_rate_time = now
logger.info(f"Курс RUB обновлен: {rate}")
return rate
else:
logger.error("Курс RUB не найден в ответе.")
return None
except Exception as e:
logger.error(f"Ошибка при запросе курса валют: {e}")
return None
new_reply_markup = kwargs.get("reply_markup")
# Проверяем на необходимость редактирования
if last_message_id and (last_message_text != new_text or last_reply_markup != new_reply_markup):
try:
sent_message = await message.bot.edit_message_text(
new_text,
chat_id=message.chat.id,
message_id=last_message_id,
**kwargs
)
await state.update_data(last_message_text=new_text, last_reply_markup=new_reply_markup)
return sent_message
except TelegramBadRequest as e:
if "message can't be edited" in str(e).lower():
logger.warning(f"Сообщение не может быть отредактировано: {e}. Пробуем отправить новое сообщение.")
else:
logger.error(f"Ошибка при редактировании сообщения: {e}")
except Exception as e:
logger.exception(f"Неожиданная ошибка при редактировании сообщения: {e}")
# Удаляем старое сообщение при необходимости
if last_message_id:
try:
await message.bot.delete_message(chat_id=message.chat.id, message_id=last_message_id)
except Exception as del_exc:
logger.error(f"Не удалось удалить сообщение: {del_exc}")
# Отправляем новое сообщение
try:
sent_message = await message.answer(new_text, **kwargs)
await state.update_data(
last_message_id=sent_message.message_id,
last_message_text=new_text,
last_reply_markup=new_reply_markup
)
return sent_message
except Exception as e:
logger.error(f"Не удалось отправить новое сообщение: {e}")
return None
async def on_startup(dispatcher: Dispatcher):
logger.info("Бот успешно запущен.")
Oct 20 13:42:29 vps1707806210 python[14628]: 2024-10-20 13:42:29,193 - bot.api - INFO - Запрос статуса для активации: 720073199
Oct 20 13:42:29 vps1707806210 python[14628]: 2024-10-20 13:42:29,381 - bot.api - INFO - Ответ статуса: STATUS_OK:1609
Oct 20 13:42:29 vps1707806210 python[14628]: 2024-10-20 13:42:29,381 - bot.handlers.activation - INFO - Получен код активации для 720073199: 1609
Oct 20 13:42:29 vps1707806210 python[14628]: 2024-10-20 13:42:29,383 - bot.handlers.activation - ERROR - Ошибка в poll_for_sms: 'NoneType' object has no attribute 'get_d ata'
^C
root@vps1707806210:~# ^C
The error message you're encountering, ERROR - Ошибка в poll_for_sms: 'NoneType' object has no attribute 'get_data', suggests that there was an attempt to call the get_data method on a NoneType object, which likely means that a None was passed where a state management context object was expected.
In the context of the poll_for_sms function, it seems like FSMContext or a similar state management object, which is supposed to be used to manage the state of the conversation, might not have been properly initialized or passed to the function.
Here's how you can further investigate and potentially fix the issue:
Check if FSMContext is correctly initialized and passed:
Since FSMContext is used to maintain state information, you need to ensure that every time you attempt to access state data, the context object is initialized. This usually happens within the framework of the aiogram dispatcher or within handlers.
If you're calling poll_for_sms independently and it requires state information, ensure you're properly passing the FSMContext.
Review how tasks are handled:
Within the poll_for_sms function, see if you're handling state parameters correctly. The error suggests a missing state or context.
Ensure any asynchronous functions interacting with state have FSMContext correctly passed to them, especially if these functions are run as tasks (like with asyncio.create_task).
Verify event loop management:
Functions running independently (as tasks) need proper context for executing async operations. Check if the main function correctly sets up and manages the event loop.
Null Check before Access:
Before accessing any method on a potentially nullable object, add a null check to prevent such errors:
python
if state is not None:
await state.get_data()
Logs for Debugging:
Add detailed logging before crucial sections where states are being handled or passed. Sometimes, you get more context around what's None.
Check dependencies:
Ensure all dependencies and versions work harmoniously. A mismatch, especially with event frameworks, can lead to unexpected behavior, especially when managing states.
If you've verified these things and ensured proper context management, it should help address the 'NoneType' object has no attribute 'get_data' error. Let me know if there are more details about how poll_for_sms is invoked or managed, as nuances in asynchronous handling might bring additional insights.
Вот некоторые изменения и проверки, которые вы можете сделать:
Проверка на наличие FSMContext: Убедитесь, что FSMContext (или другой объект состояния) правильно передается и используется в poll_for_sms. Пример с улучшенной проверкой:
python
async def poll_for_sms(bot: Bot, user_id: int, chat_id: int, activation_id: str, smshub_api: SmsHubAPI, state: FSMContext):
if state is None:
logger.error(f"State context is missing for activation {activation_id}.")
return
activations = user_activations.get(user_id, {})
activation = activations.get(activation_id)
if not activation:
logger.error(f"Aktivatsiya {activation_id} ne naydena dlya pol'zovatelya {user_id}.")
return
# Остальная часть кода...
Передача FSMContext в poll_for_sms: Убедитесь, что poll_for_sms вызывается с параметром state, если он необходим:
Логирование ошибок: Добавьте более подробное логирование в ключевые точки, где используется объект state:
python
async def safe_edit_or_send_message(
message: types.Message,
new_text: str,
state: FSMContext,
**kwargs
) -> Optional[types.Message]:
if state is None:
logger.error("No FSMContext provided.")
return None
data = await state.get_data()
# Остальная часть кода...
Исправление ошибок при вызовах API: Проверьте код на наличие вызовов, где объект может быть None, и добавьте проверки перед их использованием.
Эти изменения помогут сделать ваш код более надежным и предотвратить ошибки, связанные с NoneType. Если требуется дополнительная помощь, пожалуйста, предоставьте больше контекста или расскажите, где возникают сложности.
Спасибо за предоставленный код. Давайте посмотрим на возможную причину ошибки и как она может быть устранята в контексте вашего кода.
Проблема
Ошибка 'NoneType' object has no attribute 'get_data' указывает на то, что в какой-то момент объект, на котором вы вызываете get_data, равен None. Это обычно указывает на то, что объект состояния (FSMContext) не был передан корректно.
Возможные исправления
Проверка наличия объекта состояния:
Убедитесь, что во всех местах, где вызывается poll_for_sms, объект state (или другой объект, ожидающий наличия метода get_data) действительно передан.
Обновим функцию poll_for_sms для учета state.
python
async def poll_for_sms(bot: Bot, user_id: int, chat_id: int, activation_id: str, smshub_api: SmsHubAPI, state: FSMContext):
# Проверим наличие state перед его использованием
if not state:
logger.error(f"State is missing for activation {activation_id} and user {user_id}.")
return
activations = user_activations.get(user_id, {})
activation = activations.get(activation_id)
if not activation:
logger.error(f"Aktivatsiya {activation_id} ne naydena dlya pol'zovatelya {user_id}.")
return
try:
# Ожидание SMS
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)
await safe_edit_or_send_message(
message=None,
new_text=f"Код активации для номера `{activation['number']}`: `{code}`",
state=state,
chat_id=chat_id,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown",
bot=bot
)
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.")
Обновление вызова poll_for_sms:
Убедитесь, что при вызове poll_for_sms из других мест в коде, вы передаете объект состояния, если это требует функция.
Этапы тестирования и логирование:
Добавьте логирование перед вызовами функций, чтобы убедиться, что параметры передаются как ожидалось.
С помощью logger.debug можно проследить жизненный цикл получения и передачи состояния в отдельных функциях.
Если после этих шагов ошибка продолжает возникать, это может потребовать более полного аудита, возможно ли где-то еще пропуск параметров или состояния. Если у вас есть дополнительные вопросы или данные для уточнения, пожалуйста, сообщите.