так, смотри, у меня есть телеграм бот для получения и отправки смс, я добавил кнопки для выбора сервиса перед покупкой смс, но если я ввоу вручную, то все в порядке, к примеру я пишу сервис "ya" и бот дальше работает и я вижу: Доступно номеров: 6210
Оператор: Мегафон
Текущие цены для сервиса ya:
от 0.0194 (₽1.87)до0.0573 (₽5.51).
Введите максимальную стоимость в $ (например, 10):
но если я нажимаю на кнопку Яндекс, то я вижу в консоли ошибку:
Duration 398 ms by bot id=7625597085
2024-10-08 12:33:41,900 - bot.handlers - INFO - User 389669884 selected service via button: vk
2024-10-08 12:33:41,901 - root - INFO - Запрос цен для сервиса: vk, страна: 0, в алюта: 643
2024-10-08 12:33:41,902 - bot.handlers - ERROR - Error retrieving data for servi ce 'vk': Invalid variable type: value should be str, int or float, got None of t ype <class 'NoneType'>
2024-10-08 12:33:42,007 - bot.handlers - INFO - User 389669884 returned to the m ain menu.
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 # Your user_id to receive notifications
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"
code
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, state: FSMContext):
data = await state.get_data()
service = data.get('service')
if not service:
# Handle the case where service is not set
return
code
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)
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
# Get the number of available numbers for the service and operator
numbers_status = await smshub_api.get_numbers_status(country=country_code, operator=user_operator)
if not numbers_status:
await message.answer("Не удалось получить информацию о доступных номерах. Попробуйте снова позже.")
await state.clear()
await send_main_menu(message, state)
return
# Keys in numbers_status have the format "<service_code>_<forwarding_flag>"
service_key = f"{service}_0"
available_numbers = int(numbers_status.get(service_key, 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.error(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
code
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
Судя по вашему описанию и предоставленному логам ошибки, проблема возникает, когда вы выбираете сервис через кнопку, а при вводе вручную всё работает корректно. Ошибка, которую вы получаете:
code
Error retrieving data for service 'vk': Invalid variable type: value should be str, int or float, got None of type <class 'NoneType'>
Это говорит о том, что где-то в коде происходит попытка использовать значение None, где ожидается строка, целое или вещественное число.
Причина проблемы:
Изучив ваш код, вероятнее всего, проблема возникает в функции process_service_selection в этой строке:
Если numbers_status.get(service_key, 0) возвращает None, то int(None) вызовет ошибку, так как int() не может принять значение None.
Это может произойти, если numbers_status содержит значение None для ключа service_key, или если ключ присутствует, но его значение None. Это объясняет, почему при вводе сервиса вручную всё работает (может быть, для сервиса ya данные есть), а при выборе сервиса через кнопку появляется ошибка (для сервиса vk данных может не быть, или значение None).
Как исправить:
Чтобы избежать этой ошибки, нужно убедиться, что мы не передаём в int() значение None. Для этого можно изменить строку так, чтобы при получении None подставлялось значение 0. Вот как можно это сделать:
python
available_numbers = int(numbers_status.get(service_key) or 0)
Добавив or 0, мы гарантируем, что если numbers_status.get(service_key) вернёт None, то вместо него будет использовано значение 0. Таким образом, int(0) спокойно отработает и не вызовет ошибку.
Обновлённый код функции:
python
# ...
# Получаем количество доступных номеров для сервиса и оператора
numbers_status = await smshub_api.get_numbers_status(country=country_code, operator=user_operator)
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"
# Здесь добавляем or 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
# ...
Рекомендуемые действия:
Измените строку, как указано выше.
Добавьте логирование значения numbers_status и service_key перед этой строкой, чтобы убедиться, что вы получаете ожидаемые данные:
Убедитесь, что ваш SmsHubAPI клиент правильно обрабатывает запросы и не возвращает None там, где не должен.
Дополнительные замечания:
Возможно, что для некоторых сервисов (например, vk) API возвращает None или пустые данные, что приводит к этой ошибке. Убедитесь, что сервисы, которые вы выбираете с помощью кнопок, действительно доступны и корректно обрабатываются вашим API клиентом.
Также стоит проверить, что данные, которые вы получаете из методов API, соответствуют ожидаемым форматам и не содержат None там, где ожидается число или строка.
Заключение:
Ошибка возникает из-за попытки преобразовать значение None в int. Исправление строки с использованием or 0 должно решить проблему. Если после этого проблема сохраняется, стоит дополнительно отладить код и проверить данные, которые вы получаете из API.
Если у вас будут дополнительные вопросы или сложности, пожалуйста, дайте знать, и я постараюсь помочь более подробно.