From a791314e1fa7dc721075ea10018b1bf8a560112c Mon Sep 17 00:00:00 2001 From: Zakhar Izmaylov Date: Sat, 9 Nov 2024 23:20:08 +0300 Subject: [PATCH] Fix --- bot.py | 2 +- handlers/admin/admin_panel.py | 28 +++++++++++----------- handlers/notifications.py | 13 +++++------ handlers/payment/yookassa_pay.py | 7 +++--- handlers/profile.py | 40 ++++++++++++++------------------ handlers/start.py | 18 +++++++------- middlewares/logging.py | 12 +++++----- 7 files changed, 58 insertions(+), 62 deletions(-) diff --git a/bot.py b/bot.py index 707bb741..7e0744b6 100644 --- a/bot.py +++ b/bot.py @@ -1,7 +1,7 @@ from aiogram import Bot, Dispatcher, Router from aiogram.fsm.storage.memory import MemoryStorage -from config import API_TOKEN,YOOKASSA_ENABLE,FREEKASSA_ENABLE +from config import API_TOKEN, FREEKASSA_ENABLE, YOOKASSA_ENABLE bot = Bot(token=API_TOKEN) storage = MemoryStorage() diff --git a/handlers/admin/admin_panel.py b/handlers/admin/admin_panel.py index 21e2147a..8b81f86e 100644 --- a/handlers/admin/admin_panel.py +++ b/handlers/admin/admin_panel.py @@ -31,23 +31,23 @@ class UserEditorState(StatesGroup): async def handle_admin_command(message: types.Message, is_admin: bool): if is_admin: builder = InlineKeyboardBuilder() - builder.add( + builder.row( InlineKeyboardButton( text="Статистика пользователей", callback_data="user_stats" ) ) - builder.add( + builder.row( InlineKeyboardButton( text="Редактор пользователей", callback_data="user_editor" ) ) - builder.add( + builder.row( InlineKeyboardButton( text="Отправить сообщение всем клиентам", callback_data="send_to_alls" ) ) - builder.add(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) - builder.add( + builder.row(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) + builder.row( InlineKeyboardButton(text="Перезапустить бота", callback_data="restart_bot") ) await bot.send_message( @@ -82,7 +82,7 @@ async def user_stats_menu(callback_query: CallbackQuery, is_admin: bool): ) builder = InlineKeyboardBuilder() - builder.add( + builder.row( InlineKeyboardButton(text="Назад", callback_data="back_to_admin_menu") ) @@ -134,15 +134,15 @@ async def handle_restart(callback_query: CallbackQuery, is_admin: bool): async def user_editor_menu(callback_query: CallbackQuery, is_admin: bool): if is_admin: builder = InlineKeyboardBuilder() - builder.add( + builder.row( InlineKeyboardButton( text="Поиск по имени ключа", callback_data="search_by_key_name" ) ) - builder.add( + builder.row( InlineKeyboardButton(text="Поиск по tg_id", callback_data="search_by_tg_id") ) - builder.add( + builder.row( InlineKeyboardButton(text="Назад", callback_data="back_to_admin_menu") ) await callback_query.message.edit_text( @@ -160,24 +160,24 @@ async def back_to_admin_menu(callback_query: CallbackQuery, is_admin: bool): tg_id = callback_query.from_user.id if is_admin: builder = InlineKeyboardBuilder() - builder.add( + builder.row( InlineKeyboardButton( text="Статистика пользователей", callback_data="user_stats" ) ) - builder.add( + builder.row( InlineKeyboardButton( text="Редактор пользователей", callback_data="user_editor" ) ) - builder.add( + builder.row( InlineKeyboardButton( text="Отправить сообщение всем клиентам", callback_data="send_to_alls", ) ) - builder.add(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) - builder.add( + builder.row(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) + builder.row( InlineKeyboardButton(text="Перезапустить бота", callback_data="restart_bot") ) await bot.send_message( diff --git a/handlers/notifications.py b/handlers/notifications.py index bdc594c1..7ae371eb 100644 --- a/handlers/notifications.py +++ b/handlers/notifications.py @@ -35,13 +35,12 @@ async def notify_expiring_keys(bot: Bot): logger.info("Начало обработки уведомлений.") - notification_tasks = [ - notify_10h_keys(bot, conn, current_time, threshold_time_10h), - notify_24h_keys(bot, conn, current_time, threshold_time_24h), - handle_expired_keys(bot, conn, current_time), - ] - - await asyncio.gather(*notification_tasks) + await notify_10h_keys(bot, conn, current_time, threshold_time_10h) + await asyncio.sleep(1) + await notify_24h_keys(bot, conn, current_time, threshold_time_24h) + await asyncio.sleep(1) + await handle_expired_keys(bot, conn, current_time) + await asyncio.sleep(1) except Exception as e: logger.error(f"Ошибка при отправке уведомлений: {e}") diff --git a/handlers/payment/yookassa_pay.py b/handlers/payment/yookassa_pay.py index 7f6fe5df..1e3dae74 100644 --- a/handlers/payment/yookassa_pay.py +++ b/handlers/payment/yookassa_pay.py @@ -9,7 +9,7 @@ from loguru import logger from yookassa import Configuration, Payment from bot import bot -from config import YOOKASSA_SECRET_KEY, YOOKASSA_SHOP_ID +from config import YOOKASSA_ENABLE, YOOKASSA_SECRET_KEY, YOOKASSA_SHOP_ID from database import ( add_connection, check_connection_exists, @@ -24,8 +24,9 @@ router = Router() Configuration.account_id = YOOKASSA_SHOP_ID Configuration.secret_key = YOOKASSA_SECRET_KEY -logger.debug(f"Account ID: {YOOKASSA_SHOP_ID}") -logger.debug(f"Secret Key: {YOOKASSA_SECRET_KEY}") +if YOOKASSA_ENABLE: + logger.debug(f"Account ID: {YOOKASSA_SHOP_ID}") + logger.debug(f"Secret Key: {YOOKASSA_SECRET_KEY}") class ReplenishBalanceState(StatesGroup): diff --git a/handlers/profile.py b/handlers/profile.py index c2617b4a..1bbd597a 100644 --- a/handlers/profile.py +++ b/handlers/profile.py @@ -8,13 +8,9 @@ from aiogram.utils.keyboard import InlineKeyboardBuilder from loguru import logger from bot import bot -from config import PAYMENT_METHOD,CHANNEL_URL +from config import CHANNEL_URL, FREEKASSA_ENABLE, PAYMENT_METHOD, YOOKASSA_ENABLE from database import get_balance, get_key_count, get_referral_stats -from handlers.texts import ( - get_referral_link, - invite_message_send, - profile_message_send, -) +from handlers.texts import get_referral_link, invite_message_send, profile_message_send router = Router() @@ -35,33 +31,33 @@ async def process_callback_view_profile( profile_message = profile_message_send(username, chat_id, balance, key_count) - profile_message += f"Обязательно подпишитесь на канал здесь\n" - if key_count == 0: profile_message += ( "\nНажмите ➕Устройство снизу, чтобы добавить устройство в VPN" ) builder = InlineKeyboardBuilder() - builder.add( + builder.row(InlineKeyboardButton(text="📢 Наш канал", url=CHANNEL_URL)) + builder.row( InlineKeyboardButton(text="➕ Устройство", callback_data="create_key"), InlineKeyboardButton(text="📱 Мои устр-ва", callback_data="view_keys"), ) - builder.add( - InlineKeyboardButton( - text="💳 Пополнить баланс", - callback_data=( - "pay_freekassa" - if PAYMENT_METHOD == "freekassa" - else "replenish_balance" - ), + if YOOKASSA_ENABLE or FREEKASSA_ENABLE: + builder.row( + InlineKeyboardButton( + text="💳 Пополнить баланс", + callback_data=( + "pay_freekassa" + if PAYMENT_METHOD == "freekassa" + else "replenish_balance" + ), + ) ) - ) - builder.add( + builder.row( InlineKeyboardButton(text="👥 Пригласить", callback_data="invite"), InlineKeyboardButton(text="📘 Инструкции", callback_data="instructions"), ) - builder.add(InlineKeyboardButton(text="⬅️ Назад", callback_data="back_to_menu")) + builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="back_to_menu")) # Попробуем удалить предыдущее сообщение try: @@ -71,7 +67,7 @@ async def process_callback_view_profile( f"Ошибка при удалении сообщения: {e}" ) # Логируем ошибку, если удаление не удалось - if not os.path.isfile(image_path): + if os.path.isfile(image_path): with open(image_path, "rb") as image_file: await bot.send_photo( chat_id=chat_id, @@ -104,7 +100,7 @@ async def invite_handler(callback_query: types.CallbackQuery): invite_message = invite_message_send(referral_link, referral_stats) builder = InlineKeyboardBuilder() - builder.add(InlineKeyboardButton(text="⬅️ Назад", callback_data="view_profile")) + builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="view_profile")) await callback_query.message.delete() diff --git a/handlers/start.py b/handlers/start.py index 569ea216..9b6e564d 100644 --- a/handlers/start.py +++ b/handlers/start.py @@ -28,19 +28,19 @@ async def send_welcome_message(chat_id: int, trial_status: int): builder = InlineKeyboardBuilder() if trial_status == 0: - builder.add( + builder.row( InlineKeyboardButton(text="🔗 Подключить VPN", callback_data="connect_vpn") ) - builder.add( + builder.row( InlineKeyboardButton(text="👤 Мой профиль", callback_data="view_profile") ) - builder.add(InlineKeyboardButton(text="🔒 О VPN", callback_data="about_vpn")) - builder.add( + builder.row( InlineKeyboardButton(text="📞 Поддержка", url=SUPPORT_CHAT_URL), InlineKeyboardButton(text="📢 Наш канал", url=CHANNEL_URL), ) + builder.row(InlineKeyboardButton(text="🔒 О VPN", callback_data="about_vpn")) - if not os.path.isfile(image_path): + if os.path.isfile(image_path): with open(image_path, "rb") as image_from_buffer: await bot.send_photo( chat_id=chat_id, @@ -107,11 +107,11 @@ async def handle_connect_vpn(callback_query: CallbackQuery): ) builder = InlineKeyboardBuilder() - builder.add( + builder.row( InlineKeyboardButton(text="👤 Мой профиль", callback_data="view_profile") ) - builder.add( + builder.row( InlineKeyboardButton( text="🍏 Подключить", url=f'{APP_URL}/?url=v2raytun://import/{trial_key_info["key"]}', @@ -122,7 +122,7 @@ async def handle_connect_vpn(callback_query: CallbackQuery): ), ) - builder.add( + builder.row( InlineKeyboardButton( text="🍏 Скачать", url="https://apps.apple.com/ru/app/v2raytun/id6476628951", @@ -145,7 +145,7 @@ async def handle_about_vpn(callback_query: CallbackQuery): await callback_query.message.delete() builder = InlineKeyboardBuilder() - builder.add(InlineKeyboardButton(text="⬅️ Назад", callback_data="back_to_menu")) + builder.row(InlineKeyboardButton(text="⬅️ Назад", callback_data="back_to_menu")) await callback_query.message.answer( ABOUT_VPN, parse_mode="HTML", reply_markup=builder.as_markup() diff --git a/middlewares/logging.py b/middlewares/logging.py index cee6febe..a6471c5d 100644 --- a/middlewares/logging.py +++ b/middlewares/logging.py @@ -19,18 +19,18 @@ class UserActivityMiddleware(BaseMiddleware): if isinstance(event, Message): user_id = event.from_user.id username = event.from_user.username - action = f"Message: {event.text}" + action = f"Сообщение: {event.text}" elif isinstance(event, CallbackQuery): user_id = event.from_user.id username = event.from_user.username - action = f"Callback: {event.data}" + action = f"Обратный вызов: {event.data}" # Логируем действие пользователя logger.info( - f"User Activity - " - f"User ID: {user_id}, " - f"Username: {username}, " - f"Action: {action}" + f"Активность пользователя - " + f"ID пользователя: {user_id}, " + f"Имя пользователя: {username}, " + f"Действие: {action}" ) # Продолжаем выполнение обработчика