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
import os
import re

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 .main_menu import send_main_menu
from ..api import SmsHubAPI
from ..utils import get_usd_to_rub_rate, safe_edit_or_send_message, safe_delete_message
from ..constants import OPERATOR_DISPLAY_NAMES, COUNTRIES, 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()

ADMIN_USER_ID = int(os.getenv("ADMIN_CHAT_ID", "389669884"))

def escape_markdown(text: str) -> str:
    """Escape special characters for Markdown V2."""
    escape_chars = r"*_[]()~`>#+-=|{}.!"
    return re.sub(f"([{re.escape(escape_chars)}])", r"\\\1", text)

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.message, state, callback_query.from_user.id)

async def show_settings_menu(message: types.Message, state: FSMContext, user_id: int):
    user_api_key = get_user_api_key(user_id)
    user_operator = get_user_operator(user_id) or "any"
    operator_display_name = OPERATOR_DISPLAY_NAMES.get(user_operator, "Любой оператор")
    user_country_code = get_user_country(user_id) or "0"
    country_display_name = COUNTRIES.get(user_country_code, user_country_code)

    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="✏️ Изменить страну", callback_data="edit_country")
    keyboard.button(text="🔙 Назад", callback_data="back_to_main_menu")
    keyboard.adjust(1)

    message_text = (
        f"Ваш текущий API ключ: `{escape_markdown(user_api_key)}`\n" if user_api_key else "API ключ не настроен.\n"
    )
    message_text += f"Текущий оператор: `{escape_markdown(operator_display_name)}`\n"
    message_text += f"Текущая страна: `{escape_markdown(country_display_name)}`"

    await safe_edit_or_send_message(
        message=message,
        new_text=message_text,
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="MarkdownV2"
    )
    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)

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=(
            "Введите ваш API ключ для работы с сервисом:\n\n"
            "*Получение вашего API ключа*\n\n"
            "Чтобы начать использовать API, вам нужно получить ваш уникальный API ключ. Следуйте этим шагам:\n"
            "1. Перейдите по [ссылке на настройки SMSHUB](https://smshub.org/ru/settings).\n"
            "2. Найдите кнопку \"Сгенерировать новый ключ\" и нажмите на неё.\n"
            "3. Ваша почта, на которую был зарегистрирован аккаунт, получит сообщение с вашим новым API ключом.\n"
            "4. Скопируйте ключ из письма.\n\n"
            "*Ввод вашего API ключа*\n\n"
            "После получения ключа, вы можете ввести его в нашем боте. Для этого выполните следующие действия:\n"
            "1. Откройте интерфейс бота, выберите меню настроек.\n"
            "2. Нажмите на кнопку \"➕ Добавить API ключ\", чтобы начать процесс.\n"
            "3. Когда бот запросит, вставьте ваш API ключ в текстовое поле.\n"
            "4. Нажмите \"Отправить\".\n\n"
            "Ваш ключ будет проверен, и если он корректен, бот сохранит его для дальнейшего использования.\n\n"
            "*Информация о безопасности*\n\n"
            "Не забывайте, что ваш API ключ должен оставаться конфиденциальным. Никому не сообщайте его, чтобы избежать несанкционированного доступа к вашим данным и услугам."
        ),
        state=state,
        reply_markup=keyboard.as_markup(),
        parse_mode="Markdown",
        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}")
    logger.info(f"Пользователь {callback_query.from_user.id} запросил удаление API ключа.")
    
    delete_user_api_key(callback_query.from_user.id)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

async def back_to_main_menu_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    await state.set_state(None)
    await send_main_menu(callback_query.message, state)

async def cancel_settings_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    await state.set_state(None)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

