Files
ai-char-bot/repos/user_repo.py
2026-02-02 16:15:17 +03:00

65 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from datetime import datetime, timedelta
from enum import Enum
from aiogram.types import User
from motor.motor_asyncio import AsyncIOMotorClient
class UserStatus:
ALLOWED = "allowed"
DENIED = "denied"
PENDING = "pending"
NONE = "none" # Пользователя нет в базе
class UsersRepo:
def __init__(self, client: AsyncIOMotorClient, db_name="bot_db"):
self.collection = client[db_name]["users"]
async def get_user(self, user_id: int):
return await self.collection.find_one({"user_id": user_id})
async def create_or_update_request(self, user: User):
"""
Обновляет дату последнего запроса и ставит статус PENDING.
Сохраняет всю инфу о юзере.
"""
now = datetime.now()
data = {
"user_id": user.id,
"username": user.username,
"full_name": user.full_name,
"status": UserStatus.PENDING,
"last_request_date": now
}
await self.collection.update_one(
{"user_id": user.id},
{"$set": data},
upsert=True
)
async def set_status(self, user_id: int, status: str):
"""Меняет статус (разрешен/запрещен)"""
await self.collection.update_one(
{"user_id": user_id},
{"$set": {"status": status}}
)
async def can_request_access(self, user_id: int) -> bool:
"""
Проверяет, можно ли отправить запрос (прошло ли 24 часа).
Возвращает True, если пользователя нет или прошло > 24ч.
"""
user = await self.get_user(user_id)
if not user:
return True
last_date = user.get("last_request_date")
if not last_date:
return True
# Проверка на 24 часа
if datetime.now() - last_date > timedelta(hours=24):
return True
return False