Compare commits
7 Commits
v0.3.0
...
41986987b1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41986987b1 | ||
| 246a5cb278 | |||
| 644749929e | |||
| 8528b814d8 | |||
| d60bef7070 | |||
| 7556b3d638 | |||
| 67de9e197a |
@@ -17,21 +17,21 @@ public interface IMessengerAdapter
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение в чат.
|
/// Отправить текстовое сообщение в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<string?> SendTextAsync(string chatId,
|
Task<string?> SendTextAsync(string chatId,
|
||||||
string text,
|
string text,
|
||||||
MessageFormat format = MessageFormat.Plain,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
string? messageId = null,
|
string? messageId = null,
|
||||||
CancellationToken ct = default
|
CancellationToken ct = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл в чат.
|
/// Отправить файл в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendFileAsync(string chatId,
|
Task SendFileAsync(string chatId,
|
||||||
FileDescriptor file,
|
FileDescriptor file,
|
||||||
string? caption = null,
|
string? caption = null,
|
||||||
MessageFormat? captionFormat = null,
|
MessageFormat? captionFormat = null,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
using BotPages.Core.Abstractions;
|
namespace BotPages.Core;
|
||||||
|
|
||||||
namespace BotPages.Core;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Данные чата.
|
/// Данные чата.
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using BotPages.Core.Abstractions;
|
using BotPages.Core.Abstractions;
|
||||||
using BotPages.Core.Context;
|
using BotPages.Core.Context;
|
||||||
using BotPages.Core.Messaging;
|
|
||||||
|
|
||||||
namespace BotPages.Core;
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ public static class PageContextAdapterExtensions
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение.
|
/// Отправить текстовое сообщение.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Task<string?> SendTextAsync(this PageContext ctx,
|
public static Task<string?> SendTextAsync(this PageContext ctx,
|
||||||
string text,
|
string text,
|
||||||
MessageFormat format = MessageFormat.Plain,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
@@ -23,17 +23,17 @@ public static class PageContextAdapterExtensions
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл.
|
/// Отправить файл.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Task SendFileAsync(this PageContext ctx,
|
public static Task SendFileAsync(this PageContext ctx,
|
||||||
FileDescriptor file,
|
FileDescriptor file,
|
||||||
string? caption = null,
|
string? caption = null,
|
||||||
MessageFormat? captionFormat = null,
|
MessageFormat? captionFormat = null,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
CancellationToken ct = default
|
CancellationToken ct = default
|
||||||
)
|
)
|
||||||
=> ctx.Adapter.SendFileAsync(chatId: ctx.Update.Chat.Id,
|
=> ctx.Adapter.SendFileAsync(chatId: ctx.Update.Chat.Id,
|
||||||
file: file,
|
file: file,
|
||||||
caption: caption,
|
caption: caption,
|
||||||
captionFormat: captionFormat,
|
captionFormat: captionFormat,
|
||||||
inline: inline,
|
inline: inline,
|
||||||
reply: reply,
|
reply: reply,
|
||||||
|
|||||||
@@ -1,10 +1,4 @@
|
|||||||
using System;
|
namespace BotPages.Core.Routing;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace BotPages.Core.Routing;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
||||||
|
|||||||
@@ -17,8 +17,6 @@ internal sealed class CommandsRegistry
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public CommandsRegistry Map<TPage>(string commandTemplate, bool publish = false, string? description = null) where TPage : Page
|
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);
|
return Map(commandTemplate, (ctx, args, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct), publish, description);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,12 +47,10 @@ internal sealed class CommandsRegistry
|
|||||||
var match = cmd.Pattern.Match(command);
|
var match = cmd.Pattern.Match(command);
|
||||||
if (match.Success)
|
if (match.Success)
|
||||||
{
|
{
|
||||||
// Собираем аргументы
|
// Собираем именованные группы (без числовых)
|
||||||
var args = cmd.Pattern.GetGroupNames()
|
var args = cmd.Pattern.GetGroupNames()
|
||||||
.Where(n => n != "0")
|
.Where(n => !int.TryParse(n, out _))
|
||||||
.Select(n => new { n, v = match.Groups[n].Value })
|
.ToDictionary(n => n, n => match.Groups[n].Value);
|
||||||
.Where(x => !string.IsNullOrEmpty(x.v))
|
|
||||||
.ToDictionary(x => x.n, x => x.v);
|
|
||||||
|
|
||||||
task = cmd.Handler(ctx, args, ct);
|
task = cmd.Handler(ctx, args, ct);
|
||||||
return true;
|
return true;
|
||||||
@@ -64,14 +60,31 @@ internal sealed class CommandsRegistry
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Универсальный парсер шаблонов: /cmd {a} {b?} {c}
|
||||||
|
/// </summary>
|
||||||
private static Regex ToRegex(string template)
|
private static Regex ToRegex(string template)
|
||||||
{
|
{
|
||||||
// Простейшее преобразование шаблона: "/open {page} {id?}" -> Regex
|
// Заменяем все {name} и {name?} на регулярные группы
|
||||||
var escaped = Regex.Escape(template)
|
var pattern = "^" + Regex.Replace(template, @"\s*\{(\w+)(\?)?\}", m =>
|
||||||
.Replace("\\{", "{").Replace("\\}", "}");
|
{
|
||||||
var pattern = "^" + escaped
|
var name = m.Groups[1].Value;
|
||||||
.Replace("{page}", "(?<page>\\S+)")
|
var optional = m.Groups[2].Success;
|
||||||
.Replace("{id?}", "(?<id>\\S+)?") + "$";
|
|
||||||
|
var argPattern = $"(?:\"(?<{name}>[^\"]+)\"|(?<{name}>\\S+))";
|
||||||
|
|
||||||
|
if (optional)
|
||||||
|
{
|
||||||
|
// необязательный параметр: пробел + значение целиком необязательны
|
||||||
|
return $"(?:\\s+{argPattern})?";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// обязательный параметр: пробел обязателен
|
||||||
|
return $"\\s+{argPattern}";
|
||||||
|
}
|
||||||
|
}) + "\\s*$"; // допускаем пробелы/переносы в конце
|
||||||
|
|
||||||
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ internal sealed class RoutesRegistry
|
|||||||
|
|
||||||
internal void Map(Type? type)
|
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);
|
_routes.Add(attr.Template, type);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,6 +66,10 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
|
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
|
||||||
if (mapped is not null)
|
if (mapped is not null)
|
||||||
await onUpdate(mapped);
|
await onUpdate(mapped);
|
||||||
|
if (update.CallbackQuery is not null)
|
||||||
|
{
|
||||||
|
await _.AnswerCallbackQuery(update.CallbackQuery.Id);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
errorHandler: async (_, ex, ct2) =>
|
errorHandler: async (_, ex, ct2) =>
|
||||||
@@ -86,11 +90,11 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<string?> SendTextAsync(string chatId, string text,
|
public async Task<string?> SendTextAsync(string chatId, string text,
|
||||||
MessageFormat format = MessageFormat.Plain,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
string? messageId = null,
|
string? messageId = null,
|
||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
@@ -189,9 +193,9 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SendFileAsync(string chatId,
|
public async Task SendFileAsync(string chatId,
|
||||||
FileDescriptor file,
|
FileDescriptor file,
|
||||||
string? caption = null,
|
string? caption = null,
|
||||||
MessageFormat? captionFormat = null,
|
MessageFormat? captionFormat = null,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
|
|
||||||
@@ -7,20 +8,20 @@ namespace Demo.Pages;
|
|||||||
/// Страница ввода деталей заявки.
|
/// Страница ввода деталей заявки.
|
||||||
/// Страница с параметрами и получением состояния.
|
/// Страница с параметрами и получением состояния.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
public sealed class DetailsPage : StatefullPage<string>
|
||||||
{
|
{
|
||||||
[Statefull("Request")]
|
[Statefull("Request")]
|
||||||
private Models.Request Request;
|
private Models.Request Request;
|
||||||
|
|
||||||
public override Task OnEnter(PageContext ctx, DetailsArgs args, CancellationToken ct)
|
public override Task OnEnter(PageContext ctx, string args, CancellationToken ct)
|
||||||
{
|
{
|
||||||
Request = new()
|
Request = new()
|
||||||
{
|
{
|
||||||
Title = args.Title,
|
Title = args,
|
||||||
};
|
};
|
||||||
|
|
||||||
return new MessageBuilder(ctx)
|
return new MessageBuilder(ctx)
|
||||||
.Text($"Заголовок: {args.Title}\nДобавьте детали или нажмите Далее.")
|
.Text($"Заголовок: {args}\nДобавьте детали или нажмите Далее.")
|
||||||
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
||||||
.Reply("Отмена")
|
.Reply("Отмена")
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
@@ -52,12 +53,15 @@ public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
|||||||
await SaveState(ctx, ct);
|
await SaveState(ctx, ct);
|
||||||
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
internal static string Command => "/create_request {title?}";
|
||||||
/// Аргументы для страницы DetailsPage.
|
internal static string CommandDescription => "создание заявки /create_request {title}";
|
||||||
/// </summary>
|
internal static CommandHandler CommandHandler = async (ctx, args, ct) =>
|
||||||
public sealed class DetailsArgs
|
{
|
||||||
{
|
string? title = "";
|
||||||
public string Title { get; set; } = "";
|
args?.TryGetValue("title", out title);
|
||||||
|
|
||||||
|
// Навигация на страницу по имени
|
||||||
|
await ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, title ?? "", ct);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ public sealed class TitlePage : SingletonPage
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return ctx.Navigation.GoToAsync<DetailsPage, DetailsArgs>(ctx, new DetailsArgs { Title = text }, ct);
|
return ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, text, ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,7 @@ namespace Demo
|
|||||||
.AddDefaultPage<WelcomePage>()
|
.AddDefaultPage<WelcomePage>()
|
||||||
.MapCommand<WelcomePage>("/start", true, "Главная")
|
.MapCommand<WelcomePage>("/start", true, "Главная")
|
||||||
.MapCommand("/open {page}", openHandler, true, "открыть станицу /open {page}")
|
.MapCommand("/open {page}", openHandler, true, "открыть станицу /open {page}")
|
||||||
|
.MapCommand(DetailsPage.Command, DetailsPage.CommandHandler, true, DetailsPage.CommandDescription)
|
||||||
.AutoMapRoute()
|
.AutoMapRoute()
|
||||||
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
||||||
.AddMiddleware(new LoggingMiddleware(logger))
|
.AddMiddleware(new LoggingMiddleware(logger))
|
||||||
|
|||||||
162
TZ.md
162
TZ.md
@@ -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).
|
|
||||||
- View‑DSL как надстройка над контекстом.
|
|
||||||
- Cross‑transport identity.
|
|
||||||
- Расширенные таймауты и политики отката.
|
|
||||||
Reference in New Issue
Block a user