85 Commits

Author SHA1 Message Date
3d6b4353f9 Refactor imports across multiple files to improve code organization and readability.
All checks were successful
CI pipeline / Test & Code Quality (push) Successful in 34s
2026-02-28 23:24:25 +03:00
d0c8dab24a fix imports
Some checks failed
CI pipeline / Test & Code Quality (push) Failing after 19s
2026-02-28 23:01:21 +03:00
31314c9c9b Добавлены методы для работы с настройками авто-модерации, включая получение и установку значений, а также переключение состояний авто-публикации и авто-отклонения. Обновлены соответствующие репозитории и обработчики для интеграции новых функций в админ-панели.
Some checks are pending
CI pipeline / Test & Code Quality (push) Waiting to run
2026-02-28 22:21:29 +03:00
694cf1c106 Добавлены новые методы для получения статистики постов пользователей, информации о последних постах и количестве банов. Обновлены запросы в репозиториях для сортировки пользователей по дате бана. Исправлены вызовы функций форматирования сообщений для администраторов. Обновлены тесты для проверки новых функциональностей. 2026-02-28 21:30:08 +03:00
73c36061c7 one more fix 2026-02-02 00:54:23 +03:00
d87d4e492e fix linter, fix ci, fix tests 2026-02-02 00:46:44 +03:00
68041037bd Merge remote-tracking branch 'origin/master' into fix-1 2026-02-02 00:41:51 +03:00
561c9074dd style: isort + black 2026-02-02 00:13:33 +03:00
2a09971628 Merge remote-tracking branch 'origin/master' into dev-13 2026-02-02 00:12:09 +03:00
5ff66993fa fix black 2026-02-01 23:05:46 +03:00
9a6ab9a045 fix isort 2026-02-01 23:04:32 +03:00
f8962225ee fix quality code 2026-02-01 23:03:23 +03:00
731e68a597 import fix 2026-02-01 22:49:25 +03:00
a5faa4bdc6 Переписал почти все тесты
feat: улучшено логирование и обработка скорингов в PostService и RagApiClient

