This commit is contained in:
2024-12-07 23:02:33 +03:00
parent b0bafcda5b
commit 050ca9936b
7 changed files with 49 additions and 28 deletions

View File

@@ -39,9 +39,9 @@ class MongoDBRepository:
self.logger.debug(f"VPN сервер добавлен с ID: {result.inserted_id}")
return result.inserted_id
async def get_server(self, server_id):
async def get_server(self, server_id: str):
"""Получает сервер VPN по его ID."""
server = await self.collection.find_one({"_id": server_id})
server = await self.collection.find_one({"name": server_id})
if server:
self.logger.debug(f"Найден VPN сервер: {server}")
else:

View File

@@ -74,14 +74,16 @@ class DatabaseManager:
result = await session.execute(select(User).where(User.telegram_id == telegram_id))
user = result.scalars().first()
if user:
user.balance = amount
user.balance += int(amount)
await self.add_transaction(user.id, amount)
await session.commit()
else:
self.logger.warning(f"Пользователь с Telegram ID {telegram_id} не найден.")
return "ERROR"
except SQLAlchemyError as e:
self.logger.error(f"Ошибка при обновлении баланса: {e}")
await session.rollback()
return "ERROR"
async def last_subscription(self, user_id: int):
"""
@@ -131,14 +133,16 @@ class DatabaseManager:
return "ERROR"
# Проверка достаточности средств для покупки подписки
cost = plan["cost"]
cost = int(plan["price"])
if result.balance >= cost:
result.balance -= cost
await session.commit()
# Создание подписки для пользователя
expiry_date = datetime.now(datetime.timezone.utc) + relativedelta(months=plan["duration_months"])
new_subscription = Subscription(user_id=result.id, vpn_server_id=None, plan=plan_id, expiry_date=expiry_date)
expiry_date = datetime.utcnow() + relativedelta(months=plan["duration_months"])
server = await self.mongo_repo.get_server_with_least_clients()
self.logger.info(f"{server}")
new_subscription = Subscription(user_id=result.id, vpn_server_id=str(server['server']["name"]), plan=plan_id, expiry_date=expiry_date)
session.add(new_subscription)
await session.commit()

View File

@@ -42,11 +42,15 @@ services:
context: .
container_name: telegram_bot
environment:
POSTGRES_URL: "postgresql://AH3J9GSPBYOP:uPS9?y~mcu2@postgres:5432/bot_db"
TOKEN: "7502946151:AAHspA8iieJqrhUHZveILGfeZWp-VqQhEnQ"
POSTGRES_URL: "postgresql+asyncpg://AH3J9GSPBYOP:uPS9?y~mcu2@postgres:5432/bot_db"
MONGO_URL: "mongodb://root:itOj4CE2miKR@mongodb:27017"
DB_NAME: "MongoDBSub&Ser"
SERVER_COLLECTION: "servers"
PLAN_COLLECTION: "plans"
volumes:
- logs_data:/app/logs # Логи сохраняются в контейнере
- logs_data:/app/logs
depends_on:
- postgres
- mongodb
command: ["python", "main.py"] # Задаем явную команду запуска
command: ["python", "main.py"]

View File

@@ -3,7 +3,7 @@ from aiogram.filters import Command
from databases.postgresql import DatabaseManager
from databases.model import User, Subscription, Transaction, Administrators
from databases.db_config import get_postgres_session
from keyboard.keyboards import subhist_keyboard,tarif_confirm_keyboard, popup_keyboard, main_keyboard,faq_keyboard,about_tarifs_keyboard, account_keyboard, buy_keyboard,balance_keyboard,guide_keyboard,tarif_Lark_keyboard,tarif_Lark_pro_keyboard,tranhist_keyboard
from keyboard.keyboards import subhist_keyboard,confirm_popup_keyboard,tarif_confirm_keyboard, popup_keyboard, main_keyboard,faq_keyboard,about_tarifs_keyboard, account_keyboard, buy_keyboard,balance_keyboard,guide_keyboard,tarif_Lark_keyboard,tarif_Lark_pro_keyboard,tranhist_keyboard
# Инициализируем менеджер базы данных
db_manager = DatabaseManager(get_postgres_session)
@@ -93,7 +93,7 @@ async def popup_callback_handler(callback: types.CallbackQuery):
if user:
await callback.message.edit_text(
f"Ты думал здесь что то будет?",
f"Работает в режиме теста!!!",
reply_markup=popup_keyboard()
)
else:
@@ -242,6 +242,22 @@ async def lark_tariff_callback_handler(callback: types.CallbackQuery):
keyboard = tarif_confirm_keyboard(tariff_name, tariff_time, tariff_class)
await callback.message.edit_text(text=text, reply_markup=keyboard)
async def popup_confirm_callback_handler(callback: types.CallbackQuery):
"""
Обработчик подтверждения пополнения баланса.
"""
data = callback.data.split(":")
popup_info = data[1]
result = await db_manager.update_balance(callback.from_user.id,popup_info)
if result == "ERROR":
await callback.message.answer(
"Произошла ошибка, попробуйте позже или свяжитесь с администрацией."
)
await callback.answer()
return
text = f"Вы пополнили свой баланс на {popup_info}. P.S. Мы завтра закрываемся"
await callback.message.edit_text(text=text, reply_markup=confirm_popup_keyboard())
async def confirm_callback_handler(callback: types.CallbackQuery):
"""
Обработчик подтверждения покупки тарифа.
@@ -296,3 +312,4 @@ def register_handlers(dp: Dispatcher):
dp.callback_query.register(about_tarifs_callback_handler, lambda c: c.data == "about_tarifs")
dp.callback_query.register(lark_tariff_callback_handler, lambda c: c.data.startswith("Lark:"))
dp.callback_query.register(confirm_callback_handler, lambda c: c.data.startswith("confirm:"))
dp.callback_query.register(popup_confirm_callback_handler, lambda c: c.data.startswith("popup:"))

View File

@@ -48,7 +48,9 @@ def popup_keyboard():
Пополнение
"""
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text="Хуй знает что здесь", callback_data="secret"))
builder.row(InlineKeyboardButton(text="Пополнение на 100", callback_data="popup:100"))
builder.row(InlineKeyboardButton(text="Пополнение на 300", callback_data="popup:300"))
builder.row(InlineKeyboardButton(text="Пополнение на 500", callback_data="popup:500"))
builder.row(InlineKeyboardButton(text="Назад", callback_data="balance"))
return builder.as_markup()
@@ -128,3 +130,11 @@ def tarif_confirm_keyboard(name,amount,classif):
builder.row(InlineKeyboardButton(text="Подтвердить", callback_data=f"confirm:{name}_{classif}_{amount}"))
builder.row(InlineKeyboardButton(text="Отменить",callback_data="buy_subscription"))
return builder.as_markup()
def confirm_popup_keyboard():
"""
Подтверждение пополнения
"""
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text="Теперь иди нахуй", callback_data="balance"))
return builder.as_markup()

View File

@@ -23,14 +23,3 @@ def setup_logger():
logger.addHandler(handler)
return logger
def load_config(config_path='config/config.json'):
"""
Загрузка конфигурации из JSON файла.
"""
if not os.path.exists(config_path):
raise FileNotFoundError(f"Конфигурационный файл не найден: {config_path}")
with open(config_path, 'r') as file:
return json.load(file)

View File

@@ -3,12 +3,9 @@ import uuid
import string
import secrets
import json
from utils.LogCon import setup_logger, load_config
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
config = load_config()
def generate_uuid():