Files
telegram-helper-bot/database/repositories/message_repository.py
Andrey 1c6a37bc12 Enhance bot functionality and refactor database interactions
- Added `ca-certificates` installation to Dockerfile for improved network security.
- Updated health check command in Dockerfile to include better timeout handling.
- Refactored `run_helper.py` to implement proper signal handling and logging during shutdown.
- Transitioned database operations to an asynchronous model in `async_db.py`, improving performance and responsiveness.
- Updated database schema to support new foreign key relationships and optimized indexing for better query performance.
- Enhanced various bot handlers to utilize async database methods, improving overall efficiency and user experience.
- Removed obsolete database and fix scripts to streamline the project structure.
2025-09-02 18:22:02 +03:00

45 lines
2.0 KiB
Python
Raw Permalink 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
from typing import Optional
from database.base import DatabaseConnection
from database.models import UserMessage
class MessageRepository(DatabaseConnection):
"""Репозиторий для работы с сообщениями пользователей."""
async def create_tables(self):
"""Создание таблицы сообщений пользователей."""
query = '''
CREATE TABLE IF NOT EXISTS user_messages (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
message_text TEXT,
user_id INTEGER,
telegram_message_id INTEGER NOT NULL,
date INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES our_users (user_id) ON DELETE CASCADE
)
'''
await self._execute_query(query)
self.logger.info("Таблица сообщений пользователей создана")
async def add_message(self, message: UserMessage) -> None:
"""Добавление сообщения пользователя."""
if message.date is None:
message.date = int(datetime.now().timestamp())
query = """
INSERT INTO user_messages (message_text, user_id, telegram_message_id, date)
VALUES (?, ?, ?, ?)
"""
params = (message.message_text, message.user_id, message.telegram_message_id, message.date)
await self._execute_query(query, params)
self.logger.info(f"Новое сообщение добавлено: telegram_message_id={message.telegram_message_id}")
async def get_user_by_message_id(self, message_id: int) -> Optional[int]:
"""Получение пользователя по message_id."""
query = "SELECT user_id FROM user_messages WHERE telegram_message_id = ?"
rows = await self._execute_query_with_result(query, (message_id,))
row = rows[0] if rows else None
return row[0] if row else None