- Добавлены отладочные сообщения для передачи скорингов в функции обработки постов.
- Обновлено логирование успешного получения скорингов из RAG API с дополнительной информацией.
- Оптимизирована обработка скорингов в функции get_text_message для улучшения отладки.
- Обновлены тесты для проверки новых функциональных возможностей и обработки ошибок.
2026-01-30 00:55:47 +03:00
35767c289c fix: улучшена проверка данных из RAG API в методе получения статистики
- Упрощена логика проверки наличия данных из API, убраны лишние переменные.
- Обновлен расчет общего количества примеров для корректного отображения статистики.
2026-01-28 01:02:21 +03:00
7d173e3474 feat: улучшена обработка статистики RAG API в админ-панели
- Добавлена проверка наличия данных из API для отображения статуса модели и статистики векторного хранилища.
- Реализован fallback на синхронные данные, если API недоступен.
- Обновлено описание метода получения статистики в RagApiClient для уточнения использования endpoint /stats.
2026-01-28 00:23:37 +03:00
5d7b051554 feat: улучшена обработка постов и медиагрупп с добавлением статуса "declined"
- Реализовано обновление статуса постов на "declined" для одиночных сообщений и медиагрупп.
- Оптимизирована фоновая обработка постов, включая получение и обработку ML-скоров.
- Обновлены обработчики для немедленного ответа пользователю при отправке постов.
- Добавлены логирование ошибок для улучшения отладки.
2026-01-27 22:10:04 +03:00
be8af704ba feat: добавлен функционал для извлечения и отправки описания PR в Telegram
- Реализована возможность получения тела последнего объединенного PR по коммиту в GitHub Actions.
- Добавлен шаг для отправки описания PR в важные логи через Telegram.
- Обновлены тесты для проверки нового функционала и улучшения логики обработки сообщений.
2026-01-26 22:40:05 +03:00
feee7f010c refactor: обновление системы ML-скоринга и переход на RAG API
- Обновлен Dockerfile для использования Alpine вместо Slim, улучшая размер образа.
- Удален устаревший RAGService и добавлен RagApiClient для работы с внешним RAG API.
- Обновлены переменные окружения в env.example для настройки нового RAG API.
- Обновлен ScoringManager для интеграции с RagApiClient.
- Упрощена структура проекта, удалены ненужные файлы и зависимости, связанные с векторным хранилищем.
- Обновлены обработчики и функции для работы с новым API, включая получение статистики и обработку ошибок.
2026-01-26 22:03:15 +03:00
7f6f0f028c feat: интеграция ML-скоринга с использованием RAG и DeepSeek
- Обновлен Dockerfile для установки необходимых зависимостей.
- Добавлены новые переменные окружения для настройки ML-скоринга в env.example.
- Реализованы методы для получения и обновления ML-скоров в AsyncBotDB и PostRepository.
- Обновлены обработчики публикации постов для интеграции ML-скоринга.
- Добавлен новый обработчик для получения статистики ML-скоринга в админ-панели.
- Обновлены функции для форматирования сообщений с учетом ML-скоров.
2026-01-26 18:40:38 +03:00
e2b1353408 feat: добавлена система миграций БД и CI/CD пайплайны
- Создана система отслеживания миграций (MigrationRepository, таблица migrations)
- Добавлен скрипт apply_migrations.py для автоматического применения миграций
- Созданы CI/CD пайплайны (.github/workflows/ci.yml, deploy.yml)
- Обновлена документация по миграциям в database-patterns.md
- Миграции применяются автоматически при деплое в продакшн
2026-01-25 23:17:09 +03:00
5a90591564 Добавлен асинхронный механизм обработки медиагрупп в PrivateHandlers и улучшен AlbumMiddleware для более эффективного сбора сообщений.
- Реализована фоновая обработка медиагрупп, позволяющая пользователю получать ответ сразу, пока происходит сбор сообщений.
- Введен класс `AlbumGetter` для получения полной медиагруппы с использованием событий.
- Обновлены методы в `AlbumMiddleware` для поддержки нового функционала и улучшения логики обработки сообщений.
2026-01-24 01:35:36 +03:00
0e2aef8c03 Добавлен функционал для работы с медиагруппами и улучшена обработка сообщений
- Реализованы методы для добавления связи между постами и сообщениями в `PostRepository` и `AsyncBotDB`.
- Обновлены обработчики публикации постов для корректной работы с медиагруппами, включая удаление и уведомление авторов.
- Улучшена логика обработки сообщений в `AlbumMiddleware` для более эффективного сбора медиагрупп.
- Обновлены тесты для проверки нового функционала и обработки ошибок.
2026-01-24 01:23:35 +03:00
fecac6091e Добавлен функционал для работы с S3 хранилищем и обновление контента опубликованных постов
- В `env.example` добавлены настройки для S3 хранилища.
- Обновлен файл зависимостей `requirements.txt`, добавлена библиотека `aioboto3` для работы с S3.
- В `PostRepository` и `AsyncBotDB` реализованы методы для обновления и получения контента опубликованных постов.
- Обновлены обработчики публикации постов для сохранения идентификаторов опубликованных сообщений и их контента.
- Реализована логика сохранения медиафайлов в S3 или на локальный диск в зависимости от конфигурации.
- Обновлены тесты для проверки нового функционала.
2026-01-23 23:19:16 +03:00
7269130777 Рефакторизация процесса блокировки пользователей в обработчиках callback
- Обновлена ​​функция `process_ban_user`, теперь в качестве параметра для получения сведений о пользователе используется `bot_db`.

- Улучшена обработка ошибок в сценариях, когда пользователь не найден.

- Введен единый формат отображения информации о пользователе с помощью `format_user_info`.

- Изменено управление состоянием в соответствии с новым алгоритмом ожидания сведений о блокировке.
2026-01-23 14:02:53 +03:00
477e2666a3 Добавлено поле ban_author в модель BlacklistUser и соответствующие изменения в базе данных для отслеживания автора блокировки пользователя. Обновлены методы работы с черным списком в AsyncBotDB и BlacklistRepository, а также обработка блокировок в AdminService и BanService. Обновлены тесты для проверки новых функциональностей. 2026-01-23 13:38:48 +03:00
89022aedaf Реализован функцоинал хранения сырых текстов поста в базе данных. Оформление поста происходит непосредственно перед его отправкой в канал.
- Реализованы методы `get_post_text_and_anonymity_by_message_id` и `get_post_text_and_anonymity_by_helper_id` в `PostRepository` для получения текста поста и флага анонимности.
- Обновлена модель `TelegramPost`, добавлено поле `is_anonymous`.
- Изменена схема базы данных для включения поля `is_anonymous` в таблицу `post_from_telegram_suggest`.
- Обновлены функции публикации постов в `PostPublishService` для учета анонимности.
- Добавлены тесты для проверки новых функций и корректности работы с анонимностью.
2026-01-23 12:12:21 +03:00
34251507da fix problems 2026-01-23 00:37:09 +03:00
03ed2bcf4e Обновлена ​​обработка статуса медиагрупп и улучшены интеграционные тесты
- Реализовано обновление статуса медиагрупп в `PostPublishService` при отклонении медиагрупп.

