Files
tg_bot_language/services/user_service.py
mamonov.ep 1a02c979d0 Реализован MVP телеграм бота для изучения языков
Основные компоненты:
- База данных (PostgreSQL) с моделями User, Vocabulary, Task
- Интеграция с OpenAI API для перевода слов
- Команды: /start, /add, /vocabulary, /help
- Сервисы для работы с пользователями, словарем и AI

Реализовано:
 Регистрация и приветствие пользователя
 Добавление слов в словарь с автоматическим переводом
 Просмотр личного словаря
 Архитектура проекта с разделением на слои

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-04 11:09:54 +03:00

60 lines
1.9 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 sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from database.models import User, LanguageLevel
from typing import Optional
class UserService:
"""Сервис для работы с пользователями"""
@staticmethod
async def get_or_create_user(session: AsyncSession, telegram_id: int, username: Optional[str] = None) -> User:
"""
Получить пользователя или создать нового
Args:
session: Сессия базы данных
telegram_id: Telegram ID пользователя
username: Username пользователя
Returns:
Объект пользователя
"""
# Попытка найти существующего пользователя
result = await session.execute(
select(User).where(User.telegram_id == telegram_id)
)
user = result.scalar_one_or_none()
if user:
return user
# Создание нового пользователя
new_user = User(
telegram_id=telegram_id,
username=username,
level=LanguageLevel.A1
)
session.add(new_user)
await session.commit()
await session.refresh(new_user)
return new_user
@staticmethod
async def get_user_by_telegram_id(session: AsyncSession, telegram_id: int) -> Optional[User]:
"""
Получить пользователя по Telegram ID
Args:
session: Сессия базы данных
telegram_id: Telegram ID пользователя
Returns:
Объект пользователя или None
"""
result = await session.execute(
select(User).where(User.telegram_id == telegram_id)
)
return result.scalar_one_or_none()