Files
postbot/app/services/users.py
2025-08-19 05:13:16 +09:00

31 lines
1.1 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 typing import Optional
from sqlalchemy import select
from app.db.session import async_session_maker
from app.models.user import User
async def get_or_create_user(tg_user_id: int, username: Optional[str] = None) -> User:
"""Получить или создать пользователя.
Args:
tg_user_id: ID пользователя в Telegram
username: Имя пользователя в Telegram
Returns:
User: Объект пользователя
"""
async with async_session_maker() as session:
# Пробуем найти пользователя
query = select(User).where(User.tg_user_id == tg_user_id)
result = await session.execute(query)
user = result.scalar_one_or_none()
if not user:
# Создаем нового пользователя
user = User(tg_user_id=tg_user_id, username=username)
session.add(user)
await session.commit()
await session.refresh(user)
return user