6 Commits

Author SHA1 Message Date
FrigaT
41986987b1 чистка кода
All checks were successful
CI / build-test (push) Successful in 1m2s
2025-12-16 16:19:50 +03:00
246a5cb278 Удалено отключение бота
All checks were successful
CI / build-test (push) Successful in 35s
Release / pack-and-publish (release) Successful in 37s
2025-12-10 20:54:18 +03:00
644749929e Убивает клиента ТГ, если он запущен вторым по токену
All checks were successful
CI / build-test (push) Successful in 37s
Release / pack-and-publish (release) Successful in 41s
2025-12-10 20:31:10 +03:00
8528b814d8 Удалить TZ.md
All checks were successful
CI / build-test (push) Successful in 30s
2025-12-07 12:04:50 +03:00
d60bef7070 фикс
All checks were successful
CI / build-test (push) Successful in 29s
Release / pack-and-publish (release) Successful in 31s
2025-12-07 11:28:11 +03:00
7556b3d638 Доработаны паттерны команд 2025-12-07 11:17:21 +03:00
11 changed files with 44 additions and 204 deletions

View File

@@ -17,21 +17,21 @@ public interface IMessengerAdapter
/// <summary>
/// Отправить текстовое сообщение в чат.
/// </summary>
Task<string?> SendTextAsync(string chatId,
string text,
Task<string?> SendTextAsync(string chatId,
string text,
MessageFormat format = MessageFormat.Plain,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
string? messageId = null,
string? messageId = null,
CancellationToken ct = default
);
/// <summary>
/// Отправить файл в чат.
/// </summary>
Task SendFileAsync(string chatId,
FileDescriptor file,
string? caption = null,
Task SendFileAsync(string chatId,
FileDescriptor file,
string? caption = null,
MessageFormat? captionFormat = null,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,

View File

@@ -1,6 +1,4 @@
using BotPages.Core.Abstractions;
namespace BotPages.Core;
namespace BotPages.Core;
/// <summary>
/// Данные чата.

View File

@@ -1,6 +1,5 @@
using BotPages.Core.Abstractions;
using BotPages.Core.Context;
using BotPages.Core.Messaging;
namespace BotPages.Core;

View File

@@ -11,8 +11,8 @@ public static class PageContextAdapterExtensions
/// <summary>
/// Отправить текстовое сообщение.
/// </summary>
public static Task<string?> SendTextAsync(this PageContext ctx,
string text,
public static Task<string?> SendTextAsync(this PageContext ctx,
string text,
MessageFormat format = MessageFormat.Plain,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
@@ -23,17 +23,17 @@ public static class PageContextAdapterExtensions
/// <summary>
/// Отправить файл.
/// </summary>
public static Task SendFileAsync(this PageContext ctx,
FileDescriptor file,
string? caption = null,
public static Task SendFileAsync(this PageContext ctx,
FileDescriptor file,
string? caption = null,
MessageFormat? captionFormat = null,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
CancellationToken ct = default
)
=> ctx.Adapter.SendFileAsync(chatId: ctx.Update.Chat.Id,
file: file,
caption: caption,
=> ctx.Adapter.SendFileAsync(chatId: ctx.Update.Chat.Id,
file: file,
caption: caption,
captionFormat: captionFormat,
inline: inline,
reply: reply,

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BotPages.Core.Routing;
namespace BotPages.Core.Routing;
/// <summary>
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.

View File

@@ -17,8 +17,6 @@ internal sealed class CommandsRegistry
/// </summary>
public CommandsRegistry Map<TPage>(string commandTemplate, bool publish = false, string? description = null) where TPage : Page
{
var pattern = ToRegex(commandTemplate);
return Map(commandTemplate, (ctx, args, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct), publish, description);
}
@@ -67,15 +65,25 @@ internal sealed class CommandsRegistry
/// </summary>
private static Regex ToRegex(string template)
{
var escaped = Regex.Escape(template)
.Replace("\\{", "{").Replace("\\}", "}");
var pattern = "^" + Regex.Replace(escaped, @"\{(\w+)(\?)?\}", m =>
// Заменяем все {name} и {name?} на регулярные группы
var pattern = "^" + Regex.Replace(template, @"\s*\{(\w+)(\?)?\}", m =>
{
var name = m.Groups[1].Value;
var optional = m.Groups[2].Success;
return optional ? $"(?<{name}>\\S+)?" : $"(?<{name}>\\S+)";
}) + "$";
var argPattern = $"(?:\"(?<{name}>[^\"]+)\"|(?<{name}>\\S+))";
if (optional)
{
// необязательный параметр: пробел + значение целиком необязательны
return $"(?:\\s+{argPattern})?";
}
else
{
// обязательный параметр: пробел обязателен
return $"\\s+{argPattern}";
}
}) + "\\s*$"; // допускаем пробелы/переносы в конце
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}

View File

@@ -31,7 +31,7 @@ internal sealed class RoutesRegistry
internal void Map(Type? type)
{
foreach(var attr in type.GetCustomAttributes<RouteAttribute>(inherit: true))
foreach (var attr in type.GetCustomAttributes<RouteAttribute>(inherit: true))
{
_routes.Add(attr.Template, type);
}

View File

@@ -66,6 +66,10 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
if (mapped is not null)
await onUpdate(mapped);
if (update.CallbackQuery is not null)
{
await _.AnswerCallbackQuery(update.CallbackQuery.Id);
}
},
errorHandler: async (_, ex, ct2) =>
@@ -86,11 +90,11 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
}
/// <inheritdoc />
public async Task<string?> SendTextAsync(string chatId, string text,
public async Task<string?> SendTextAsync(string chatId, string text,
MessageFormat format = MessageFormat.Plain,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
string? messageId = null,
string? messageId = null,
CancellationToken ct = default)
{
if (_client is null)
@@ -189,9 +193,9 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
}
/// <inheritdoc />
public async Task SendFileAsync(string chatId,
FileDescriptor file,
string? caption = null,
public async Task SendFileAsync(string chatId,
FileDescriptor file,
string? caption = null,
MessageFormat? captionFormat = null,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,

View File

@@ -54,8 +54,8 @@ public sealed class DetailsPage : StatefullPage<string>
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
}
internal static string Command => "/create_request {title}";
internal static string CommandDescription => "создание заявки /create_request {title";
internal static string Command => "/create_request {title?}";
internal static string CommandDescription => "создание заявки /create_request {title}";
internal static CommandHandler CommandHandler = async (ctx, args, ct) =>
{
string? title = "";

View File

@@ -1,7 +1,6 @@
using BotPages.Core;
using BotPages.Core.Abstractions;
using BotPages.Core.Messaging;
using BotPages.Core.Routing;
namespace Demo.Pages;
/// <summary>

162
TZ.md
View File

@@ -1,162 +0,0 @@
# Техническое задание
## Проект: BotPages
### 1. Общая информация
- **Название:** BotPages
- **Цель:** Создание библиотеки (NuGetпакета) для управления страницами в ботах (Telegram, VK, Discord, WhatsApp и др.), позволяющей строить логику без жёсткой привязки к конкретному API.
- **Платформа:** .NET 8
- **Артефакты:**
- `BotPages.Core` — ядро, независимое от транспорта.
- `BotPages.Telegram` — адаптер для Telegram.
- В будущем: адаптеры для VK, Discord, WhatsApp.
- **Демо:** `Demo.exe` — демонстрация работы (создание заявки через несколько страниц, кнопки, файлы).
---
### 2. Основные понятия
- **Page** — класс, отвечающий за состояние экрана бота.
- `Page` — базовый класс.
- `Page<TArguments>` — страница с аргументами.
- **Контекст:**
- `UserContext` — данные пользователя (UserId, MessengerType).
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
- `PageContext` — объединяет UserContext, ChatContext, состояние, навигацию, файлы.
- **Состояние:**
- `IStateStorage` — универсальный интерфейс хранения.
- Базовая реализация: InMemory.
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId)`.
- История состояний: опционально (None, LastN, TimeWindow, Full).
---
### 3. Жизненный цикл страницы
- Методы (все async, с `CancellationToken`):
- `OnEnter(ctx)` — вход.
- `OnUpdate(ctx, update)` — общий обработчик.
- `OnText(ctx, text)` — текстовые сообщения.
- `OnFile(ctx, file)` — файлы.
- `OnButton(ctx, action)` — кнопки.
- `OnLeave(ctx)` — выход.
- `OnError(ctx, exception)` — ошибки.
- `OnTimeout(ctx, timeoutInfo)` — таймауты.
- Прогресс фоновых операций:
- `StartProgress()`, `UpdateProgress(percent)` + событие обновления.
---
### 4. Навигация
- Императивный API:
```csharp
ctx.GoTo<CitySelectionPage>();
ctx.GoTo<ConfirmationPage>(new ConfirmationArgs { PhotoId = photoId });
ctx.GoTo<DetailsPage>(args => { args.Photo = photoId; });
ctx.ReplaceWith<MainPage>();
ctx.Back();
```
- Декларативный роутинг:
- Атрибуты `[Route("order/create")]`.
- Реестр `routes.Map<CreateOrderPage>("order/create")`.
- Проверка конфликтов при старте.
- Стек навигации: отдельный пакет `BotPages.Navigation.Stack`.
---
### 5. Команды
- Команды имеют приоритет над событиями страниц.
- Поддержка шаблонов:
```csharp
app.Commands.Map("/start").To<WelcomePage>();
app.Commands.Map("/open {page} {id?}")
.To(ctx => ctx.GoToByName(page, new { id }));
```
- Возможность указать страницу, которая открывается при вводе команды.
---
### 6. Файлы
- **FileDescriptor:**
- `Id`, `Name`, `Extension`, `Size`, `Mime`, `Type(enum)`, `SourceMessenger`, `GetStreamAsync()`, `Checksum?`.
- Отправка:
```csharp
await ctx.Chat.SendFileAsync(file, caption: "Документ");
await ctx.Chat.Files.BeginAlbum().Add(file1).Add(file2).SendAsync();
```
- Альбомы, сжатие — на уровне адаптера.
- Метаданные файлов — временно в контексте, экспорт в состояние вручную.
---
### 7. Адаптеры
- Интерфейс `IMessengerAdapter`:
- `SendMessage`, `EditMessage`, `DeleteMessage`, `SendFile`, `SendAlbum`.
- `ReceiveUpdate`.
- `GetChat`, `GetFileStream`.
- `AnswerCallback`, `SetTypingIndicator`.
- Telegram: первая реализация.
- Поддержка **Webhook** и **Polling** (выбор конфигом).
---
### 8. Capabilities
- В `ChatContext.Capabilities`:
- `SupportsInlineButtons`, `SupportsReplyButtons`, `SupportsAlbums`, `SupportsFormattingMarkdown`, `SupportsFormattingHtml`, `MaxMessageLength`.
- Разработчик может проверять возможности.
- Адаптер всегда деградирует и логирует `Warn`.
---
### 9. Логирование
- Уровни: `Info`, `Warn`, `Critical`.
- Примеры:
- Info: вход на страницу, прогресс.
- Warn: деградация возможностей.
- Critical: падение хранилища.
---
### 10. Middleware
- Интерфейс:
```csharp
public interface IUpdateMiddleware
{
Task InvokeAsync(UpdateContext ctx, Func<Task> next, CancellationToken ct);
}
```
- Пример:
```csharp
app.AddMiddleware<LoggingMiddleware>();
app.AddMiddleware<ErrorMiddleware>(params);
```
- Порядок регистрации = порядок выполнения.
- Middleware только для входящих обновлений.
---
### 11. Дефолтная страница
- Конфигурация:
```csharp
app.UseDefaultPage<WelcomePage>();
```
- Одна дефолтная страница для всех мессенджеров.
- Условия не нужны.
---
### 12. Demo.exe
- Сценарий: создание заявки.
- Страницы:
1. **StartPage** — приветствие, кнопка «Создать заявку».
2. **TitlePage** — ввод текста.
3. **DetailsPage** — доп. поля, inline/reply кнопки.
4. **FilesPage** — загрузка файлов, просмотр списка.
5. **ConfirmPage** — подтверждение заявки.
6. **SubmitPage** — отправка, итоговое сообщение.
---
### 13. TODO (будущие версии)
- Поддержка модальных страниц со стеком.
- Расширенные Capabilities (rate limits, threads).
- ViewDSL как надстройка над контекстом.
- Crosstransport identity.
- Расширенные таймауты и политики отката.