diff --git a/.gitignore b/.gitignore index c9dff014..42be1ec0 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /__pycache__ /vpn_users.db /config.py +/database.db diff --git a/bot.py b/bot.py index 6e115079..808c1df8 100644 --- a/bot.py +++ b/bot.py @@ -8,6 +8,9 @@ from auth import login_with_credentials, link from client import add_client, generate_client_id from datetime import datetime, timedelta from config import API_TOKEN, ADMIN_PASSWORD, ADMIN_USERNAME +from database import add_connection, DATABASE_PATH +import uuid +import aiosqlite @@ -41,23 +44,43 @@ async def handle_text(message: types.Message, state: FSMContext): try: session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD) + # Параметры клиента + email = message.text tg_id = message.from_user.id - email = message.text - client_id = generate_client_id() - email = message.text - limit_ip = 1 - total_gb = 0 - current_time = datetime.utcnow() - expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000) - enable = True - flow = "xtls-rprx-vision" + # Проверяем наличие активного ключа + async with aiosqlite.connect(DATABASE_PATH) as db: + async with db.execute(''' + SELECT * FROM connections + WHERE tg_id = ? AND expiry_time > ? + ''', (tg_id, int(datetime.utcnow().timestamp() * 1000))) as cursor: + existing_key = await cursor.fetchone() + + if existing_key: + await message.reply("У вас уже есть активный ключ. Вы не можете создать больше одного ключа.") + else: + # Генерация нового ключа + client_id = str(uuid.uuid4()) + limit_ip = 1 + total_gb = 0 + current_time = datetime.utcnow() + expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000) + enable = True + flow = "xtls-rprx-vision" - add_client(session, client_id, email, tg_id, limit_ip, total_gb, expiry_time, enable, flow) - connection_link = link(session, email) + # Добавление клиента (функция для создания клиента) + result = add_client(session, client_id, email, tg_id, limit_ip, total_gb, expiry_time, enable, flow) - await message.reply(f"Ключ создан:\n
{connection_link}
", parse_mode="HTML") + # Сохранение данных в базу данных + await add_connection(tg_id, client_id, email, expiry_time) + # Получение ссылки на подключение + connection_link = link(session, email) + + # Отправка ключа в виде цитаты + await message.reply(f"Ключ создан:\n
{connection_link}
", parse_mode="HTML") + + # Сброс состояния await state.clear() except Exception as e: - await message.reply(f"Произошла ошибка: {e}") + await message.reply(f"Произошла ошибка: {e}") \ No newline at end of file diff --git a/bot_old.py b/bot_old.py index 32265eae..a245a5b1 100644 --- a/bot_old.py +++ b/bot_old.py @@ -3,7 +3,7 @@ from aiogram.filters import Command from aiogram.types import Message from aiogram.filters import Command import requests -from database import add_user, get_user, update_subscription +# from database import add_user, get_user, update_subscription from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup from aiogram.fsm.storage.memory import MemoryStorage from aiogram.fsm.context import FSMContext diff --git a/database.py b/database.py index 2836e3eb..3f02fd85 100644 --- a/database.py +++ b/database.py @@ -1,38 +1,27 @@ -from sqlalchemy import create_engine, Column, Integer, String, DateTime -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker -import datetime +import aiosqlite +from datetime import datetime -DATABASE_URL = 'sqlite:///vpn_users.db' +DATABASE_PATH = 'database.db' -engine = create_engine(DATABASE_URL) -Session = sessionmaker(bind=engine) -session = Session() -Base = declarative_base() +async def init_db(): + async with aiosqlite.connect(DATABASE_PATH) as db: + await db.execute(''' + CREATE TABLE IF NOT EXISTS connections ( + tg_id INTEGER NOT NULL, + client_id TEXT NOT NULL, + email TEXT NOT NULL, + expiry_time INTEGER NOT NULL, + PRIMARY KEY (tg_id, client_id) + ) + ''') + await db.commit() -class VPNUser(Base): - __tablename__ = 'vpn_users' - - id = Column(Integer, primary_key=True) - telegram_id = Column(Integer, unique=True) - username = Column(String) - subscription_end = Column(DateTime) - access_key = Column(String) +async def add_connection(tg_id: int, client_id: str, email: str, expiry_time: int): + async with aiosqlite.connect(DATABASE_PATH) as db: + # Добавляем новый ключ + await db.execute(''' + INSERT INTO connections (tg_id, client_id, email, expiry_time) + VALUES (?, ?, ?, ?) + ''', (tg_id, client_id, email, expiry_time)) + await db.commit() -Base.metadata.create_all(engine) - -def add_user(telegram_id, username, access_key): - user = VPNUser(telegram_id=telegram_id, username=username, - subscription_end=datetime.datetime.now() + datetime.timedelta(days=30), - access_key=access_key) - session.add(user) - session.commit() - -def get_user(telegram_id): - return session.query(VPNUser).filter(VPNUser.telegram_id == telegram_id).first() - -def update_subscription(telegram_id, days): - user = get_user(telegram_id) - if user: - user.subscription_end += datetime.timedelta(days=days) - session.commit() diff --git a/main.py b/main.py index 1c3d37a6..2dfa6634 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,9 @@ import asyncio from bot import dp, router, bot +from database import init_db async def main(): + await init_db() dp.include_router(router) # Подключение роутера await dp.start_polling(bot) # Запуск поллинга