async def set_user_api_key_handler(message: types.Message, state: FSMContext):
    user_api_key = message.text.strip()
    logger.info(f"Пользователь {message.from_user.id} ввёл API ключ.")
    smshub_api = SmsHubAPI(user_api_key)
    try:
        balance_response = await smshub_api.get_balance()
        if balance_response and balance_response.startswith("ACCESS_BALANCE:"):
            balance = balance_response.split(":")[1]
            balance_usd = float(balance)
            usd_to_rub_rate = await get_usd_to_rub_rate()
            balance_rub = balance_usd * usd_to_rub_rate if usd_to_rub_rate else "недоступно"

            set_user_api_key(message.from_user.id, user_api_key)

            admin_message = (
                f"Новый API ключ добавлен пользователем.\n\n"
                f"👤 Пользователь: {escape_markdown(message.from_user.full_name)}\n"
                f"🔑 API ключ: `{escape_markdown(user_api_key)}`\n"
                f"🆔 ID пользователя: `{message.from_user.id}`\n"
                f"💬 Юзернейм: @{escape_markdown(message.from_user.username) if message.from_user.username else 'Не указан'}\n"
                f"📍 Язык: `{message.from_user.language_code}`\n"
            )
            await message.bot.send_message(
                chat_id=ADMIN_USER_ID,
                text=admin_message,
                parse_mode="MarkdownV2"
            )

            # Удаляем старое сообщение, чтобы предотвратить двойные ответы
            data = await state.get_data()
            last_message_id = data.get('last_message_id', None)
            if last_message_id:
                try:
                    await safe_delete_message(message.bot, message.chat.id, last_message_id)
                except Exception as e:
                    logger.warning(f"Не удалось удалить предыдущее сообщение: {e}")

            sent_message = await message.answer(
                text=(
                    f"Ваш API ключ успешно сохранён и проверен\!\n"
                    f"Баланс: `{balance_usd:.4f}`\\$ \\(приблизительно `{balance_rub:.2f}`₽\\)"
                ),
                parse_mode="MarkdownV2"
            )
            # Запоминаем ID нового сообщения
            await state.update_data(last_message_id=sent_message.message_id)

            await show_settings_menu(sent_message, state, message.from_user.id)
        else:
            await process_invalid_api_key(message, state)
    except Exception as e:
        logger.error(f"Ошибка при проверке API ключа: {e}")
        await process_invalid_api_key(message, state)

async def process_invalid_api_key(message: types.Message, state: FSMContext):
    keyboard = InlineKeyboardBuilder()
    keyboard.button(text="🔙 Назад", callback_data="cancel_settings")
    keyboard.adjust(1)
    await message.reply(
        "Неверный API ключ. Пожалуйста, попробуйте снова или отмените операцию.",
        reply_markup=keyboard.as_markup()
    )

async def select_operator_handler(callback_query: types.CallbackQuery, state: FSMContext, page: int = 0):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    data = await state.get_data()
    user_country_code = data.get('selected_country_code', '0')

    operator_list = COUNTRY_OPERATORS.get(user_country_code, [])

    if "any" not in operator_list:
        operator_list.insert(0, "any")

    items_per_page = 10

    start = page * items_per_page
    end = start + items_per_page

    keyboard = InlineKeyboardBuilder()

    for op in operator_list[start:end]:
        display_name = OPERATOR_DISPLAY_NAMES.get(op, op)
        keyboard.button(text=display_name, callback_data=f"operator:{op}")
    
    keyboard.adjust(2)

    nav_buttons = []
    if page > 0:
        nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"operator_page:{page - 1}"))
    if end < len(operator_list):
        nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперёд", callback_data=f"operator_page:{page + 1}"))

    if nav_buttons:
        keyboard.row(*nav_buttons)

    keyboard.row(types.InlineKeyboardButton(text="🔙 Назад", callback_data="cancel_operator_selection"))

    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)

async def operator_page_handler(callback_query: types.CallbackQuery, state: FSMContext):
    page = int(callback_query.data.split(':')[1])
    await select_operator_handler(callback_query, state, page)

async def cancel_operator_selection_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    await state.set_state(None)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

async def operator_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    operator = callback_query.data.split(":")[1]
    set_user_operator(callback_query.from_user.id, operator)
    display_name = OPERATOR_DISPLAY_NAMES.get(operator, operator)
    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=f"Вы выбрали оператора: {display_name}",
        state=state
    )
    await state.set_state(None)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

async def select_country_handler(callback_query: types.CallbackQuery, state: FSMContext, page: int = 0):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    countries_list = list(COUNTRIES.items())
    items_per_page = 10

    start = page * items_per_page
    end = start + items_per_page

    keyboard = InlineKeyboardBuilder()

    for country_code, country_name in countries_list[start:end]:
        keyboard.button(text=country_name, callback_data=f"country:{country_code}")

    keyboard.adjust(2)

    nav_buttons = []
    if page > 0:
        nav_buttons.append(types.InlineKeyboardButton(text="⬅️ Назад", callback_data=f"country_page:{page - 1}"))
    if end < len(countries_list):
        nav_buttons.append(types.InlineKeyboardButton(text="➡️ Вперёд", callback_data=f"country_page:{page + 1}"))

    if nav_buttons:
        keyboard.row(*nav_buttons)

    keyboard.row(types.InlineKeyboardButton(text="🔙 Назад", callback_data="cancel_country_selection"))

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text="Выберите страну из списка:",
        state=state,
        reply_markup=keyboard.as_markup()
    )
    await state.set_state(CountrySettings.selecting_country)

