так, мсотри, я теб высылаю полностью код моего бота в телеграм для работы с сервисом smshub для покупки вирутального мобилнього номера и полученяи на него смс и офоциальную документацию по этому сервису через апи, сейчас у меня проблема заключается в том, что все работает, но покупка номера не учиывает выбор оператора, который мы задаем в настройках, т.е. к примеру я выбрал оператра Билайн, а номер будет покупаться я так понимаю для any, то бишь для любьгго оператора, помоги мне исправить проблему и пришли мне готовый исправленный код полнотью для тех компоненртов, где это нужно
def load_data():
"""Загружает данные из JSON файла."""
global user_data
with lock:
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, "r", encoding="utf-8") as file:
user_data = json.load(file)
logger.info("Данные пользователей успешно загружены.")
except json.JSONDecodeError:
user_data = {}
logger.warning("Не удалось декодировать JSON из файла. Используем пустые данные.")
else:
user_data = {}
logger.info("Файл данных не найден. Используем пустые данные.")
Вызываем load_data() при импорте модуля
load_data()
def save_data():
"""Сохраняет текущие данные в JSON файл."""
with lock:
with open(DATA_FILE, "w", encoding="utf-8") as file:
json.dump(user_data, file, ensure_ascii=False, indent=4)
logger.info("Данные пользователей успешно сохранены.")
Методы для работы с API ключами
def set_user_api_key(user_id, api_key):
"""Сохраняет API ключ для конкретного пользователя."""
with lock:
user = user_data.get(str(user_id), {})
user["api_key"] = api_key
user_data[str(user_id)] = user
save_data()
logger.info(f"API ключ для пользователя {user_id} сохранён.")
def get_user_api_key(user_id):
"""Возвращает API ключ для конкретного пользователя, если он сохранен."""
with lock:
return user_data.get(str(user_id), {}).get("api_key")
def delete_user_api_key(user_id):
"""Удаляет API ключ для конкретного пользователя."""
with lock:
user = user_data.get(str(user_id), {})
if "api_key" in user:
del user["api_key"]
if not user:
del user_data[str(user_id)]
save_data()
logger.info(f"API ключ для пользователя {user_id} удалён.")
else:
logger.warning(f"У пользователя {user_id} нет API ключа для удаления.")
Методы для работы с оператором
def set_user_operator(user_id, operator):
"""Сохраняет выбранный оператор для конкретного пользователя."""
with lock:
user = user_data.get(str(user_id), {})
user["operator"] = operator
user_data[str(user_id)] = user
save_data()
logger.info(f"Оператор '{operator}' для пользователя {user_id} сохранён.")
def get_user_operator(user_id):
"""Возвращает выбранный оператор для конкретного пользователя, если он сохранен."""
with lock:
return user_data.get(str(user_id), {}).get("operator")
def delete_user_operator(user_id):
"""Удаляет выбранный оператор для конкретного пользователя."""
with lock:
user = user_data.get(str(user_id), {})
if "operator" in user:
del user["operator"]
if not user:
del user_data[str(user_id)]
save_data()
logger.info(f"Оператор для пользователя {user_id} удалён.")
else:
logger.warning(f"У пользователя {user_id} нет оператора для удаления.")
handlers.py
import asyncio
import logging
import time
from datetime import datetime
from typing import Optional, Dict
import aiohttp
from aiogram import Bot, Dispatcher, Router, types, F
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup
from aiogram.utils.markdown import bold, italic
from aiogram.utils.keyboard import InlineKeyboardBuilder
from .data import (
get_user_api_key,
set_user_api_key,
delete_user_api_key,
set_user_operator,
get_user_operator
)
from .api import SmsHubAPI
from .helpers import build_services_keyboard
from .services import SERVICES
ADMIN_USER_ID = 389669884 # Ваш user_id для получения уведомлений
async def get_usd_to_rub_rate() -> Optional[float]:
"""Get the current USD to RUB exchange rate with caching."""
global _cached_usd_to_rub_rate, _cached_usd_to_rub_rate_time
now = time.time()
if _cached_usd_to_rub_rate and (now - _cached_usd_to_rub_rate_time < USD_TO_RUB_RATE_TTL):
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
return rate
else:
logger.error("RUB rate not found in response.")
return None
except Exception as e:
logger.error(f"Error fetching exchange rate: {e}")
return None
class UserSettings(StatesGroup):
entering_api_key = State()
class SmsOrderState(StatesGroup):
waiting_for_service = State()
waiting_for_max_price = State()
class OperatorSettings(StatesGroup):
selecting_operator = State()
Helper function for safe message editing or sending
async def safe_edit_or_send_message(message: types.Message, new_text: str, state: FSMContext, reply_markup=None, parse_mode=None):
try:
await message.edit_text(new_text, reply_markup=reply_markup, parse_mode=parse_mode)
# Save the message_id of the edited message
await state.update_data(last_message_id=message.message_id)
except Exception as e:
logger.error(f"Failed to edit message: {e}")
# If editing failed, delete the previous bot message
data = await state.get_data()
last_message_id = data.get('last_message_id')
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"Failed to delete message: {del_exc}")
# Send a new message and save its message_id
sent_message = await message.answer(new_text, reply_markup=reply_markup, parse_mode=parse_mode)
await state.update_data(last_message_id=sent_message.message_id)
@router.message(Command('start'))
async def start_handler(message: types.Message, state: FSMContext):
logger.info(f"User {message.from_user.id} started the bot.")
# Set operator to "any" by default if not set
user_operator = get_user_operator(message.from_user.id)
if not user_operator:
set_user_operator(message.from_user.id, "any")
await send_main_menu(message, state)
async def send_main_menu(message: types.Message, state: FSMContext):
logger.info(f"User {message.chat.id} returned to the main menu.")
keyboard = InlineKeyboardBuilder()
keyboard.button(text="💰 Проверить баланс", callback_data="check_balance")
keyboard.button(text="📲 Получить SMS", callback_data="get_sms")
keyboard.button(text="📋 Текущие активации", callback_data="current_activations")
keyboard.button(text="⚙️ Настройки", callback_data="settings")
keyboard.adjust(1)
async def show_settings_menu(callback_query: types.CallbackQuery, state: FSMContext, user_id: int):
user_api_key = get_user_api_key(user_id)
user_operator = get_user_operator(user_id)
if not user_operator:
# Set operator to "any" by default if not set
set_user_operator(user_id, "any")
user_operator = "any"
operator_display_name = OPERATOR_DISPLAY_NAMES.get(user_operator, user_operator)
keyboard = InlineKeyboardBuilder()
# API key settings
if user_api_key:
keyboard.button(text="✏️ Изменить API ключ", callback_data="edit_api_key")
keyboard.button(text="❌ Удалить API ключ", callback_data="delete_api_key")
else:
keyboard.button(text="➕ Добавить API ключ", callback_data="add_api_key")
# Operator settings
keyboard.button(text="✏️ Изменить оператора", callback_data="edit_operator")
keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
keyboard.adjust(1)
message_text = (
f"Ваш текущий API ключ: `{user_api_key}`\n" if user_api_key else "API ключ не настроен.\n"
)
message_text += (
f"Текущий оператор: `{operator_display_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.clear()
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Введите ваш API ключ для работы с сервисом:",
state=state,
reply_markup=keyboard.as_markup()
)
await state.set_state(UserSettings.entering_api_key)
@router.callback_query(F.data == "delete_api_key")
async def delete_user_api_key_handler(callback_query: types.CallbackQuery, state: FSMContext):
await callback_query.answer()
logger.info(f"User {callback_query.from_user.id} requested API key deletion.")
try:
delete_user_api_key(callback_query.from_user.id)
await safe_edit_or_send_message(
message=callback_query.message,
new_text="API ключ успешно удалён.",
state=state
)
await send_main_menu(callback_query.message, state)
await state.clear()
except Exception as e:
logger.exception(f"Error deleting API key: {e}")
await callback_query.message.answer("Не удалось удалить API ключ. Попробуйте снова.")
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Пожалуйста, сначала настройте ваш API ключ в разделе 'Настройки'.",
state=state,
reply_markup=keyboard.as_markup()
)
return
logger.info(f"User {callback_query.from_user.id} started the process of obtaining a number.")
# Send the services keyboard starting from page 0
keyboard = build_services_keyboard(page_number=0)
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Выберите сервис для получения номера или введите код сервиса вручную:",
state=state,
reply_markup=keyboard,
parse_mode="Markdown"
)
await state.update_data(current_services_page=0)
await state.set_state(SmsOrderState.waiting_for_service)
async def process_service_selection(message_or_callback, service, state: FSMContext):
logger.debug(f"Processing service code: {repr(service)}")
if not service:
# Handle the case where service is not set
return
if isinstance(message_or_callback, types.Message):
user = message_or_callback.from_user
message = message_or_callback
elif isinstance(message_or_callback, types.CallbackQuery):
user = message_or_callback.from_user
message = message_or_callback.message
else:
logger.error("Unknown message_or_callback type.")
return
user_api_key = get_user_api_key(user.id)
logger.debug(f"user.id: {user.id}, user_api_key: {user_api_key}")
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 message.answer(
"Пожалуйста, сначала настройте ваш API ключ в разделе 'Настройки'.",
reply_markup=keyboard.as_markup()
)
return
user_operator = get_user_operator(user.id) or "any"
smshub_api = SmsHubAPI(user_api_key)
country_code = "0"
usd_to_rub_rate = await get_usd_to_rub_rate()
try:
# Check if service is valid
service_codes = [s['code'] for s in SERVICES]
if service not in service_codes:
keyboard = InlineKeyboardBuilder()
keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
keyboard.adjust(1)
await message.answer(
f"Сервис '{service}' не найден. Пожалуйста, выберите сервис из списка или введите корректный код.",
reply_markup=keyboard.as_markup()
)
return
# Get prices for the service (without filtering by operator)
price_info = await smshub_api.get_price_for_service(service, country=country_code)
if not price_info:
await message.answer("Сервис недоступен. Пожалуйста, попробуйте снова.")
await state.clear()
await send_main_menu(message, state)
return
logger.debug(f"price_info: {price_info}")
# Получаем количество доступных номеров для сервиса и оператора
operator_param = None if user_operator == "any" else user_operator
numbers_status = await smshub_api.get_numbers_status(country=country_code, operator=operator_param)
if not numbers_status:
await message.answer("Не удалось получить информацию о доступных номерах. Попробуйте снова позже.")
await state.clear()
await send_main_menu(message, state)
return
# Ключи в numbers_status имеют формат "<service_code>_<forwarding_flag>"
service_key = f"{service}_0"
available_numbers = int(numbers_status.get(service_key) or 0)
if available_numbers == 0:
await message.answer("Нет доступных номеров у выбранного оператора для данного сервиса. Пожалуйста, выберите другого оператора или попробуйте позже.")
await state.clear()
await send_main_menu(message, state)
return
# Get the list of prices from price_info
prices = [float(price_str) for price_str in price_info.keys()]
min_price_usd = min(prices)
max_price_usd = max(prices)
min_price_rub = min_price_usd * usd_to_rub_rate if usd_to_rub_rate else 0
max_price_rub = max_price_usd * usd_to_rub_rate if usd_to_rub_rate else 0
keyboard = InlineKeyboardBuilder()
keyboard.button(text="❌ Отмена", callback_data="cancel_operation")
keyboard.adjust(1)
operator_display = OPERATOR_DISPLAY_NAMES.get(user_operator, user_operator)
if operator_display.lower() == "любой оператор":
operator_display = "любой оператор" # Lowercase for better text appearance
# Before sending a new message, delete the previous bot message
data = await state.get_data()
last_message_id = data.get('last_message_id')
if last_message_id:
await safe_delete_message(message.bot, message.chat.id, last_message_id)
# Formulate the message using Markdown formatting
message_text = (
f"{bold('Доступно номеров:')} {available_numbers}\n"
f"{bold('Оператор:')} {operator_display}\n"
f"{bold('Текущие цены для сервиса')} {service}:\n"
f"от `{min_price_usd:.4f}` $ (₽{min_price_rub:.2f}) до `{max_price_usd:.4f}` $ (₽{max_price_rub:.2f}).\n\n"
f"{italic('Введите максимальную стоимость в $ (например, 10):')}"
)
# Send a new message and save its message_id
sent_message = await message.answer(
message_text,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
await state.update_data(last_message_id=sent_message.message_id)
# Save data for later use
await state.update_data(
service=service,
min_price=min_price_usd,
max_price=max_price_usd,
min_price_rub=min_price_rub,
max_price_rub=max_price_rub
)
await state.set_state(SmsOrderState.waiting_for_max_price)
except Exception as e:
logger.exception(f"Error retrieving data for service '{service}': {e}")
await message.answer("Произошла ошибка при обработке запроса. Попробуйте снова.")
await state.clear()
await send_main_menu(message, state)
activations = user_activations.get(user_id, {})
activation = activations.get(activation_id)
if activation:
# Cancel task if exists
task = activation.get('task')
if task:
task.cancel()
# Cancel activation on API side
result = await smshub_api.cancel_activation(activation_id)
logger.info(f"Activation {activation_id} canceled on API side: {result}")
# Remove activation from the list
del activations[activation_id]
# Create new keyboard with "🔙 Назад" button
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
)
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":
# Cancel task if exists
task = activation.get('task')
if task:
task.cancel()
# Remove activation from the list
del activations[activation_id]
# Create new keyboard with "🔙 Назад" button
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"Failed to complete activation. Response: {result}")
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Не удалось завершить активацию. Попробуйте снова.",
state=state,
reply_markup=callback_query.message.reply_markup
)
if not activation:
logger.error(f"Activation {activation_id} not found for user {user_id}.")
return
try:
max_wait_time = 300 # Maximum wait time in seconds
poll_interval = 3 # Polling interval in seconds
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("No response when requesting activation status.")
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"Waiting for SMS code for activation {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"Waiting for retry SMS code, last code: {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"Received activation code for {activation_id}: {code}")
activation['status'] = f'Код получен: {code}'
activation['last_update'] = time.time()
await bot.send_message(
chat_id,
f"Код активации для номера `{activation['number']}`: `{code}`",
parse_mode="Markdown"
)
return
else:
logger.error(f"Unexpected activation status: {status_response}")
activation['status'] = f'Неизвестный статус: {status}'
await bot.send_message(chat_id, f"Неизвестный статус активации: {status}")
return
# If wait time has expired, function ends without changing activation status
except asyncio.CancelledError:
logger.info(f"Task poll_for_sms for activation {activation_id} was cancelled.")
except Exception as e:
logger.error(f"Error in poll_for_sms: {e}")
activation['status'] = 'Ошибка при получении SMS'
await bot.send_message(chat_id, "Произошла ошибка при получении SMS.")
Background task to periodically check activation statuses
async def check_activations_status():
while True:
await asyncio.sleep(300) # Check every 5 minutes
logger.info("Checking statuses of active activations...")
for user_id, activations in user_activations.copy().items():
for activation_id, activation in activations.copy().items():
try:
user_api_key = get_user_api_key(user_id)
if not user_api_key:
continue
smshub_api = SmsHubAPI(user_api_key)
status_response = await smshub_api.get_status(activation_id)
if not status_response:
continue
status_parts = status_response.split(":", 1)
status = status_parts[0]
if status == "STATUS_CANCEL":
# Remove activation
logger.info(f"Activation {activation_id} was cancelled on the service side.")
task = activation.get('task')
if task:
task.cancel()
del activations[activation_id]
elif activation['status'].startswith("Код получен"):
# Check if enough time has passed
elapsed_since_update = time.time() - activation.get('last_update', 0)
if elapsed_since_update > 1800: # 30 minutes
logger.info(f"Activation {activation_id} completed after time expired.")
task = activation.get('task')
if task:
task.cancel()
del activations[activation_id]
except Exception as e:
logger.error(f"Error checking activation {activation_id}: {e}")
Function to start background tasks when bot starts
Проблема заключается в том, что коды операторов, которые вы используете в боте, не соответствуют кодам операторов, ожидаемым API сервиса smshub.org. В результате ваш бот не правильно передает оператор при покупке номера, и API воспринимает это как запрос на любой оператор.
Решение:
Обновить коды операторов в соответствии с требованиями API smshub.org.
Убедиться, что выбранный оператор правильно передается при вызове метода get_number.
Шаги по исправлению:
Обновим словарь OPERATOR_CODES и OPERATOR_DISPLAY_NAMES в handlers.py или вынесем их в отдельный файл.
Согласно документации smshub.org, коды операторов для России имеют числовые значения:
Обновим функцию max_price_handler в handlers.py для правильной передачи кода оператора.
Замените часть кода следующим образом:
@router.message(SmsOrderState.waiting_for_max_price)
async def max_price_handler(message: types.Message, state: FSMContext):
max_price_input = message.text.strip()
logger.info(f"User {message.from_user.id} specified maximum price: {max_price_input}")
try:
max_price = float(max_price_input)
except ValueError:
# Обработка ошибки
pass
user_data = await state.get_data()
service = user_data['service']
user_api_key = get_user_api_key(message.from_user.id)
smshub_api = SmsHubAPI(user_api_key)
country_code = "0" # Код страны для России
user_operator_code = get_user_operator(message.from_user.id) or "any"
operator_param = None if user_operator_code == "any" else user_operator_code
result = await smshub_api.get_number(service, country=country_code, max_price=max_price, operator=operator_param)
# Дальнейшая обработка
Изменим метод get_number в api.py, чтобы правильно передавать параметр оператора.
В файле api.py замените условие добавления оператора в параметры запроса:
async def get_number(self, service, country="0", operator=None, max_price=None):
logging.debug(f"Requesting number for service: {service}, country: {country}, operator: {operator}, max price: {max_price}, currency: 643")
params = {
"api_key": self.api_key,
"action": "getNumber",
"service": service,
"country": country,
"currency": "643"
}
if operator:
params["operator"] = operator
if max_price:
params["maxPrice"] = max_price
# Остальной код функции
Теперь параметр оператора будет всегда передаваться, если он установлен, даже если это "any" или код конкретного оператора.
Проверьте работу бота.
После внесения этих изменений, запустите бота и проверьте покупку номера с выбранным оператором. Убедитесь, что номер приобретается для выбранного оператора, а не для "any".
Обновленный код для handlers.py (фрагмент):
# Добавьте эти словари в начало файла handlers.py или вынесите их в отдельный файл
OPERATOR_CODES = {
"any": None,
"1": "Билайн",
"2": "Мегафон",
"3": "МТС",
"4": "Теле2",
"6": "Йота",
# Добавьте остальные операторы с их кодами
}
OPERATOR_DISPLAY_NAMES = {
"any": "Любой оператор",
"1": "Билайн",
"2": "Мегафон",
"3": "МТС",
"4": "Теле2",
"6": "Йота",
# Добавьте остальные операторы
}
# Обновите функцию выбора оператора
@router.callback_query(F.data == "edit_operator")
async def select_operator_handler(callback_query: types.CallbackQuery, state: FSMContext):
await callback_query.answer()
operator_codes = list(OPERATOR_DISPLAY_NAMES.keys())
# Создаем клавиатуру с операторами
keyboard = InlineKeyboardBuilder()
for op_code in operator_codes:
display_name = OPERATOR_DISPLAY_NAMES.get(op_code, op_code)
keyboard.button(text=display_name, callback_data=f"operator:{op_code}")
keyboard.button(text="❌ Отмена", callback_data="cancel_operator_selection")
keyboard.adjust(2) # Устанавливаем 2 столбца
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Выберите оператора из списка:",
state=state,
reply_markup=keyboard.as_markup()
)
await state.set_state(OperatorSettings.selecting_operator)
@router.callback_query(OperatorSettings.selecting_operator, F.data.startswith("operator:"))
async def operator_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
await callback_query.answer()
operator_code = callback_query.data.split(":")[1]
set_user_operator(callback_query.from_user.id, operator_code)
display_name = OPERATOR_DISPLAY_NAMES.get(operator_code, operator_code)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=f"Вы выбрали оператора: {display_name}",
state=state
)
await state.clear()
# Возвращаем пользователя в меню настроек
await show_settings_menu(callback_query, state, callback_query.from_user.id)
# Обновите функцию обработки максимальной цены
@router.message(SmsOrderState.waiting_for_max_price)
async def max_price_handler(message: types.Message, state: FSMContext):
max_price_input = message.text.strip()
logger.info(f"User {message.from_user.id} specified maximum price: {max_price_input}")
try:
max_price = float(max_price_input)
except ValueError:
# Обработка ошибки
pass
user_data = await state.get_data()
service = user_data['service']
user_api_key = get_user_api_key(message.from_user.id)
smshub_api = SmsHubAPI(user_api_key)
country_code = "0" # Код страны для России
user_operator_code = get_user_operator(message.from_user.id) or "any"
operator_param = None if user_operator_code == "any" else user_operator_code
result = await smshub_api.get_number(service, country=country_code, max_price=max_price, operator=operator_param)
# Дальнейшая обработка
Обновленный код для api.py:
async def get_number(self, service, country="0", operator=None, max_price=None):
logging.debug(f"Requesting number for service: {service}, country: {country}, operator: {operator}, max price: {max_price}, currency: 643")
params = {
"api_key": self.api_key,
"action": "getNumber",
"service": service,
"country": country,
"currency": "643"
}
if operator:
params["operator"] = operator
if max_price:
params["maxPrice"] = max_price
async with aiohttp.ClientSession() as session:
async with session.get(BASE_URL, params=params) as response:
text = await response.text()
if response.status == 200:
logging.info(f"Ответ номера: {text}")
return text
else:
logging.error(f"Ошибка при запросе номера: {response.status}, ответ: {text}")
return None
Заключение:
После этих изменений ваш бот будет корректно учитывать выбранного оператора при покупке номера через API smshub.org. Убедитесь, что коды операторов соответствуют тем, которые принимает API. Если у вас есть доступ к документации smshub.org с актуальными кодами операторов, обновите словарь OPERATOR_CODES в соответствии с ней.