Nov 15 21:59:22 vps1707806210 systemd[1]: Started My SMS Bot Service.
Nov 15 21:59:25 vps1707806210 python[14554]: Traceback (most recent call last):
Nov 15 21:59:25 vps1707806210 python[14554]: File "/root/smstest/main.py", line 37, in
Nov 15 21:59:25 vps1707806210 python[14554]: asyncio.run(main())
Nov 15 21:59:25 vps1707806210 python[14554]: File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
Nov 15 21:59:25 vps1707806210 python[14554]: return loop.run_until_complete(main)
Nov 15 21:59:25 vps1707806210 python[14554]: File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
Nov 15 21:59:25 vps1707806210 python[14554]: return future.result()
Nov 15 21:59:25 vps1707806210 python[14554]: File "/root/smstest/main.py", line 25, in main
Nov 15 21:59:25 vps1707806210 python[14554]: register_handlers(dp)
Nov 15 21:59:25 vps1707806210 python[14554]: File "/root/smstest/bot/handlers/init.py", line 16, in register_handlers
Nov 15 21:59:25 vps1707806210 python[14554]: register_sms_handlers(dp)
Nov 15 21:59:25 vps1707806210 python[14554]: File "/root/smstest/bot/handlers/sms.py", line 760, in register_sms_handlers
Nov 15 21:59:25 vps1707806210 python[14554]: dp.callback_query.register(handle_search_page_navigation, F.data.startswith("search_page:"))
Nov 15 21:59:25 vps1707806210 python[14554]: NameError: name 'handle_search_page_navigation' is not defined
Nov 15 21:59:26 vps1707806210 systemd[1]: my_smsbottest.service: Main process exited, code=exited, status=1/FAILURE
Nov 15 21:59:26 vps1707806210 systemd[1]: my_smsbottest.service: Failed with result 'exit-code'.
Nov 15 21:59:26 vps1707806210 systemd[1]: my_smsbottest.service: Consumed 4.096s CPU time.
Nov 15 21:59:26 vps1707806210 systemd[1]: my_smsbottest.service: Scheduled restart job, restart counter is at 5.
Nov 15 21:59:26 vps1707806210 systemd[1]: Stopped My SMS Bot Service.
Nov 15 21:59:26 vps1707806210 systemd[1]: my_smsbottest.service: Consumed 4.096s CPU time.
Nov 15 21:59:26 vps1707806210 systemd[1]: Started My SMS Bot Service.
import asyncio
import logging
import time
import json
from pathlib import Path
from typing import Optional, List, Tuple, Set
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.operators import OPERATOR_DISPLAY_NAMES
from ..constants.countries import COUNTRIES
from ..constants.services import 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]
for code, name in current_page:
# Добавляем красный круг, если у сервиса нет доступных номеров
if code not in services_with_numbers:
name += " 🔴"
keyboard.button(text=name, callback_data=f"service_select:{code}")
keyboard.adjust(3)
if len(services_pages) > 1: # Показываем кнопки навигации только если страниц больше одной
nav_buttons = []
if page_number > 0:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"service_page:{page_number - 1}"))
# Центрируем информацию о номере страницы
nav_buttons.append(types.InlineKeyboardButton(text=f"Страница {page_number + 1}/{len(services_pages)}", callback_data="ignore"))
if page_number < len(services_pages) - 1:
nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"service_page:{page_number + 1}"))
keyboard.row(*nav_buttons)
# Оставляем кнопку "🔙 Назад в меню" неизменной
keyboard.row(types.InlineKeyboardButton(text="🔙 Назад в меню", callback_data="back_to_main_menu"))
return keyboard
def get_service_message_text(total_services_with_numbers: int, total_services_for_country: int, services_with_operator: int, country_name: str, operator_name: str) -> str:
return (
f"🔢 Общее кол-во сервисов:{total_services_for_country}\n"
f"💼 Доступные сервисы (где есть номера):{total_services_with_numbers}\n"
f"✅ Доступные сервисы (с вашими настройками оператора):{services_with_operator}\n\n"
f"— Нажмите на кнопку, чтобы выбрать сервис.\n"
f"— Или введите название, чтобы найти сервис.\n\n"
f"🐾 Текущая страна:{country_name}\n"
f"📡 Текущий оператор:{operator_name}\n"
f"(Эти параметры можно изменить в настройках)\n"
f"\n_🔴 - нет номеров_"
)
for attempt in range(1, max_attempts + 1):
try:
# Получаем текущие данные из состояния
data = await state.get_data()
message = data.get('message')
# Отправляем прогресс-сообщение
progress_text = f"Идет запрос списка сервисов {attempt}/{max_attempts}..."
keyboard = InlineKeyboardBuilder()
keyboard.button(text="❌ Отмена", callback_data="cancel_operation") # Оставляем "Отмена" кнопкой здесь
keyboard.adjust(1)
await safe_edit_or_send_message(
message=message,
new_text=progress_text,
state=state,
reply_markup=keyboard.as_markup()
)
# Выполняем запрос к API с указанным оператором
numbers_status = await smshub_api.get_numbers_status(country=user_country_code, operator=user_operator)
if numbers_status:
# Все сервисы и сервисы с доступными номерами
available_services = [service.split('_')[0] for service in numbers_status.keys()]
services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
break
except Exception as e:
last_exception = e
logger.error(f"Ошибка при запросе статуса всех сервисов, попытка {attempt}: {e}")
data = await state.get_data()
if data.get("cancel_request"):
logger.info("Запрос на получение всех сервисов был отменен.")
return None, set(), 0, 0
await asyncio.sleep(5)
if last_exception:
logger.error(f"Ошибка при запросе всех сервисов: {last_exception}")
return None, set(), 0, 0
# Сохраняем numbers_status в состоянии для дальнейшего использования
await state.update_data(numbers_status=numbers_status)
return available_services, services_with_numbers, len(services_with_numbers), len(available_services)
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}")
user_api_key = get_user_api_key(callback_query.from_user.id)
user_country_code = get_user_country(callback_query.from_user.id) or "0"
user_operator = get_user_operator(callback_query.from_user.id) or "any"
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} начал процесс получения номера.")
await state.update_data(message=callback_query.message, cancel_request=False)
available_services, services_with_numbers, total_services_with_numbers, total_services_for_country = await fetch_all_services(
user_api_key, user_country_code, user_operator, state
)
if available_services is None:
await send_main_menu(callback_query.message, state)
return
country_name = COUNTRIES.get(user_country_code, 'Неизвестно')
operator_name = OPERATOR_DISPLAY_NAMES.get(user_operator, 'Любой')
await state.update_data(
total_services_with_numbers=total_services_with_numbers,
total_services_for_country=total_services_for_country,
country_name=country_name,
operator_name=operator_name
)
services_with_operator = services_with_numbers # Теперь это множество
# Сортируем и разделяем на страницы
sorted_services = get_sorted_services(available_services)
services_pages = get_service_pages(sorted_services)
keyboard = build_service_keyboard(page_number=0, services_pages=services_pages, services_with_numbers=services_with_operator)
message_text = get_service_message_text(
total_services_with_numbers,
total_services_for_country,
len(services_with_operator),
country_name,
operator_name
)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=message_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
await state.set_state(SmsOrderState.waiting_for_service)
await state.update_data(
available_services=available_services,
services_pages=services_pages, # Сохраняем страницы для навигации
services_with_numbers=services_with_operator,
current_page=0 # Сохраняем текущую страницу
)
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} отменил операцию.")
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} вернулся в главное меню.")
max_attempts = 3
last_exception = None
data = await state.get_data()
numbers_status = data.get('numbers_status', {})
available_numbers = user_data.get('available_numbers', 0)
for attempt in range(1, max_attempts + 1):
if data.get("cancel_request"):
logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен.")
return
try:
progress_text = f"Идет запрос на получение номера {attempt}/{max_attempts}..."
keyboard = InlineKeyboardBuilder()
# Здесь оставляем "❌ Отмена" как раньше, так как это статусное сообщение
keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
keyboard.adjust(1)
await safe_edit_or_send_message(
message=message,
new_text=progress_text,
state=state,
reply_markup=keyboard.as_markup()
)
user_operator = get_user_operator(user_id) or "any"
# Используем кэшированные данные `numbers_status` вместо повторного запроса
result = await smshub_api.get_number(service, country=user_country_code, max_price=max_price, operator=user_operator)
if data.get("cancel_request"):
logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен.")
return
if result and result.startswith("ACCESS_NUMBER"):
_, activation_id, number = result.split(":")
logger.info(f"Пользователь {user_id} получил номер: {number}, активация ID: {activation_id}")
if user_id not in user_activations:
user_activations[user_id] = {}
user_activations[user_id][activation_id] = {
'number': number,
'status': 'Ожидание SMS',
'service': service,
'service_display': service_display,
'country_name': country_name,
'last_update': time.time(),
'task': None
}
keyboard = InlineKeyboardBuilder()
keyboard.button(text="📂 Текущие активации", callback_data="current_activations")
keyboard.button(text="❌ Отменить активацию", callback_data=f"cancel_activation:{activation_id}")
keyboard.button(text="🔙 Главное меню", callback_data="back_to_main_menu")
keyboard.adjust(1)
message_text = (
f"*Получен номер:* `{number}`\n"
f"*Страна:* `{country_name}`\n"
f"*Оператор:* `{operator_display}`\n"
f"*Сервис:* `{service_display}`\n"
f"*Максимальная стоимость:* `{max_price:.2f}` $ (₽{max_price * user_data['usd_to_rub_rate']:.2f})\n"
f"*Статус:* *Ожидание SMS*\n"
f"Вы можете управлять активацией или вернуться в главное меню."
)
sent_message = await safe_edit_or_send_message(
message=message,
new_text=message_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
user_activations[user_id][activation_id]['message_id'] = sent_message.message_id
await state.set_state(None)
task = asyncio.create_task(poll_for_sms(
bot=message.bot,
user_id=user_id,
chat_id=message.chat.id,
activation_id=activation_id,
smshub_api=smshub_api
))
user_activations[user_id][activation_id]['task'] = task
return
elif result == "NO_NUMBERS":
logger.info(f"Попытка {attempt} из {max_attempts}: нет доступных номеров.")
last_exception = result
if attempt == max_attempts:
suggestion = (
"Попробуйте выбрать 'Любой оператор' в настройках или увеличить максимальную цену."
if user_operator != "any" else
"Попробуйте увеличить максимальную цену или повторите попытку позже."
)
keyboard = InlineKeyboardBuilder()
# Заменяем "❌ Отмена" на "🔙 Назад", возвращаясь на текущую страницу
current_page = data.get('current_page', 0)
keyboard.button(text="🔙 Назад", callback_data=f"service_page:{current_page}")
await safe_edit_or_send_message(
message=message,
new_text=f"Нет доступных номеров для оператора {operator_display} по данной цене.\n{suggestion}",
state=state,
reply_markup=keyboard.as_markup()
)
return
else:
raise Exception("Неожиданный ответ API")
except Exception as e:
logger.error(f"Ошибка при получении номера для сервиса '{service_code}', попытка {attempt}: {e}")
last_exception = e
await asyncio.sleep(5)
if last_exception and last_exception != "NO_NUMBERS":
data = await state.get_data()
current_page = data.get('current_page', 0)
keyboard = InlineKeyboardBuilder()
# Заменяем "❌ Отмена" на "🔙 Назад", возвращаясь на текущую страницу
keyboard.button(text="🔙 Назад", callback_data=f"service_page:{current_page}")
await safe_edit_or_send_message(
message=message,
new_text=f"Произошла ошибка при обработке запроса: {last_exception}. Попробуйте снова.",
state=state,
reply_markup=keyboard.as_markup()
)
Добавляем обработчик для колбэка "ignore" чтобы игнорировать его
async def ignore_callback_handler(callback_query: types.CallbackQuery):
try:
await callback_query.answer() # Просто отвечаем, чтобы подтвердить действие
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
The error you're encountering is due to the handle_search_page_navigation function being referenced in your register_sms_handlers function but not being defined anywhere in your code. This causes a NameError when the service attempts to start.
Error Details:
NameError: name 'handle_search_page_navigation' is not defined
This error points to the following line in your register_sms_handlers function:
Option 1: Define the handle_search_page_navigation Function
If handle_search_page_navigation is intended to handle specific callback queries related to search page navigation, you should define this function with the appropriate logic. Here's a basic template to get you started:
async def handle_search_page_navigation(callback_query: types.CallbackQuery, state: FSMContext):
"""
Handles navigation between search result pages.
Args:
callback_query (types.CallbackQuery): The callback query from the user.
state (FSMContext): The current state of the conversation.
"""
try:
await callback_query.answer() # Acknowledge the callback to remove the loading state
# Extract the page number from the callback data
page_number_str = callback_query.data.split(":")[1]
try:
page_number = int(page_number_str)
except ValueError:
await callback_query.message.reply("Некорректный номер страницы.")
return
# Retrieve current search results from the state
data = await state.get_data()
search_results_pages = data.get('search_results_pages', [])
if 0 <= page_number < len(search_results_pages):
current_page = search_results_pages[page_number]
# Build your keyboard for the new page
keyboard = build_search_result_keyboard(page_number, search_results_pages)
# Update the message with the new page of search results
await callback_query.message.edit_text(
text=f"Результаты поиска - Страница {page_number + 1}/{len(search_results_pages)}",
reply_markup=keyboard.as_markup()
)
await state.update_data(current_page=page_number)
else:
await callback_query.message.reply("Страница не найдена.")
except Exception as e:
logger.error(f"Ошибка при навигации по страницам поиска: {e}")
await callback_query.message.reply("Произошла ошибка при обработке запроса.")
def build_search_result_keyboard(page_number: int, search_results_pages: List[List[Tuple[str, str]]]) -> InlineKeyboardBuilder:
"""
Builds an inline keyboard for search result pagination.
Args:
page_number (int): The current page number.
search_results_pages (List[List[Tuple[str, str]]]): The paginated search results.
Returns:
InlineKeyboardBuilder: The constructed inline keyboard.
"""
keyboard = InlineKeyboardBuilder()
# Add your search result buttons here
for result in search_results_pages[page_number]:
keyboard.button(text=result[1], callback_data=f"select_search_result:{result[0]}")
# Add pagination buttons
nav_buttons = []
if page_number > 0:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"search_page:{page_number - 1}"))
if page_number < len(search_results_pages) - 1:
nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"search_page:{page_number + 1}"))
if nav_buttons:
keyboard.row(*nav_buttons)
# Add a button to return to the main menu
keyboard.row(types.InlineKeyboardButton(text="🔙 Главное меню", callback_data="back_to_main_menu"))
return keyboard
Explanation:
Function Definition: The handle_search_page_navigation function handles callback queries that start with "search_page:".
Callback Data Parsing: It extracts the page number from the callback data.
State Management: Retrieves the current search results from the FSMContext state.
Keyboard Building: Uses a helper function build_search_result_keyboard to create an inline keyboard for the new page.
Error Handling: Provides feedback if the page number is invalid or if an error occurs during processing.
Registration:
Ensure that this function is correctly registered in your register_sms_handlers function:
Option 2: Remove or Comment Out the Registration Line
If the search page navigation functionality is not needed or not yet implemented, you can temporarily remove or comment out the line that registers the handle_search_page_navigation handler. This will prevent the NameError from occurring.
Caution: Ensure that no part of your application relies on this handler before removing it. If it is required for certain functionalities, it's better to implement it as shown in Option 1.
Final Recommendations:
Determine Intent: Decide whether the handle_search_page_navigation function is needed based on your application's requirements.
Implement If Needed: If navigation through search pages is a required feature, implement the handler as per Option 1.
Remove If Unnecessary: If this functionality is not required, safely remove or comment out the registration line to eliminate the error.
Consistent Naming: Ensure that all handlers and their registrations are named consistently to avoid similar errors in the future.
Testing: After making the changes, restart your service and monitor the logs to ensure that the NameError no longer appears and that your bot functions as expected.
By addressing the missing handle_search_page_navigation function through one of the above options, your My SMS Bot Service should start without encountering the NameError.