я высылаю все текущие хендлеры моего телеграм чат бота, ты можешь для меня полносттью перераотать весь код и прислать исправленный вариант добавив и изменив все с использованием aiogram-dialog. полный код! без сокращений!!! полностю переарботай его весь, если тебе не хватит токенов для ответа, то я тебе потом напишу и попрошу продолжить, пиши максимум, без скоращений, чтоыбы был полный код, без единого скоращений, чтобы я скоприровал к себе и вставил и запустил, без всяких доработок:
bot/handlers/init.py
from aiogram import Dispatcher
from .start import register_start_handlers
from .settings import register_settings_handlers
from .balance import register_balance_handlers
from .sms import register_sms_handlers
from .activation import register_activation_handlers
from .errors import register_error_handlers
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.services import SERVICE_DISPLAY_NAMES
import logging
from aiogram import Dispatcher, types, F
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.fsm.context import FSMContext
from datetime import datetime
from ..data import get_user_api_key
from ..api import SmsHubAPI
from ..utils import get_usd_to_rub_rate, safe_edit_or_send_message
logger = logging.getLogger(name)
async def balance_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)
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
smshub_api = SmsHubAPI(user_api_key)
logger.info(f"Пользователь {callback_query.from_user.id} запросил баланс.")
balance_response = await smshub_api.get_balance()
usd_to_rub_rate = await get_usd_to_rub_rate()
if balance_response and balance_response.startswith("ACCESS_BALANCE:"):
balance_usd = float(balance_response.split(":")[1])
balance_rub = balance_usd * usd_to_rub_rate if usd_to_rub_rate else "недоступно"
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message_text = (
f"Ваш баланс на {current_time}:\n"
f"`{balance_usd:.4f}`$ (приблизительно `{balance_rub:.2f}`₽)"
)
keyboard = InlineKeyboardBuilder()
keyboard.button(text="🔄 Обновить баланс", callback_data="check_balance")
keyboard.button(text="🔙 Вернуться в меню", callback_data="back_to_main_menu")
keyboard.adjust(1)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=message_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
else:
logger.error(f"Не удалось получить баланс. Ответ: {balance_response}")
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Не удалось получить баланс. Попробуйте снова.",
state=state,
reply_markup=callback_query.message.reply_markup
)
import logging
from aiogram import Dispatcher, types
logger = logging.getLogger(name)
async def errors_handler(update: types.Update, exception: Exception):
logger.exception(f"Исключение в обработчике: {exception}")
# Может быть логика отправки уведомления о недоступности
return True # Возвращаем True, чтобы обозначить, что ошибка обработана
import logging
from aiogram import Dispatcher, types, F
from aiogram.fsm.context import FSMContext
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.fsm.state import State, StatesGroup
from ..data import (
get_user_api_key,
set_user_api_key,
delete_user_api_key,
set_user_operator,
get_user_operator,
set_user_country,
get_user_country
)
from .start import send_main_menu
from ..api import SmsHubAPI
from ..utils import get_usd_to_rub_rate, safe_edit_or_send_message
from ..constants.operators import OPERATOR_DISPLAY_NAMES
from ..constants.countries import COUNTRIES
from ..constants.country_operator import COUNTRY_OPERATORS
logger = logging.getLogger(name)
class UserSettings(StatesGroup):
entering_api_key = State()
class OperatorSettings(StatesGroup):
selecting_operator = State()
class CountrySettings(StatesGroup):
selecting_country = State()
class DeleteApiKeyConfirmation(StatesGroup):
waiting_for_confirmation = State()
async def settings_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
await show_settings_menu(callback_query, state)
keyboard = InlineKeyboardBuilder()
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")
keyboard.button(text="📡 Изменить оператора", callback_data="edit_operator")
keyboard.button(text=f"{flag_emoji} Изменить страну", callback_data="edit_country")
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}`\n"
message_text += f"*Текущая страна:* `{country_display_name}`"
sent_message = await safe_edit_or_send_message(
message=callback.message if isinstance(callback, types.CallbackQuery) else callback,
new_text=message_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
if not sent_message:
try:
sent_message = await callback.bot.send_message(
chat_id=user_id,
text=message_text,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
await state.update_data(prompt_message_id=sent_message.message_id)
except Exception as e:
logger.error(f"Не удалось отправить новое меню настроек: {e}")
await state.set_state(None)
async def input_api_key_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
keyboard = InlineKeyboardBuilder()
keyboard.button(text="🔙 Назад", callback_data="cancel_settings")
keyboard.adjust(1)
prompt_text = (
"Введите ваш API ключ для работы с сервисом:\n\n"
"<blockquote expandable>"
"<b>Получение вашего API ключа</b>\n"
"Чтобы начать использовать API, вам нужно получить ваш уникальный API ключ. Следуйте этим шагам:\n"
"1. Перейдите по <a href=\"tg://user?id=123456789\">ссылке на настройки SMSHUB</a>.\n"
"2. Найдите кнопку \"Сгенерировать новый ключ\" и нажмите на неё.\n"
"3. Ваша почта, на которую был зарегистрирован аккаунт, получит сообщение с вашим новым API ключом.\n"
"4. Скопируйте ключ из письма.\n"
"</blockquote>\n"
"<blockquote expandable>"
"<b>Ввод вашего API ключа</b>\n"
"После получения ключа, вы можете ввести его в нашем боте. Для этого выполните следующие действия:\n"
"1. Откройте интерфейс бота, выберите меню настроек.\n"
"2. Нажмите на кнопку \"➕ Добавить API ключ\", чтобы начать процесс.\n"
"3. Когда бот запросит, вставьте ваш API ключ в текстовое поле.\n"
"4. Нажмите \"Отправить\".\n\n"
"Ваш ключ будет проверен, и если он корректен, бот сохранит его для дальнейшего использования.\n"
"</blockquote>\n"
"<blockquote expandable>"
"<b>Информация о безопасности</b>\n"
"Не забывайте, что ваш API ключ должен оставаться конфиденциальным. Никому не сообщайте его, чтобы избежать несанкционированного доступа к вашим данным и услугам.\n"
"</blockquote>"
)
await safe_edit_or_send_message(
message=callback_query.message,
new_text=prompt_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="HTML",
disable_web_page_preview=True
)
await state.set_state(UserSettings.entering_api_key)
async def delete_user_api_key_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
keyboard = InlineKeyboardBuilder()
keyboard.button(text="✅ Да", callback_data="confirm_delete_api_key")
keyboard.button(text="❌ Нет", callback_data="cancel_delete_api_key")
keyboard.adjust(2)
confirmation_text = "⚠️ Вы действительно хотите удалить ваш API ключ?"
await safe_edit_or_send_message(
message=callback_query.message,
new_text=confirmation_text,
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
await state.set_state(DeleteApiKeyConfirmation.waiting_for_confirmation)
async def confirm_delete_api_key_handler(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
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.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:
# Append a red circle emoji if the service does not have available numbers
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: # Only show navigation buttons if more than one page exists
nav_buttons = []
if page_number > 0:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"service_page:{page_number - 1}"))
# Centralize page number information
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:
numbers_status = await smshub_api.get_numbers_status(country=user_country_code)
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, 0, 0
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=data.get('message'),
new_text=progress_text,
state=state,
reply_markup=keyboard.as_markup()
)
await asyncio.sleep(5)
if last_exception:
logger.error(f"Ошибка при запросе всех сервисов: {last_exception}")
return None, 0, 0
return available_services, 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, total_services_with_numbers, total_services_for_country = await fetch_all_services(user_api_key, user_country_code, state)
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)
if available_services is None:
await send_main_menu(callback_query.message, state)
return
smshub_api = SmsHubAPI(user_api_key)
numbers_status = await smshub_api.get_numbers_status(country=user_country_code, operator=user_operator)
services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
services_with_operator = len(services_with_numbers) # Количество сервисов с учетом настроек оператора
keyboard = build_service_keyboard(page_number=0, available_services=available_services, services_with_numbers=services_with_numbers)
message_text = get_service_message_text(total_services_with_numbers, total_services_for_country, 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)
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} отменил операцию.")
await state.update_data(cancel_request=True)
data = await state.get_data()
current_task = data.get('current_task')
if current_task:
current_task.cancel()
# Обновите актуальные данные здесь
available_services = data.get('available_services', [])
total_services_with_numbers = data.get('total_services_with_numbers', len(available_services))
total_services_for_country = data.get('total_services_for_country', len(available_services))
country_name = data.get('country_name', 'Неизвестно')
operator_name = data.get('operator_name', 'Любой')
smshub_api = SmsHubAPI(get_user_api_key(callback_query.from_user.id))
numbers_status = await smshub_api.get_numbers_status(country=get_user_country(callback_query.from_user.id), operator=get_user_operator(callback_query.from_user.id))
services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
services_with_operator = len(services_with_numbers) # Количество сервисов с учетом настроек оператора
keyboard = build_service_keyboard(page_number=0, available_services=available_services, services_with_numbers=services_with_numbers)
message_text = get_service_message_text(total_services_with_numbers, total_services_for_country, 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)
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_handler(message: types.Message, state: FSMContext, user_id: Optional[int] = None):
try:
await message.delete()
except Exception as e:
logger.error(f"Не удалось удалить сообщение пользователя: {e}")
user_input = message.text.strip().lower()
if user_id is None:
user_id = message.from_user.id
logger.info(f"Пользователь {user_id} ввел сервис: {user_input}")
data = await state.get_data()
available_services = data.get('available_services', [])
smshub_api = SmsHubAPI(get_user_api_key(user_id))
numbers_status = await smshub_api.get_numbers_status(country=get_user_country(user_id), operator=get_user_operator(user_id))
services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
matched_services = [
(code, name) for code, name in SERVICE_DISPLAY_NAMES.items()
if code in available_services and (user_input in name.lower() or user_input == code.lower())
]
if matched_services:
pages = get_service_pages(matched_services)
page_number = 0
keyboard = build_page_keyboard(pages, page_number, services_with_numbers)
await state.update_data(matched_services=matched_services)
await safe_edit_or_send_message(
message=message,
new_text="Пожалуйста, выберите один из представленных сервисов:\n_🔴 - нет номеров_",
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
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()
)
for code, name in current_page:
# Append a red circle emoji if the service does not have available numbers
if code not in services_with_numbers:
name += " 🔴"
keyboard.button(text=name, callback_data=f"service_select:{code}")
keyboard.adjust(3)
if len(service_pages) > 1: # Only show navigation buttons if more than one page exists
nav_buttons = []
if page_number > 0:
nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"search_page:{page_number - 1}"))
# Centralize page number information
nav_buttons.append(types.InlineKeyboardButton(text=f"Страница {page_number + 1}/{len(service_pages)}", callback_data="ignore"))
if page_number < len(service_pages) - 1:
nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперед", callback_data=f"search_page:{page_number + 1}"))
keyboard.row(*nav_buttons)
keyboard.row(types.InlineKeyboardButton(text="🔙 Назад к сервисам", callback_data="service_page:0"))
return keyboard
async def handle_search_page_navigation(callback_query: types.CallbackQuery, state: FSMContext):
try:
await callback_query.answer()
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
page_number = int(callback_query.data.split(":")[1])
data = await state.get_data()
matched_services = data.get('matched_services', [])
smshub_api = SmsHubAPI(get_user_api_key(callback_query.from_user.id))
numbers_status = await smshub_api.get_numbers_status(country=get_user_country(callback_query.from_user.id), operator=get_user_operator(callback_query.from_user.id))
services_with_numbers = {service.split('_')[0] for service, count in numbers_status.items() if int(count) > 0}
pages = get_service_pages(matched_services)
keyboard = build_page_keyboard(pages, page_number, services_with_numbers)
await safe_edit_or_send_message(
message=callback_query.message,
new_text="Пожалуйста, выберите один из представленных сервисов:\n_🔴 - нет номеров_",
state=state,
reply_markup=keyboard.as_markup(),
parse_mode="Markdown"
)
max_attempts = 3
last_exception = None
try:
for attempt in range(1, max_attempts + 1):
data = await state.get_data()
if data.get("cancel_request"):
logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен.")
return
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"
if data.get("cancel_request"):
logger.info(f"Запрос на получение номера для пользователя {user_id} был отменен перед выполнением.")
return
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()
keyboard.button(text="Назад", callback_data="service_page:0")
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")
await asyncio.sleep(5)
except asyncio.CancelledError:
logger.info(f"Задача для пользователя {user_id} была отменена.")
return
if last_exception and last_exception != "NO_NUMBERS":
keyboard = InlineKeyboardBuilder()
keyboard.button(text="Назад", callback_data="service_page:0")
await safe_edit_or_send_message(
message=message,
new_text=f"Произошла ошибка при обработке запроса: {last_exception}. Попробуйте снова.",
state=state,
reply_markup=keyboard.as_markup()
)
Add a handler for the "ignore" callback to silently ignore it
async def ignore_callback_handler(callback_query: types.CallbackQuery):
try:
await callback_query.answer() # Just answer to confirm the action
except Exception as e:
logger.warning(f"Не удалось ответить на callback_query: {e}")
import logging
from aiogram import Dispatcher, types
from aiogram.filters import Command
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.fsm.context import FSMContext
from ..data import set_user_operator, get_user_operator
from ..utils import safe_delete_message, safe_edit_or_send_message
try:
await safe_delete_message(message.bot, message.chat.id, message.message_id)
except Exception as e:
logger.error(f"Ошибка при удалении сообщения с командой /start: {e}")
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)