- Добавлены интеграционные тесты для обновления статусов постов и медиагрупп в `test_post_repository_integration.py

- Улучшен фиктивный репозиторий в `conftest_post_repository.py` для поддержки новых методов обновления статуса.

- Обновлены существующие тесты для проверки корректной обработки статуса постов и медиагрупп.
2026-01-22 23:52:48 +03:00
09e894e48f Обновление управления статусами сообщений и схемы базы данных
- Добавлены методы в `AsyncBotDB` и `PostRepository` для обновления статусов сообщений по идентификатору сообщения и для групп медиафайлов.

- Добавлено поле `status` в модель `TelegramPost` и обновлена ​​схема базы данных, чтобы включить это поле со значением по умолчанию 'suggest'.

- Обновлен `PostPublishService` для установки статусов сообщений на 'approved' или 'declined' в процессе публикации.
2026-01-22 23:37:27 +03:00
a0a7a47c8d Refactor Docker configuration and improve database initialization
- Updated `.dockerignore` to streamline ignored files and directories, focusing on essential components.
- Removed obsolete `Dockerfile.bot` to simplify the build process.
- Enhanced `run_helper.py` with a new `init_db` function to initialize the SQLite database if it doesn't exist, improving setup reliability.
- Removed the `/status` endpoint from `server_prometheus.py` to clean up unused functionality and improve code clarity.
2025-09-16 18:43:05 +03:00
31e29cdec0 Update banned users handling with async support and improved date parsing
- Modified `change_page` function in `callback_handlers.py` to use async methods for retrieving banned users and their buttons.
- Enhanced `get_banned_users_list` in `helper_func.py` to handle string timestamps and various date formats, ensuring robust date parsing.
- Added a new test case in `test_utils.py` to validate the handling of string timestamps in the banned users list retrieval.
2025-09-08 23:19:19 +03:00
5f6882d348 Implement audio record management features in AsyncBotDB and AudioRepository
- Added methods to delete audio moderation records and retrieve all audio records in async_db.py.
- Enhanced AudioRepository with functionality to delete audio records by file name and retrieve all audio message records.
- Improved logging for audio record operations to enhance monitoring and debugging capabilities.
- Updated related handlers to ensure proper integration of new audio management features.
2025-09-05 01:31:50 +03:00
fc0517c011 Enhance bot functionality with new features and improvements
- Added a new `/status` endpoint in `server_prometheus.py` to provide process status information, including uptime and resource usage metrics.
- Implemented a PID manager in `run_helper.py` to track the bot's process, improving monitoring capabilities.
- Introduced a method to delete audio moderation records in `audio_repository.py`, enhancing database management.
- Updated voice message handling in callback handlers to ensure proper deletion of audio moderation records.
- Improved error handling and logging in various services, ensuring better tracking of media processing and file downloads.
- Refactored media handling functions to streamline operations and improve code readability.
- Enhanced metrics tracking for file downloads and media processing, providing better insights into bot performance.
2025-09-04 00:46:45 +03:00
ae7bd476bb Refactor metrics handling and remove scheduler
- Removed the metrics scheduler functionality from the bot, transitioning to real-time metrics updates via middleware.
- Enhanced logging for metrics operations across various handlers to improve monitoring and debugging capabilities.
- Integrated metrics tracking for user activities and database errors, providing better insights into bot performance.
- Cleaned up code by removing obsolete comments and unused imports, improving overall readability and maintainability.
2025-09-03 19:18:04 +03:00
650acd5bce Add cancel ban process handler in admin handlers
- Introduced a new handler for canceling the ban process in `admin_handlers.py`, allowing users to easily abort ongoing ban actions.
- Enhanced error handling and logging for the cancellation process to improve user experience and debugging.
- Removed obsolete comments and cleaned up the code for better readability in the admin handlers.
- Updated metrics middleware to streamline event processing and improve logging clarity, ensuring comprehensive metrics collection for all events.
2025-09-03 17:35:51 +03:00
fe06008930 Enhance metrics handling and logging in bot
- Integrated metrics scheduler start and stop functionality in `run_helper.py` for better resource management.
- Improved logging for metrics server operations in `server_prometheus.py`, ensuring clearer error reporting and status updates.
- Updated metrics middleware to collect comprehensive metrics for all event types, enhancing monitoring capabilities.
- Added active user metrics tracking in `admin_handlers.py` to provide insights on user engagement.
- Refactored command and callback handling in `metrics_middleware.py` to improve clarity and error handling.
2025-09-03 16:16:14 +03:00
c8c7d50cbb Refactor metrics handling and improve logging
- Removed the MetricsManager initialization from `run_helper.py` to avoid duplication, as metrics are now handled in `main.py`.
- Updated logging levels in `server_prometheus.py` and `metrics_middleware.py` to use debug instead of info for less critical messages.
- Added metrics configuration to `BaseDependencyFactory` for better management of metrics settings.
- Deleted the obsolete `metrics_exporter.py` file to streamline the codebase.
- Updated various tests to reflect changes in the metrics handling and ensure proper functionality.
2025-09-03 00:33:20 +03:00
6fcecff97c Refactor voice handler and update welcome message
- Reintroduced the cancel handler registration in the voice handler for private chats, ensuring users can cancel interactions with the bot.
- Updated the welcome message in the messages utility to reflect the new voice bot access method and added instructions for using the /restart command.
- Improved clarity in the welcome message by including a link to the bot's help command and contact information for user support.
2025-09-02 22:42:33 +03:00
1ab427a7ba Enhance admin handlers with improved logging and error handling
- Added detailed logging for user ban processing in `process_ban_target` and `process_ban_reason` functions, including user data and error messages.
- Improved error handling for user input validation and database interactions.
- Updated `return_to_admin_menu` function to log user return actions.
- Enhanced media group handling in `PostPublishService` with better error logging and author ID retrieval.
- Added new button options in voice handlers and updated keyboard layouts for improved user interaction.
- Refactored album middleware to better handle media group messages and added documentation for clarity.
2025-09-02 22:20:34 +03:00
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
013892dcb7 Remove obsolete configuration management and test settings files
- Deleted the `config.py` file responsible for managing bot configuration via environment variables and `.env` files, as it is no longer needed.
- Removed the `test_settings.ini` file used for testing, which contained mock configuration data.
- Cleaned up the project structure by eliminating unused files to enhance maintainability.
2025-09-01 20:30:10 +03:00
3a7b0f6219 Add voice bot welcome tracking functionality
- Implemented methods to check and mark if a user has received a welcome message from the voice bot in both async and synchronous database classes.
- Updated database schema to include a new field for tracking welcome message status.
- Enhanced voice handler to utilize the new tracking methods, improving user interaction flow and engagement metrics.
2025-09-01 19:43:46 +03:00
2d40f4496e Update voice bot functionality and clean up project structure
- Added voice message handling capabilities, including saving and deleting audio messages via callback queries.
- Refactored audio record management in the database to remove unnecessary fields and streamline operations.
- Introduced new keyboard options for voice interactions in the bot.
- Updated `.gitignore` to include voice user files for better project organization.
- Removed obsolete voice bot handler files to simplify the codebase.
2025-09-01 19:17:05 +03:00
d128e54694 Refactor project structure and remove obsolete files
- Deleted the Makefile, `README_TESTING.md`, and several deployment scripts to streamline the project.
- Updated `.dockerignore` to exclude unnecessary development files.
- Adjusted database schema comments for clarity.
- Refactored metrics handling in middleware for improved command extraction and logging.
- Enhanced command mappings for buttons and callbacks in constants for better maintainability.
- Start refactor voice bot
2025-09-01 00:54:10 +03:00
98d12be67d Initial commit for dev-8 branch with all current changes 2025-08-31 15:35:42 +03:00
5c2f9e501d Enhance user activity tracking in private handlers
- Added functionality to log user messages and update user activity in the suggest router, improving user engagement metrics.
2025-08-31 11:17:49 +03:00
8f338196b7 Refactor Docker and configuration files for improved structure and functionality
- Updated `.dockerignore` to include additional development and temporary files, enhancing build efficiency.
- Modified `.gitignore` to remove unnecessary entries and streamline ignored files.
- Enhanced `docker-compose.yml` with health checks, resource limits, and improved environment variable handling for better service management.
- Refactored `Dockerfile.bot` to utilize a multi-stage build for optimized image size and security.
- Improved `Makefile` with new commands for deployment, migration, and backup, along with enhanced help documentation.
- Updated `requirements.txt` to include new dependencies for environment variable management.
- Refactored metrics handling in the bot to ensure proper initialization and collection.
2025-08-29 23:15:06 +03:00
f097d69dd4 Enhance Makefile and update metrics handling in bot
- Added new commands in the Makefile for restarting individual services: `restart-bot`, `restart-prometheus`, and `restart-grafana`.
- Updated Prometheus and Grafana dashboard expressions for better metrics aggregation.
- Removed the `main_with_metrics.py` file and integrated metrics handling directly into the main bot file.
- Refactored middleware to improve metrics tracking and error handling across message and callback processing.
- Optimized metrics recording with enhanced bucket configurations for better performance monitoring.
2025-08-29 18:23:17 +03:00
c68db87901 Refactor project structure and enhance Docker support
- Removed unnecessary `__init__.py` and `Dockerfile` to streamline project organization.
- Updated `.dockerignore` and `.gitignore` to improve exclusion patterns for build artifacts and environment files.
- Enhanced `Makefile` with new commands for managing Docker containers and added help documentation.
- Introduced `pyproject.toml` for better project metadata management and dependency tracking.
- Updated `requirements.txt` to reflect changes in dependencies for metrics and monitoring.
- Refactored various handler files to improve code organization and maintainability.
2025-08-29 16:49:28 +03:00