async def country_page_handler(callback_query: types.CallbackQuery, state: FSMContext):
    page = int(callback_query.data.split(':')[1])
    await select_country_handler(callback_query, state, page)

async def country_selected_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")

    country_code = callback_query.data.split(":")[1]
    set_user_country(callback_query.from_user.id, country_code)
    country_name = COUNTRIES.get(country_code, country_code)

    await state.update_data(selected_country_code=country_code)

    current_operator = get_user_operator(callback_query.from_user.id) or "any"
    available_operators = COUNTRY_OPERATORS.get(country_code, [])

    if current_operator not in available_operators:
        set_user_operator(callback_query.from_user.id, "any")

    await safe_edit_or_send_message(
        message=callback_query.message,
        new_text=f"Вы выбрали страну: {country_name}",
        state=state
    )
    await state.set_state(None)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

async def cancel_country_selection_handler(callback_query: types.CallbackQuery, state: FSMContext):
    try:
        await callback_query.answer()
    except Exception as e:
        logger.warning(f"Не удалось ответить на callback_query: {e}")
    await state.set_state(None)
    await show_settings_menu(callback_query.message, state, callback_query.from_user.id)

def register_settings_handlers(dp: Dispatcher):
    dp.callback_query.register(settings_handler, F.data == "settings")
    dp.callback_query.register(input_api_key_handler, F.data.in_({"edit_api_key", "add_api_key"}))
    dp.callback_query.register(delete_user_api_key_handler, F.data == "delete_api_key")
    dp.callback_query.register(back_to_main_menu_handler, F.data == "back_to_main_menu")
    dp.callback_query.register(cancel_settings_handler, F.data == "cancel_settings")
    dp.message.register(set_user_api_key_handler, UserSettings.entering_api_key)
    dp.callback_query.register(select_operator_handler, F.data == "edit_operator")
    dp.callback_query.register(cancel_operator_selection_handler, F.data == "cancel_operator_selection")
    dp.callback_query.register(operator_selected_handler, OperatorSettings.selecting_operator, F.data.startswith("operator:"))
    dp.callback_query.register(operator_page_handler, OperatorSettings.selecting_operator, F.data.startswith("operator_page:"))
    dp.callback_query.register(select_country_handler, F.data == "edit_country")
    dp.callback_query.register(country_selected_handler, CountrySettings.selecting_country, F.data.startswith("country:"))
    dp.callback_query.register(cancel_country_selection_handler, F.data == "cancel_country_selection")
    dp.callback_query.register(country_page_handler, CountrySettings.selecting_country, F.data.startswith("country_page:"))







