Compare commits
4 Commits
v0.3.3
...
41986987b1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41986987b1 | ||
| 246a5cb278 | |||
| 644749929e | |||
| 8528b814d8 |
@@ -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>
|
||||||
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
||||||
|
|||||||
@@ -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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,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)
|
||||||
@@ -193,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,7 +1,6 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Abstractions;
|
using BotPages.Core.Abstractions;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
using BotPages.Core.Routing;
|
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
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