From e524e439b19f2d7913e6607e672aeea0a3fc6480 Mon Sep 17 00:00:00 2001 From: Zakhar Izmaylov Date: Sun, 10 Nov 2024 11:02:15 +0300 Subject: [PATCH] Add make and config for formatting --- .flake8 | 6 +++ .isort.cfg | 3 ++ Makefile | 2 + auth.py | 2 +- bot.py | 12 ++--- client.py | 15 +++--- database.py | 8 +-- handlers/admin/admin.py | 8 +-- handlers/admin/admin_panel.py | 29 ++++------- handlers/admin/user_editor.py | 10 ++-- handlers/commands.py | 5 +- handlers/instructions/instructions.py | 3 +- handlers/keys/key_management.py | 35 ++++--------- handlers/keys/key_utils.py | 27 ++++------ handlers/keys/keys.py | 72 +++++++-------------------- handlers/keys/trial_key.py | 9 ++-- handlers/notifications.py | 22 +++----- handlers/payment/yookassa_pay.py | 5 +- handlers/profile.py | 6 +-- handlers/start.py | 25 +++------- handlers/utils.py | 8 +-- middlewares/admin.py | 1 - middlewares/database.py | 1 - 23 files changed, 110 insertions(+), 204 deletions(-) create mode 100644 .flake8 create mode 100644 .isort.cfg create mode 100644 Makefile diff --git a/.flake8 b/.flake8 new file mode 100644 index 00000000..63d91628 --- /dev/null +++ b/.flake8 @@ -0,0 +1,6 @@ +[flake8] +max-line-length = 200 +ignore = E203, E266, E501, W503, F541, E704, W293, W291, E126, E121, E123, E128, E302,E131,E231,W292 +max-complexity = 25 +select = B, C, E, F, W, T4, B9 +exclude = .venv,.git,.tox,dist,doc,*lib/python*,*egg,build,.txt \ No newline at end of file diff --git a/.isort.cfg b/.isort.cfg new file mode 100644 index 00000000..ffc56c98 --- /dev/null +++ b/.isort.cfg @@ -0,0 +1,3 @@ +[settings] +profile=black +line_length = 200 \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..1f142115 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +formatting: + @black . && isort . && flake8 diff --git a/auth.py b/auth.py index ee0e238a..2eeae90a 100644 --- a/auth.py +++ b/auth.py @@ -50,7 +50,7 @@ async def link(session, server_id: str, client_id: str, email: str): raise Exception("Не удалось получить данные клиентов.") inbounds = response["obj"][0] - settings = json.loads(inbounds["settings"]) + # settings = json.loads(inbounds["settings"]) stream_settings = json.loads(inbounds["streamSettings"]) tcp = stream_settings.get("network", "tcp") diff --git a/bot.py b/bot.py index 7e0744b6..9bcefb32 100644 --- a/bot.py +++ b/bot.py @@ -2,12 +2,6 @@ from aiogram import Bot, Dispatcher, Router from aiogram.fsm.storage.memory import MemoryStorage from config import API_TOKEN, FREEKASSA_ENABLE, YOOKASSA_ENABLE - -bot = Bot(token=API_TOKEN) -storage = MemoryStorage() -dp = Dispatcher(bot=bot, storage=storage) -router = Router() - from handlers import commands, notifications, profile, start from handlers.admin import admin, admin_panel, user_editor from handlers.keys import key_management, keys @@ -15,6 +9,12 @@ from handlers.payment import freekassa_pay, yookassa_pay from middlewares.admin import AdminMiddleware from middlewares.logging import UserActivityMiddleware +bot = Bot(token=API_TOKEN) +storage = MemoryStorage() +dp = Dispatcher(bot=bot, storage=storage) +router = Router() + + dp.include_router(admin.router) dp.include_router(admin_panel.router) dp.include_router(user_editor.router) diff --git a/client.py b/client.py index 3aca9b5a..ac4fb3ca 100644 --- a/client.py +++ b/client.py @@ -69,7 +69,8 @@ async def reset_client_traffic(session, server_id: str, email: str) -> bool: async with session.post(url, headers=headers) as response: if response.status == 200: logger.info( - f"Трафик клиента {email} успешно сброшен на сервере {server_id}") + f"Трафик клиента {email} успешно сброшен на сервере {server_id}" + ) return True else: logger.error( @@ -78,7 +79,8 @@ async def reset_client_traffic(session, server_id: str, email: str) -> bool: return False except Exception as e: logger.error( - f"Ошибка при попытке сброса трафика клиента {email} на сервере {server_id}: {e}") + f"Ошибка при попытке сброса трафика клиента {email} на сервере {server_id}: {e}" + ) return False @@ -136,8 +138,7 @@ async def extend_client_key( ), } - headers = {"Content-Type": "application/json", - "Accept": "application/json"} + headers = {"Content-Type": "application/json", "Accept": "application/json"} try: async with session.post( @@ -146,8 +147,7 @@ async def extend_client_key( headers=headers, ) as response: logger.info(f"POST {response.url} Status: {response.status}") - logger.info( - f"POST Request Data: {json.dumps(payload, indent=2)}") + logger.info(f"POST Request Data: {json.dumps(payload, indent=2)}") response_text = await response.text() logger.info(f"POST Response: {response_text}") @@ -190,8 +190,7 @@ async def extend_client_key_admin( ), } - headers = {"Content-Type": "application/json", - "Accept": "application/json"} + headers = {"Content-Type": "application/json", "Accept": "application/json"} try: async with session.post( diff --git a/database.py b/database.py index 37fba5b0..fd03473b 100644 --- a/database.py +++ b/database.py @@ -25,7 +25,7 @@ async def init_db(): client_id TEXT NOT NULL, email TEXT NOT NULL, created_at BIGINT NOT NULL, - expiry_time BIGINT NOT NULL, + expiry_time BIGINT NOT NULL, key TEXT NOT NULL, server_id TEXT NOT NULL DEFAULT 'server1', -- поле для идентификатора сервера notified BOOLEAN NOT NULL DEFAULT FALSE, -- новое поле для статуса уведомления @@ -170,8 +170,8 @@ async def update_balance(tg_id: int, amount: float): conn = await asyncpg.connect(DATABASE_URL) await conn.execute( """ - UPDATE connections - SET balance = balance + $1 + UPDATE connections + SET balance = balance + $1 WHERE tg_id = $2 """, amount, @@ -236,7 +236,7 @@ async def handle_referral_on_balance_update(tg_id: int, amount: float): await conn.execute( """ - UPDATE referrals SET reward_issued = TRUE + UPDATE referrals SET reward_issued = TRUE WHERE referrer_tg_id = $1 AND referred_tg_id = $2 """, referrer_tg_id, diff --git a/handlers/admin/admin.py b/handlers/admin/admin.py index b27fed36..6106ce79 100644 --- a/handlers/admin/admin.py +++ b/handlers/admin/admin.py @@ -8,13 +8,7 @@ from loguru import logger from auth import login_with_credentials from client import extend_client_key_admin from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL -from database import ( - add_balance_to_client, - check_connection_exists, - get_client_id_by_email, - get_tg_id_by_client_id, - update_key_expiry, -) +from database import add_balance_to_client, check_connection_exists, get_client_id_by_email, get_tg_id_by_client_id, update_key_expiry router = Router() diff --git a/handlers/admin/admin_panel.py b/handlers/admin/admin_panel.py index 16c4fb59..1f5af451 100644 --- a/handlers/admin/admin_panel.py +++ b/handlers/admin/admin_panel.py @@ -6,11 +6,7 @@ from aiogram import F, Router, types from aiogram.filters import Command from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup -from aiogram.types import ( - CallbackQuery, - InlineKeyboardButton, - Message, -) +from aiogram.types import CallbackQuery, InlineKeyboardButton, Message from aiogram.utils.keyboard import InlineKeyboardBuilder from backup import backup_database @@ -45,11 +41,9 @@ async def handle_admin_command(message: types.Message, is_admin: bool): text="Отправить сообщение всем клиентам", callback_data="send_to_alls" ) ) - builder.row(InlineKeyboardButton( - text="Создать бэкап", callback_data="backups")) + builder.row(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) builder.row( - InlineKeyboardButton(text="Перезапустить бота", - callback_data="restart_bot") + InlineKeyboardButton(text="Перезапустить бота", callback_data="restart_bot") ) await bot.send_message( message.chat.id, "Панель администратора.", reply_markup=builder.as_markup() @@ -84,8 +78,7 @@ async def user_stats_menu(callback_query: CallbackQuery, is_admin: bool): builder = InlineKeyboardBuilder() builder.row( - InlineKeyboardButton( - text="Назад", callback_data="back_to_admin_menu") + InlineKeyboardButton(text="Назад", callback_data="back_to_admin_menu") ) await callback_query.message.edit_text( @@ -119,7 +112,7 @@ async def handle_backup(message: Message, is_admin: bool): async def handle_restart(callback_query: CallbackQuery, is_admin: bool): if is_admin: try: - result = subprocess.run( + subprocess.run( ["sudo", "systemctl", "restart", "bot.service"], check=True, capture_output=True, @@ -142,12 +135,10 @@ async def user_editor_menu(callback_query: CallbackQuery, is_admin: bool): ) ) builder.row( - InlineKeyboardButton(text="Поиск по tg_id", - callback_data="search_by_tg_id") + InlineKeyboardButton(text="Поиск по tg_id", callback_data="search_by_tg_id") ) builder.row( - InlineKeyboardButton( - text="Назад", callback_data="back_to_admin_menu") + InlineKeyboardButton(text="Назад", callback_data="back_to_admin_menu") ) await callback_query.message.edit_text( "Выберите метод поиска:", reply_markup=builder.as_markup() @@ -180,11 +171,9 @@ async def back_to_admin_menu(callback_query: CallbackQuery, is_admin: bool): callback_data="send_to_alls", ) ) - builder.row(InlineKeyboardButton( - text="Создать бэкап", callback_data="backups")) + builder.row(InlineKeyboardButton(text="Создать бэкап", callback_data="backups")) builder.row( - InlineKeyboardButton(text="Перезапустить бота", - callback_data="restart_bot") + InlineKeyboardButton(text="Перезапустить бота", callback_data="restart_bot") ) await bot.send_message( tg_id, "Панель администратора", reply_markup=builder.as_markup() diff --git a/handlers/admin/user_editor.py b/handlers/admin/user_editor.py index 0e58d04d..38d256f1 100644 --- a/handlers/admin/user_editor.py +++ b/handlers/admin/user_editor.py @@ -5,16 +5,14 @@ import asyncpg from aiogram import F, Router, types from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup -from aiogram.types import (CallbackQuery, InlineKeyboardButton, - InlineKeyboardMarkup) +from aiogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup from loguru import logger from auth import login_with_credentials from bot import bot from client import delete_client, extend_client_key_admin from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL, SERVERS -from database import (get_client_id_by_email, get_tg_id_by_client_id, - update_key_expiry) +from database import get_client_id_by_email, get_tg_id_by_client_id, update_key_expiry from handlers.admin.admin_panel import back_to_admin_menu from handlers.utils import sanitize_key_name @@ -247,7 +245,7 @@ async def handle_key_name_input(message: types.Message, state: FSMContext): key_buttons = [] for record in user_records: - tg_id = record["tg_id"] + # tg_id = record["tg_id"] balance = record["balance"] email = record["email"] key = record["key"] @@ -450,7 +448,7 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery): ) if record: - email = record["email"] + # email = record["email"] response_message = "Ключ успешно удален." back_button = types.InlineKeyboardButton( text="Назад", callback_data="view_keys" diff --git a/handlers/commands.py b/handlers/commands.py index 833cb70e..f3e6614b 100644 --- a/handlers/commands.py +++ b/handlers/commands.py @@ -10,10 +10,7 @@ from bot import bot from config import DATABASE_URL from handlers.admin.admin import cmd_add_balance from handlers.keys.key_management import handle_key_name_input -from handlers.payment.yookassa_pay import ( - ReplenishBalanceState, - process_custom_amount_input, -) +from handlers.payment.yookassa_pay import ReplenishBalanceState, process_custom_amount_input from handlers.profile import process_callback_view_profile from handlers.start import start_command from handlers.texts import TRIAL diff --git a/handlers/instructions/instructions.py b/handlers/instructions/instructions.py index 3d4d41f1..87394869 100644 --- a/handlers/instructions/instructions.py +++ b/handlers/instructions/instructions.py @@ -1,8 +1,7 @@ import os from aiogram import types -from aiogram.types import (BufferedInputFile, InlineKeyboardButton, - InlineKeyboardMarkup) +from aiogram.types import BufferedInputFile, InlineKeyboardButton, InlineKeyboardMarkup from handlers.texts import INSTRUCTIONS diff --git a/handlers/keys/key_management.py b/handlers/keys/key_management.py index d27419f8..5b84ce55 100644 --- a/handlers/keys/key_management.py +++ b/handlers/keys/key_management.py @@ -6,31 +6,15 @@ import asyncpg from aiogram import F, Router from aiogram.fsm.context import FSMContext from aiogram.fsm.state import State, StatesGroup -from aiogram.types import ( - CallbackQuery, - InlineKeyboardButton, - InlineKeyboardMarkup, - Message, -) +from aiogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message from bot import bot, dp -from config import ( - APP_URL, - DATABASE_URL, - PUBLIC_LINK, - SERVERS, -) +from config import APP_URL, DATABASE_URL, PUBLIC_LINK, SERVERS from database import add_connection, get_balance, store_key, update_balance from handlers.instructions.instructions import send_instructions -from handlers.profile import process_callback_view_profile from handlers.keys.key_utils import create_key_on_server -from handlers.texts import ( - KEY, - KEY_TRIAL, - NULL_BALANCE, - RENEWAL_PLANS, - key_message_success, -) +from handlers.profile import process_callback_view_profile +from handlers.texts import KEY, KEY_TRIAL, NULL_BALANCE, RENEWAL_PLANS, key_message_success from handlers.utils import sanitize_key_name router = Router() @@ -61,7 +45,7 @@ async def process_callback_create_key(callback_query: CallbackQuery, state: FSMC async def select_server(callback_query: CallbackQuery, state: FSMContext): - selected_server_id = (await state.get_data()).get("selected_server_id") + # selected_server_id = (await state.get_data()).get("selected_server_id") conn = await asyncpg.connect(DATABASE_URL) try: @@ -108,8 +92,8 @@ async def select_server(callback_query: CallbackQuery, state: FSMContext): @dp.callback_query(F.data == "confirm_create_new_key") async def confirm_create_new_key(callback_query: CallbackQuery, state: FSMContext): tg_id = callback_query.from_user.id - data = await state.get_data() - server_id = data.get("selected_server_id") + # data = await state.get_data() + # server_id = data.get("selected_server_id") balance = await get_balance(tg_id) if balance < RENEWAL_PLANS["1"]["price"]: @@ -161,7 +145,7 @@ async def handle_key_name_input(message: Message, state: FSMContext): finally: await conn.close() - data = await state.get_data() + # data = await state.get_data() client_id = str(uuid.uuid4()) email = key_name.lower() current_time = datetime.utcnow() @@ -185,8 +169,7 @@ async def handle_key_name_input(message: Message, state: FSMContext): replenish_button = InlineKeyboardButton( text="Перейти в профиль", callback_data="view_profile" ) - keyboard = InlineKeyboardMarkup( - inline_keyboard=[[replenish_button]]) + keyboard = InlineKeyboardMarkup(inline_keyboard=[[replenish_button]]) await message.bot.send_message( tg_id, "❗️ Недостаточно средств на балансе для создания подписки на новое устройство.", diff --git a/handlers/keys/key_utils.py b/handlers/keys/key_utils.py index 47b43614..a269ba18 100644 --- a/handlers/keys/key_utils.py +++ b/handlers/keys/key_utils.py @@ -26,8 +26,7 @@ async def create_key_on_server(server_id, tg_id, client_id, email, expiry_timest if not response.get("success", True): error_msg = response.get("msg", "Неизвестная ошибка.") if "Duplicate email" in error_msg: - raise ValueError( - f"Имя {email} уже занято на сервере {server_id}") + raise ValueError(f"Имя {email} уже занято на сервере {server_id}") else: raise Exception(error_msg) except Exception as e: @@ -35,11 +34,7 @@ async def create_key_on_server(server_id, tg_id, client_id, email, expiry_timest async def renew_server_key( - server_id, - tg_id, client_id, - email, - new_expiry_time, - reset_traffic=RESET_TRAFFIC + server_id, tg_id, client_id, email, new_expiry_time, reset_traffic=RESET_TRAFFIC ): try: session = await login_with_credentials( @@ -65,8 +60,7 @@ async def delete_key_from_db(client_id): conn = await asyncpg.connect(DATABASE_URL) await conn.execute("DELETE FROM keys WHERE client_id = $1", client_id) except Exception as e: - logger.error( - f"Ошибка при удалении ключа {client_id} из базы данных: {e}") + logger.error(f"Ошибка при удалении ключа {client_id} из базы данных: {e}") finally: await conn.close() @@ -74,17 +68,19 @@ async def delete_key_from_db(client_id): async def delete_key_from_server(server_id, client_id): """Удаление ключа с сервера""" try: - async with login_with_credentials(server_id, - ADMIN_USERNAME, - ADMIN_PASSWORD) as session: + async with login_with_credentials( + server_id, ADMIN_USERNAME, ADMIN_PASSWORD + ) as session: success = await delete_client(session, server_id, client_id) if not success: logger.error( - f"Ошибка удаления ключа {client_id} на сервере {server_id}") + f"Ошибка удаления ключа {client_id} на сервере {server_id}" + ) except Exception as e: logger.error( - f"Ошибка при удалении ключа {client_id} с сервера {server_id}: {e}") + f"Ошибка при удалении ключа {client_id} с сервера {server_id}: {e}" + ) async def update_key_on_server(tg_id, client_id, email, expiry_time, server_id): @@ -110,8 +106,7 @@ async def update_key_on_server(tg_id, client_id, email, expiry_time, server_id): f"Ошибка при обновлении ключа на сервере {server_id} для {client_id}" ) else: - logger.info( - f"Ключ успешно обновлен на сервере {server_id} для {client_id}") + logger.info(f"Ключ успешно обновлен на сервере {server_id} для {client_id}") except Exception as e: logger.error( diff --git a/handlers/keys/keys.py b/handlers/keys/keys.py index 57b3c00a..2c03ed15 100644 --- a/handlers/keys/keys.py +++ b/handlers/keys/keys.py @@ -9,38 +9,12 @@ from aiogram.types import BufferedInputFile from loguru import logger from bot import bot -from config import ( - APP_URL, - DATABASE_URL, - PUBLIC_LINK, - SERVERS, -) -from database import ( - delete_key, - get_balance, - store_key, - update_balance, - update_key_expiry, -) -from handlers.texts import ( - INSUFFICIENT_FUNDS_MSG, - KEY_NOT_FOUND_MSG, - NO_KEYS, - PLAN_SELECTION_MSG, - RENEWAL_PLANS, - SUCCESS_RENEWAL_MSG, - key_message, -) - +from config import APP_URL, DATABASE_URL, PUBLIC_LINK, SERVERS +from database import delete_key, get_balance, store_key, update_balance, update_key_expiry +from handlers.keys.key_utils import delete_key_from_db, delete_key_from_server, renew_server_key, update_key_on_server +from handlers.texts import INSUFFICIENT_FUNDS_MSG, KEY_NOT_FOUND_MSG, NO_KEYS, PLAN_SELECTION_MSG, RENEWAL_PLANS, SUCCESS_RENEWAL_MSG, key_message from handlers.utils import handle_error -from handlers.keys.key_utils import ( - update_key_on_server, - delete_key_from_db, - renew_server_key, - delete_key_from_server -) - locale.setlocale(locale.LC_TIME, "ru_RU.UTF-8") router = Router() @@ -76,8 +50,7 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery): ) buttons.append([back_button]) - inline_keyboard = types.InlineKeyboardMarkup( - inline_keyboard=buttons) + inline_keyboard = types.InlineKeyboardMarkup(inline_keyboard=buttons) response_message = ( "Это ваши устройства:\n\n" "Нажмите на имя устройства для управления его подпиской." @@ -159,8 +132,7 @@ async def process_callback_view_key(callback_query: types.CallbackQuery): expiry_time = record["expiry_time"] server_id = record["server_id"] - server_name = SERVERS.get(server_id, {}).get( - "name", "мультисервер") + server_name = SERVERS.get(server_id, {}).get("name", "мультисервер") expiry_date = datetime.utcfromtimestamp(expiry_time / 1000) current_date = datetime.utcnow() time_left = expiry_date - current_date @@ -220,11 +192,9 @@ async def process_callback_view_key(callback_query: types.CallbackQuery): inline_keyboard.append([back_button]) - keyboard = types.InlineKeyboardMarkup( - inline_keyboard=inline_keyboard) + keyboard = types.InlineKeyboardMarkup(inline_keyboard=inline_keyboard) - image_path = os.path.join( - os.path.dirname(__file__), "pic_view.jpg") + image_path = os.path.join(os.path.dirname(__file__), "pic_view.jpg") if not os.path.isfile(image_path): await bot.send_message(tg_id, "Файл изображения не найден.") @@ -304,7 +274,7 @@ async def process_callback_update_subscription(callback_query: types.CallbackQue ) ) - results = await asyncio.gather(*tasks) + await asyncio.gather(*tasks) await store_key( tg_id, @@ -326,8 +296,7 @@ async def process_callback_update_subscription(callback_query: types.CallbackQue back_button = types.InlineKeyboardButton( text="🔙 Назад в профиль", callback_data="view_profile" ) - keyboard = types.InlineKeyboardMarkup( - inline_keyboard=[[back_button]]) + keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]]) await bot.send_message( tg_id, response_message, reply_markup=keyboard, parse_mode="HTML" @@ -421,9 +390,9 @@ async def process_callback_renew_key(callback_query: types.CallbackQuery): ) if record: - email = record["email"] + # email = record["email"] expiry_time = record["expiry_time"] - current_time = datetime.utcnow().timestamp() * 1000 + # current_time = datetime.utcnow().timestamp() * 1000 keyboard = types.InlineKeyboardMarkup( inline_keyboard=[ [ @@ -505,13 +474,12 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery): ) if record: - email = record["email"] + # email = record["email"] response_message = "Ключ успешно удален." back_button = types.InlineKeyboardButton( text="Назад", callback_data="view_keys" ) - keyboard = types.InlineKeyboardMarkup( - inline_keyboard=[[back_button]]) + keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]]) await delete_key(client_id) await bot.edit_message_text( @@ -525,14 +493,12 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery): try: tasks = [] for server_id in SERVERS: - tasks.append(delete_key_from_server( - server_id, client_id)) + tasks.append(delete_key_from_server(server_id, client_id)) await asyncio.gather(*tasks) except Exception as e: - logger.error( - f"Ошибка при удалении ключа {client_id}: {e}") + logger.error(f"Ошибка при удалении ключа {client_id}: {e}") asyncio.create_task(delete_key_from_servers()) @@ -543,8 +509,7 @@ async def process_callback_confirm_delete(callback_query: types.CallbackQuery): back_button = types.InlineKeyboardButton( text="Назад", callback_data="view_keys" ) - keyboard = types.InlineKeyboardMarkup( - inline_keyboard=[[back_button]]) + keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]]) await bot.edit_message_text( response_message, @@ -633,8 +598,7 @@ async def process_callback_renew_plan(callback_query: types.CallbackQuery): back_button = types.InlineKeyboardButton( text="Назад", callback_data="view_profile" ) - keyboard = types.InlineKeyboardMarkup( - inline_keyboard=[[back_button]]) + keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]]) await bot.send_message( tg_id, response_message, reply_markup=keyboard, parse_mode="HTML" diff --git a/handlers/keys/trial_key.py b/handlers/keys/trial_key.py index 4b0bb8f9..117868d8 100644 --- a/handlers/keys/trial_key.py +++ b/handlers/keys/trial_key.py @@ -63,16 +63,15 @@ async def generate_and_store_keys( await conn.execute( """ - INSERT INTO connections (tg_id, trial) - VALUES ($1, 1) - ON CONFLICT (tg_id) + INSERT INTO connections (tg_id, trial) + VALUES ($1, 1) + ON CONFLICT (tg_id) DO UPDATE SET trial = 1 """, tg_id, ) else: - logger.error( - "Не удалось создать ключ на одном или нескольких серверах.") + logger.error("Не удалось создать ключ на одном или нескольких серверах.") finally: await conn.close() diff --git a/handlers/notifications.py b/handlers/notifications.py index 898aef88..25f37a03 100644 --- a/handlers/notifications.py +++ b/handlers/notifications.py @@ -9,13 +9,7 @@ from auth import login_with_credentials from client import delete_client, extend_client_key from config import ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_URL, SERVERS from database import delete_key, get_balance, update_balance, update_key_expiry -from handlers.texts import ( - KEY_EXPIRY_10H, - KEY_EXPIRY_24H, - KEY_RENEWAL_FAILED, - KEY_RENEWED, - RENEWAL_PLANS, -) +from handlers.texts import KEY_EXPIRY_10H, KEY_EXPIRY_24H, KEY_RENEWAL_FAILED, KEY_RENEWED, RENEWAL_PLANS router = Router() @@ -254,13 +248,13 @@ async def handle_expired_keys(bot: Bot, conn: asyncpg.Connection, current_time: f"Время истечения ключа: {expiry_time} (дата: {expiry_date}), Текущее время: {current_date}, Оставшееся время: {time_left}." ) - if time_left.total_seconds() <= 0: - days_left_message = "Ключ истек" - elif time_left.days > 0: - days_left_message = f"Осталось дней: {time_left.days}" - else: - hours_left = time_left.seconds // 3600 - days_left_message = f"Осталось часов: {hours_left}" + # if time_left.total_seconds() <= 0: + # days_left_message = "Ключ истек" + # elif time_left.days > 0: + # days_left_message = f"Осталось дней: {time_left.days}" + # else: + # hours_left = time_left.seconds // 3600 + # days_left_message = f"Осталось часов: {hours_left}" message_expired = f"Ваш ключ {email} истек и был удален!\n\n Перейдите в профиль для создания нового ключа" button_profile = types.InlineKeyboardButton( diff --git a/handlers/payment/yookassa_pay.py b/handlers/payment/yookassa_pay.py index 9944c960..fc791543 100644 --- a/handlers/payment/yookassa_pay.py +++ b/handlers/payment/yookassa_pay.py @@ -10,8 +10,7 @@ from yookassa import Configuration, Payment from bot import bot from config import YOOKASSA_ENABLE, YOOKASSA_SECRET_KEY, YOOKASSA_SHOP_ID -from database import (add_connection, check_connection_exists, get_key_count, - update_balance) +from database import add_connection, check_connection_exists, get_key_count, update_balance from handlers.profile import process_callback_view_profile from handlers.texts import PAYMENT_OPTIONS @@ -128,7 +127,7 @@ async def process_amount_selection( await state.update_data(amount=amount) await state.set_state(ReplenishBalanceState.waiting_for_payment_confirmation) - state_data = await state.get_data() + # state_data = await state.get_data() customer_name = callback_query.from_user.full_name customer_id = callback_query.from_user.id diff --git a/handlers/profile.py b/handlers/profile.py index a868675c..ea6539ba 100644 --- a/handlers/profile.py +++ b/handlers/profile.py @@ -7,11 +7,9 @@ from aiogram.utils.keyboard import InlineKeyboardBuilder from loguru import logger from bot import bot -from config import (CHANNEL_URL, FREEKASSA_ENABLE, PAYMENT_METHOD, - YOOKASSA_ENABLE) +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() diff --git a/handlers/start.py b/handlers/start.py index 112925dc..40f76706 100644 --- a/handlers/start.py +++ b/handlers/start.py @@ -3,12 +3,7 @@ import os import asyncpg from aiogram import F, Router from aiogram.filters import Command -from aiogram.types import ( - BufferedInputFile, - CallbackQuery, - InlineKeyboardButton, - Message, -) +from aiogram.types import BufferedInputFile, CallbackQuery, InlineKeyboardButton, Message from aiogram.utils.keyboard import InlineKeyboardBuilder from loguru import logger @@ -27,26 +22,22 @@ async def send_welcome_message(chat_id: int, trial_status: int): builder = InlineKeyboardBuilder() if trial_status == 0: builder.row( - InlineKeyboardButton(text="🔗 Подключить VPN", - callback_data="connect_vpn") + InlineKeyboardButton(text="🔗 Подключить VPN", callback_data="connect_vpn") ) builder.row( - InlineKeyboardButton(text="👤 Мой профиль", - callback_data="view_profile") + InlineKeyboardButton(text="👤 Мой профиль", callback_data="view_profile") ) builder.row( InlineKeyboardButton(text="📞 Поддержка", url=SUPPORT_CHAT_URL), InlineKeyboardButton(text="📢 Наш канал", url=CHANNEL_URL), ) - builder.row(InlineKeyboardButton( - text="🔒 О VPN", callback_data="about_vpn")) + builder.row(InlineKeyboardButton(text="🔒 О VPN", callback_data="about_vpn")) if os.path.isfile(image_path): with open(image_path, "rb") as image_from_buffer: await bot.send_photo( chat_id=chat_id, - photo=BufferedInputFile( - image_from_buffer.read(), filename="pic.jpg"), + photo=BufferedInputFile(image_from_buffer.read(), filename="pic.jpg"), caption=WELCOME_TEXT, parse_mode="HTML", reply_markup=builder.as_markup(), @@ -110,8 +101,7 @@ async def handle_connect_vpn(callback_query: CallbackQuery): builder = InlineKeyboardBuilder() builder.row( - InlineKeyboardButton(text="👤 Мой профиль", - callback_data="view_profile") + InlineKeyboardButton(text="👤 Мой профиль", callback_data="view_profile") ) builder.row( @@ -148,8 +138,7 @@ async def handle_about_vpn(callback_query: CallbackQuery): await callback_query.message.delete() builder = InlineKeyboardBuilder() - builder.row(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/handlers/utils.py b/handlers/utils.py index bab8c9c5..9ed382c6 100644 --- a/handlers/utils.py +++ b/handlers/utils.py @@ -1,11 +1,11 @@ import random import re -from bot import bot - -from config import SERVERS from loguru import logger +from bot import bot +from config import SERVERS + def sanitize_key_name(key_name: str) -> str: return re.sub(r"[^a-z0-9@._-]", "", key_name.lower()) @@ -46,4 +46,4 @@ async def handle_error(tg_id, callback_query, message): await bot.send_message(tg_id, message, parse_mode="HTML") except Exception as e: - logger.error(f"Ошибка при обработке ошибки: {e}") \ No newline at end of file + logger.error(f"Ошибка при обработке ошибки: {e}") diff --git a/middlewares/admin.py b/middlewares/admin.py index 6c6fccf1..753d8d3f 100644 --- a/middlewares/admin.py +++ b/middlewares/admin.py @@ -1,4 +1,3 @@ -from functools import wraps from typing import Any, Awaitable, Callable, Dict from aiogram import BaseMiddleware diff --git a/middlewares/database.py b/middlewares/database.py index 759004fb..c2d05102 100644 --- a/middlewares/database.py +++ b/middlewares/database.py @@ -1,4 +1,3 @@ -from functools import wraps from typing import Any, Awaitable, Callable, Dict import asyncpg