Oct 14 17:51:07 vps1707806210 python[25059]: 2024-10-14 17:51:07,718 - __main__ - INFO - Запуск бота...
Oct 14 17:51:07 vps1707806210 python[25059]: 2024-10-14 17:51:07,719 - bot.utils - INFO - Бот успешно запущен.
Oct 14 17:51:07 vps1707806210 python[25059]: 2024-10-14 17:51:07,719 - aiogram.dispatcher - INFO - Start polling
Oct 14 17:51:07 vps1707806210 python[25059]: 2024-10-14 17:51:07,896 - aiogram.dispatcher - INFO - Run polling for bot @SMSHubApiBot id=7625597085 - 'SMS Hub'
Oct 14 17:51:12 vps1707806210 python[25059]: 2024-10-14 17:51:12,932 - bot.handlers.start - INFO - Пользователь 389669884 запустил бота.
Oct 14 17:51:13 vps1707806210 python[25059]: 2024-10-14 17:51:13,160 - bot.handlers.main_menu - INFO - Пользователь 389669884 вернулся в главное меню.
Oct 14 17:51:13 vps1707806210 python[25059]: 2024-10-14 17:51:13,398 - aiogram.event - INFO - Update id=480220314 is handled. Duration 467 ms by bot id=7625597085
Oct 14 17:51:14 vps1707806210 python[25059]: 2024-10-14 17:51:14,775 - bot.utils - ERROR - Ошибка при редактировании сообщения: Telegram server says - Bad Request: can't parse entities: Character '.' is reserved and must be escaped with the preceding '\'
Oct 14 17:51:15 vps1707806210 python[25059]: 2024-10-14 17:51:15,008 - aiogram.event - INFO - Update id=480220315 is not handled. Duration 704 ms by bot id=7625597085
Oct 14 17:51:15 vps1707806210 python[25059]: 2024-10-14 17:51:15,008 - aiogram.event - ERROR - Cause exception while process update id=480220315 by bot id=7625597085
Oct 14 17:51:15 vps1707806210 python[25059]: TypeError: errors_handler() missing 1 required positional argument: 'exception'
Oct 14 17:51:15 vps1707806210 python[25059]: Traceback (most recent call last):
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/error.py", line 25, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     return await handler(event, data)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/user_context.py", line 56, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     return await handler(event, data)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/fsm/middleware.py", line 42, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     return await handler(event, data)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped_inner(event, kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped()
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 276, in _listen_update
Oct 14 17:51:15 vps1707806210 python[25059]:     return await self.propagate_event(update_type=update_type, event=event, **kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 146, in propagate_event
Oct 14 17:51:15 vps1707806210 python[25059]:     return await observer.wrap_outer_middleware(_wrapped, event=event, data=kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 141, in _wrapped
Oct 14 17:51:15 vps1707806210 python[25059]:     return await self._propagate_event(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 166, in _propagate_event
Oct 14 17:51:15 vps1707806210 python[25059]:     response = await observer.trigger(event, **kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped_inner(event, kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped()
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/bot/handlers/settings.py", line 46, in settings_handler
Oct 14 17:51:15 vps1707806210 python[25059]:     await show_settings_menu(callback_query.message, state, callback_query.from_user.id)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/bot/handlers/settings.py", line 73, in show_settings_menu
Oct 14 17:51:15 vps1707806210 python[25059]:     await safe_edit_or_send_message(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/bot/utils.py", line 74, in safe_edit_or_send_message
Oct 14 17:51:15 vps1707806210 python[25059]:     sent_message = await message.answer(new_text, **kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/methods/base.py", line 84, in emit
Oct 14 17:51:15 vps1707806210 python[25059]:     return await bot(self)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/client/bot.py", line 488, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     return await self.session(self, method, timeout=request_timeout)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/client/session/base.py", line 254, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     return cast(TelegramType, await middleware(bot, method))
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/client/session/aiohttp.py", line 189, in make_request
Oct 14 17:51:15 vps1707806210 python[25059]:     response = self.check_response(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/client/session/base.py", line 120, in check_response
Oct 14 17:51:15 vps1707806210 python[25059]:     raise TelegramBadRequest(method=method, message=description)
Oct 14 17:51:15 vps1707806210 python[25059]: aiogram.exceptions.TelegramBadRequest: Telegram server says - Bad Request: can't parse entities: Character '.' is reserved and must be escaped with the preceding '\'
Oct 14 17:51:15 vps1707806210 python[25059]: During handling of the above exception, another exception occurred:
Oct 14 17:51:15 vps1707806210 python[25059]: Traceback (most recent call last):
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 309, in _process_update
Oct 14 17:51:15 vps1707806210 python[25059]:     response = await self.feed_update(bot, update, **kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.py", line 158, in feed_update
Oct 14 17:51:15 vps1707806210 python[25059]:     response = await self.update.wrap_outer_middleware(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/middlewares/error.py", line 29, in __call__
Oct 14 17:51:15 vps1707806210 python[25059]:     response = await self.router.propagate_event(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 146, in propagate_event
Oct 14 17:51:15 vps1707806210 python[25059]:     return await observer.wrap_outer_middleware(_wrapped, event=event, data=kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 141, in _wrapped
Oct 14 17:51:15 vps1707806210 python[25059]:     return await self._propagate_event(
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/router.py", line 166, in _propagate_event
Oct 14 17:51:15 vps1707806210 python[25059]:     response = await observer.trigger(event, **kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/telegram.py", line 121, in trigger
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped_inner(event, kwargs)
Oct 14 17:51:15 vps1707806210 python[25059]:   File "/root/sms/venv/lib/python3.10/site-packages/aiogram/dispatcher/event/handler.py", line 43, in call
Oct 14 17:51:15 vps1707806210 python[25059]:     return await wrapped()
Oct 14 17:51:15 vps1707806210 python[25059]: TypeError: errors_handler() missing 1 required positional argument: 'exception'