10 KiB
10 KiB
📁 Структура проекта
Подробное описание организации кода в ChatBot.
🌳 Дерево проекта
ChatBot/
├── .gitea/
│ └── workflows/
│ └── build.yml # CI/CD pipeline (SonarQube)
├── ChatBot/ # Основной проект
│ ├── Common/
│ │ └── Constants/
│ │ ├── AIResponseConstants.cs
│ │ └── ChatTypes.cs
│ ├── Data/
│ │ ├── Interfaces/
│ │ │ └── IChatSessionRepository.cs
│ │ ├── Repositories/
│ │ │ └── ChatSessionRepository.cs
│ │ └── ChatBotDbContext.cs
│ ├── Migrations/
│ │ └── [EF Core миграции]
│ ├── Models/
│ │ ├── Configuration/
│ │ │ ├── Validators/
│ │ │ ├── AISettings.cs
│ │ │ ├── DatabaseSettings.cs
│ │ │ ├── OllamaSettings.cs
│ │ │ └── TelegramBotSettings.cs
│ │ ├── Dto/
│ │ │ └── ChatMessage.cs
│ │ ├── Entities/
│ │ │ ├── ChatMessageEntity.cs
│ │ │ └── ChatSessionEntity.cs
│ │ └── ChatSession.cs
│ ├── Prompts/
│ │ └── system-prompt.txt # AI промпт
│ ├── Properties/
│ │ └── launchSettings.json
│ ├── Services/
│ │ ├── HealthChecks/
│ │ │ ├── OllamaHealthCheck.cs
│ │ │ └── TelegramBotHealthCheck.cs
│ │ ├── Interfaces/
│ │ │ ├── IAIService.cs
│ │ │ ├── IHistoryCompressionService.cs
│ │ │ ├── IOllamaClient.cs
│ │ │ ├── ISessionStorage.cs
│ │ │ └── ITelegramBotClientWrapper.cs
│ │ ├── Telegram/
│ │ │ ├── Commands/
│ │ │ │ ├── ClearCommand.cs
│ │ │ │ ├── CommandAttribute.cs
│ │ │ │ ├── CommandRegistry.cs
│ │ │ │ ├── HelpCommand.cs
│ │ │ │ ├── ReplyInfo.cs
│ │ │ │ ├── SettingsCommand.cs
│ │ │ │ ├── StartCommand.cs
│ │ │ │ ├── StatusCommand.cs
│ │ │ │ ├── TelegramCommandBase.cs
│ │ │ │ ├── TelegramCommandContext.cs
│ │ │ │ └── TelegramCommandProcessor.cs
│ │ │ ├── Interfaces/
│ │ │ │ ├── ITelegramBotService.cs
│ │ │ │ ├── ITelegramCommand.cs
│ │ │ │ ├── ITelegramCommandProcessor.cs
│ │ │ │ ├── ITelegramErrorHandler.cs
│ │ │ │ └── ITelegramMessageHandler.cs
│ │ │ └── Services/
│ │ │ ├── BotInfoService.cs
│ │ │ ├── TelegramBotService.cs
│ │ │ ├── TelegramErrorHandler.cs
│ │ │ ├── TelegramMessageHandler.cs
│ │ │ └── TelegramMessageSender.cs
│ │ ├── AIService.cs
│ │ ├── ChatService.cs
│ │ ├── DatabaseInitializationService.cs
│ │ ├── DatabaseSessionStorage.cs
│ │ ├── HistoryCompressionService.cs
│ │ ├── InMemorySessionStorage.cs
│ │ ├── ModelService.cs
│ │ ├── OllamaClientAdapter.cs
│ │ ├── SystemPromptService.cs
│ │ └── TelegramBotClientWrapper.cs
│ ├── appsettings.json
│ ├── appsettings.Development.json
│ ├── ChatBot.csproj
│ └── Program.cs
├── ChatBot.Tests/ # Тестовый проект
│ ├── Common/
│ ├── Configuration/
│ ├── Data/
│ ├── Integration/
│ ├── Models/
│ ├── Program/
│ ├── Services/
│ ├── Telegram/
│ └── ChatBot.Tests.csproj
├── docs/ # Документация
├── .gitignore
├── .gitattributes
├── ChatBot.sln
├── LICENSE.txt
└── README.md
📂 Основные папки
/Common
Общие константы и утилиты.
Constants/
AIResponseConstants.cs- Константы для AI ответовEmptyResponseMarker = "{empty}"DefaultErrorMessage
ChatTypes.cs- Типы чатовPrivate,Group,Supergroup,Channel
/Data
Слой доступа к данным.
Interfaces/
IChatSessionRepository.cs- Интерфейс репозитория
Repositories/
ChatSessionRepository.cs- Реализация репозитория
Root:
ChatBotDbContext.cs- EF Core контекст
/Models
Модели данных и конфигурация.
Configuration/
- Settings классы для конфигурации
- Validators/ - FluentValidation валидаторы
Dto/
ChatMessage.cs- DTO для сообщений
Entities/
ChatSessionEntity.cs- Сущность сессииChatMessageEntity.cs- Сущность сообщения
Root:
ChatSession.cs- Доменная модель сессии
/Services
Бизнес-логика приложения.
HealthChecks/
OllamaHealthCheck.cs- Проверка OllamaTelegramBotHealthCheck.cs- Проверка Telegram
Interfaces/
- Интерфейсы всех сервисов
Telegram/
- Commands/ - Реализация команд бота
- Interfaces/ - Интерфейсы Telegram сервисов
- Services/ - Реализация Telegram сервисов
Root Services:
AIService.cs- Работа с AIChatService.cs- Управление чатамиHistoryCompressionService.cs- Сжатие историиDatabaseSessionStorage.cs- Хранение в БДInMemorySessionStorage.cs- Хранение в памяти- И другие...
/Migrations
EF Core миграции базы данных.
/Prompts
AI промпты.
system-prompt.txt- Системный промпт для AI
🎯 Naming Conventions
Файлы
- Classes:
PascalCase.cs(например,ChatService.cs) - Interfaces:
IPascalCase.cs(например,IAIService.cs) - Tests:
ClassNameTests.cs
Namespace
namespace ChatBot.Services
namespace ChatBot.Models.Configuration
namespace ChatBot.Data.Repositories
Структура namespace соответствует структуре папок.
Классы
public class ChatService // Service classes
public interface IAIService // Interfaces (I prefix)
public class ChatSession // Models
public class ChatSessionEntity // Entities (Entity suffix)
🔍 Зависимости между слоями
Program.cs
↓
Services/
↓
Data/Repositories
↓
Data/ChatBotDbContext
↓
Models/Entities
Правила:
- Services зависят от Interfaces
- Repositories зависят от Entities
- Models независимы
- Presentation зависит от Services
📦 NuGet пакеты
Основные
<PackageReference Include="Telegram.Bot" Version="22.7.2" />
<PackageReference Include="OllamaSharp" Version="5.4.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.10" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
Логирование
<PackageReference Include="Serilog" Version="4.3.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
Validation
<PackageReference Include="FluentValidation" Version="12.0.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
🧪 Тестовый проект
Структура
ChatBot.Tests/
├── Common/ # Тесты констант
├── Configuration/ # Тесты валидаторов
├── Data/ # Тесты репозиториев и DbContext
├── Integration/ # Интеграционные тесты
├── Models/ # Тесты моделей
├── Services/ # Тесты сервисов
└── Telegram/ # Тесты Telegram функций
Naming Convention
public class ChatServiceTests
{
[Fact]
public void ProcessMessage_ShouldReturnResponse()
[Theory]
[InlineData(...)]
public void Method_Scenario_ExpectedBehavior()
}
🔧 Configuration Files
appsettings.json
Основная конфигурация приложения.
appsettings.Development.json
Переопределения для Development режима.
.env
Локальные переменные окружения (не в git).
launchSettings.json
Настройки запуска для Visual Studio/Rider.
📝 Special Files
Program.cs
Точка входа приложения:
- Конфигурация DI
- Регистрация сервисов
- Инициализация логирования
ChatBot.csproj
Project file:
- Target Framework: net9.0
- Package References
- Build configurations
ChatBot.sln
Solution file для Visual Studio.
🚀 Build Output
bin/
├── Debug/
│ └── net9.0/
├── Release/
│ └── net9.0/
obj/
└── [Промежуточные файлы]