Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 644749929e | |||
| 8528b814d8 | |||
| d60bef7070 | |||
| 7556b3d638 | |||
| 67de9e197a | |||
| edc718b1f9 | |||
| 8af03fa52b | |||
| d6f54bb0e6 | |||
| db122e8aef |
@@ -9,35 +9,39 @@ namespace BotPages.Core.Abstractions;
|
||||
/// </summary>
|
||||
public interface IMessengerAdapter
|
||||
{
|
||||
/// <summary>
|
||||
/// Доступные возможности мессенджера.
|
||||
/// </summary>
|
||||
Capabilities Capabilities { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Отправить текстовое сообщение в чат.
|
||||
/// </summary>
|
||||
Task SendTextAsync(string chatId, string text, MessageFormat format,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
|
||||
Task<string?> SendTextAsync(string chatId,
|
||||
string text,
|
||||
MessageFormat format = MessageFormat.Plain,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||
string? messageId = null,
|
||||
CancellationToken ct = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Отправить файл в чат.
|
||||
/// </summary>
|
||||
Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct);
|
||||
Task SendFileAsync(string chatId,
|
||||
FileDescriptor file,
|
||||
string? caption = null,
|
||||
MessageFormat? captionFormat = null,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Создать билдер альбома для отправки медиагруппы.
|
||||
/// </summary>
|
||||
IAlbumBuilder CreateAlbumBuilder(PageContext ctx);
|
||||
|
||||
/// <summary>
|
||||
/// Начать отображение прогресса операции.
|
||||
/// </summary>
|
||||
Task<string?> StartProgressAsync(PageContext ctx, string title, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Обновить прогресс операции.
|
||||
/// </summary>
|
||||
Task UpdateProgressAsync(PageContext ctx, string messageId, string title, int percent, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Вызывается при выходе со страницы.
|
||||
/// </summary>
|
||||
@@ -55,5 +59,5 @@ public interface IMessangerAdapterSetup : IMessengerAdapter
|
||||
/// <param name="onUpdate"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, CancellationToken ct);
|
||||
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct);
|
||||
}
|
||||
@@ -69,16 +69,34 @@ public sealed class BotPagesApp
|
||||
/// </summary>
|
||||
public BotPagesApp MapCommand<TPage>(string commandTemplate) where TPage : Page
|
||||
{
|
||||
_commands.Map<TPage>(commandTemplate);
|
||||
_commands.Map<TPage>(commandTemplate, false, null);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Зарегистрировать команду, ведущую на страницу.
|
||||
/// </summary>
|
||||
public BotPagesApp MapCommand<TPage>(string commandTemplate, bool publish, string description) where TPage : Page
|
||||
{
|
||||
_commands.Map<TPage>(commandTemplate, publish, description);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Зарегистрировать команду с кастомным обработчиком.
|
||||
/// </summary>
|
||||
public BotPagesApp MapCommand(string template, Func<PageContext, CancellationToken, Task> handler)
|
||||
public BotPagesApp MapCommand(string template, CommandHandler handler)
|
||||
{
|
||||
_commands.Map(template, handler);
|
||||
_commands.Map(template, handler, false, null);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Зарегистрировать команду с кастомным обработчиком.
|
||||
/// </summary>
|
||||
public BotPagesApp MapCommand(string template, CommandHandler handler, bool publish, string description)
|
||||
{
|
||||
_commands.Map(template, handler, publish, description);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -142,7 +160,6 @@ public sealed class BotPagesApp
|
||||
{
|
||||
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null)
|
||||
{
|
||||
_logger.Log(LogLevel.Info, $"Command '{update.Text}' dispatched.");
|
||||
await dispatched;
|
||||
return;
|
||||
}
|
||||
@@ -237,7 +254,7 @@ public sealed class BotPagesApp
|
||||
{
|
||||
foreach (var adapter in _adapterFactory.Adapters)
|
||||
{
|
||||
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), cancellationToken);
|
||||
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,47 +27,4 @@ public sealed class PageContext
|
||||
/// </summary>
|
||||
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this);
|
||||
|
||||
/// <summary>
|
||||
/// Начать прогресс операции.
|
||||
/// </summary>
|
||||
public async Task<string?> StartProgressAsync(string title, CancellationToken ct)
|
||||
{
|
||||
var messageId = await Adapter.StartProgressAsync(this, title, ct);
|
||||
|
||||
if (messageId != null)
|
||||
{
|
||||
_progressMessageId = messageId;
|
||||
_progressTitle = title;
|
||||
}
|
||||
|
||||
return messageId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновить прогресс операции.
|
||||
/// </summary>
|
||||
public Task UpdateProgressAsync(int percent, CancellationToken ct)
|
||||
{
|
||||
if (_progressMessageId != null)
|
||||
{
|
||||
return Adapter.UpdateProgressAsync(this, _progressMessageId, _progressTitle ?? "", percent, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновить прогресс операции.
|
||||
/// </summary>
|
||||
public Task UpdateProgressAsync(string messageId, int percent, CancellationToken ct)
|
||||
{
|
||||
return Adapter.UpdateProgressAsync(this, messageId, _progressTitle ?? "", percent, ct);
|
||||
}
|
||||
|
||||
|
||||
private string? _progressMessageId = null;
|
||||
private string? _progressTitle = null;
|
||||
|
||||
}
|
||||
@@ -11,21 +11,31 @@ public static class PageContextAdapterExtensions
|
||||
/// <summary>
|
||||
/// Отправить текстовое сообщение.
|
||||
/// </summary>
|
||||
public static Task SendTextAsync(this PageContext ctx, string text, MessageFormat format = MessageFormat.Plain,
|
||||
public static Task<string?> SendTextAsync(this PageContext ctx,
|
||||
string text,
|
||||
MessageFormat format = MessageFormat.Plain,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||
string? messageId = null,
|
||||
CancellationToken ct = default)
|
||||
=> ctx.Adapter.SendTextAsync(ctx.Update.Chat.Id, text, format, inline, reply, ct);
|
||||
=> ctx.Adapter.SendTextAsync(ctx.Update.Chat.Id, text, format, inline, reply, messageId, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Отправить файл.
|
||||
/// </summary>
|
||||
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null, CancellationToken ct = default)
|
||||
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Отправить файл.
|
||||
/// </summary>
|
||||
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
||||
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, null, ct);
|
||||
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,
|
||||
captionFormat: captionFormat,
|
||||
inline: inline,
|
||||
reply: reply,
|
||||
ct: ct);
|
||||
}
|
||||
@@ -14,10 +14,8 @@ public sealed class MessageBuilder
|
||||
private readonly List<List<ReplyButton>> _reply = new();
|
||||
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new();
|
||||
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
|
||||
private string? _progressTitle = null;
|
||||
private int? _progressPercent = null;
|
||||
private string? _progressMessageId = null;
|
||||
private bool _disableReplyKeyboard;
|
||||
private string? _editMessageId = null;
|
||||
|
||||
/// <summary>Создать билдер сообщений.</summary>
|
||||
public MessageBuilder(PageContext ctx) => _ctx = ctx;
|
||||
@@ -30,6 +28,13 @@ public sealed class MessageBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Редактировать сообщение.</summary>
|
||||
public MessageBuilder EditMessage(string messagId)
|
||||
{
|
||||
_editMessageId = messagId;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Добавить inline‑кнопку.</summary>
|
||||
public MessageBuilder Inline(string label, string value)
|
||||
{
|
||||
@@ -113,30 +118,30 @@ public sealed class MessageBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Установить прогресс операции.</summary>
|
||||
public MessageBuilder Progress(string title, int percent = 0)
|
||||
{
|
||||
_progressTitle = title;
|
||||
_progressPercent = percent;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Отправить собранное сообщение.</summary>
|
||||
public async Task SendAsync(CancellationToken ct = default)
|
||||
{
|
||||
// Текст
|
||||
if (!string.IsNullOrWhiteSpace(_text))
|
||||
public async Task<string?> SendAsync(CancellationToken ct = default)
|
||||
{
|
||||
string? messageId = null;
|
||||
|
||||
List<List<ReplyButton>>? reply = null;
|
||||
if (_disableReplyKeyboard) reply = new();
|
||||
else if (_reply.Any()) reply = _reply;
|
||||
|
||||
await _ctx.SendTextAsync(_text, _format, _inline, reply, ct);
|
||||
// Текст
|
||||
if (!string.IsNullOrWhiteSpace(_text))
|
||||
{
|
||||
messageId = await _ctx.SendTextAsync(_text, _format, _inline, reply, _editMessageId, ct);
|
||||
}
|
||||
|
||||
// Файлы
|
||||
foreach (var (file, caption, captionFormat) in _files)
|
||||
await _ctx.SendFileAsync(file, caption, captionFormat, ct);
|
||||
await _ctx.SendFileAsync(file: file
|
||||
, caption: caption
|
||||
, captionFormat: captionFormat
|
||||
, reply: reply
|
||||
, inline: _inline
|
||||
, ct: ct
|
||||
);
|
||||
|
||||
// Альбом
|
||||
if (_album.Count > 0)
|
||||
@@ -147,25 +152,12 @@ public sealed class MessageBuilder
|
||||
await builder.SendAsync(ct);
|
||||
}
|
||||
|
||||
// Прогресс
|
||||
if (_progressTitle is not null)
|
||||
{
|
||||
if (_progressMessageId is null)
|
||||
_progressMessageId = await _ctx.StartProgressAsync(_progressTitle, ct);
|
||||
|
||||
if (_progressPercent > 0 && !string.IsNullOrEmpty(_progressMessageId))
|
||||
await _ctx.UpdateProgressAsync(_progressMessageId, _progressPercent.Value, ct);
|
||||
}
|
||||
|
||||
_text = null;
|
||||
_files.Clear();
|
||||
_album.Clear();
|
||||
|
||||
if (_progressPercent >= 100)
|
||||
{
|
||||
_progressTitle = null;
|
||||
_progressMessageId = null;
|
||||
_progressPercent = null;
|
||||
}
|
||||
_editMessageId = null;
|
||||
|
||||
return messageId;
|
||||
}
|
||||
}
|
||||
|
||||
34
BotPages.Core/Routing/Command.cs
Normal file
34
BotPages.Core/Routing/Command.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
namespace BotPages.Core.Routing;
|
||||
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
/// <summary>
|
||||
/// Команда действий. Например "/start"
|
||||
/// </summary>
|
||||
public class Command
|
||||
{
|
||||
/// <summary>
|
||||
/// Название команды.
|
||||
/// </summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Шаблон команды.
|
||||
/// </summary>
|
||||
public required Regex Pattern { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Обработчик команды.
|
||||
/// </summary>
|
||||
public required CommandHandler Handler { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Описание команды.
|
||||
/// </summary>
|
||||
public string? Description { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Публичный? нужно ли регистрировать в боте.
|
||||
/// </summary>
|
||||
public required bool Publish { get; init; }
|
||||
}
|
||||
12
BotPages.Core/Routing/CommandHandler.cs
Normal file
12
BotPages.Core/Routing/CommandHandler.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BotPages.Core.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
||||
/// </summary>
|
||||
public delegate Task CommandHandler(PageContext context, IReadOnlyDictionary<string, string>? args, CancellationToken cancellationToken);
|
||||
@@ -2,30 +2,38 @@
|
||||
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Реестр команд, доступных из любого места.
|
||||
/// </summary>
|
||||
internal sealed class CommandsRegistry
|
||||
{
|
||||
private readonly List<(Regex pattern, Func<PageContext, CancellationToken, Task> handler)> _commands = new();
|
||||
private readonly List<Command> _commands = new();
|
||||
|
||||
public List<Command> Commands => _commands;
|
||||
|
||||
/// <summary>
|
||||
/// Зарегистрировать команду, ведущую на страницу.
|
||||
/// </summary>
|
||||
public CommandsRegistry Map<TPage>(string commandTemplate) where TPage : Page
|
||||
public CommandsRegistry Map<TPage>(string commandTemplate, bool publish = false, string? description = null) where TPage : Page
|
||||
{
|
||||
var pattern = ToRegex(commandTemplate);
|
||||
_commands.Add((pattern, (ctx, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct)));
|
||||
return this;
|
||||
return Map(commandTemplate, (ctx, args, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct), publish, description);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Зарегистрировать команду с кастомным обработчиком.
|
||||
/// </summary>
|
||||
public CommandsRegistry Map(string commandTemplate, Func<PageContext, CancellationToken, Task> handler)
|
||||
public CommandsRegistry Map(string commandTemplate, CommandHandler handler, bool publish = false, string? description = null)
|
||||
{
|
||||
var pattern = ToRegex(commandTemplate);
|
||||
_commands.Add((pattern, handler));
|
||||
_commands.Add(new Command()
|
||||
{
|
||||
Name = ToCommandName(commandTemplate),
|
||||
Pattern = pattern,
|
||||
Handler = handler,
|
||||
Publish = publish,
|
||||
Description = string.IsNullOrWhiteSpace(description) ? null : description
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -34,11 +42,17 @@ internal sealed class CommandsRegistry
|
||||
/// </summary>
|
||||
public bool TryDispatch(PageContext ctx, string command, CancellationToken ct, out Task? task)
|
||||
{
|
||||
foreach (var (pattern, handler) in _commands)
|
||||
foreach (var cmd in _commands)
|
||||
{
|
||||
if (pattern.IsMatch(command))
|
||||
var match = cmd.Pattern.Match(command);
|
||||
if (match.Success)
|
||||
{
|
||||
task = handler(ctx, ct);
|
||||
// Собираем именованные группы (без числовых)
|
||||
var args = cmd.Pattern.GetGroupNames()
|
||||
.Where(n => !int.TryParse(n, out _))
|
||||
.ToDictionary(n => n, n => match.Groups[n].Value);
|
||||
|
||||
task = cmd.Handler(ctx, args, ct);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -46,14 +60,37 @@ internal sealed class CommandsRegistry
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Универсальный парсер шаблонов: /cmd {a} {b?} {c}
|
||||
/// </summary>
|
||||
private static Regex ToRegex(string template)
|
||||
{
|
||||
// Простейшее преобразование шаблона: "/open {page} {id?}" -> Regex
|
||||
var escaped = Regex.Escape(template)
|
||||
.Replace("\\{", "{").Replace("\\}", "}");
|
||||
var pattern = "^" + escaped
|
||||
.Replace("{page}", "(?<page>\\S+)")
|
||||
.Replace("{id?}", "(?<id>\\S+)?") + "$";
|
||||
// Заменяем все {name} и {name?} на регулярные группы
|
||||
var pattern = "^" + Regex.Replace(template, @"\s*\{(\w+)(\?)?\}", m =>
|
||||
{
|
||||
var name = m.Groups[1].Value;
|
||||
var optional = m.Groups[2].Success;
|
||||
|
||||
var argPattern = $"(?:\"(?<{name}>[^\"]+)\"|(?<{name}>\\S+))";
|
||||
|
||||
if (optional)
|
||||
{
|
||||
// необязательный параметр: пробел + значение целиком необязательны
|
||||
return $"(?:\\s+{argPattern})?";
|
||||
}
|
||||
else
|
||||
{
|
||||
// обязательный параметр: пробел обязателен
|
||||
return $"\\s+{argPattern}";
|
||||
}
|
||||
}) + "\\s*$"; // допускаем пробелы/переносы в конце
|
||||
|
||||
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
private static string ToCommandName(string template)
|
||||
{
|
||||
// Простейшее преобразование шаблона: "/open {page} {id?}" -> "/open"
|
||||
return template.Split(" ", StringSplitOptions.RemoveEmptyEntries).First().ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Exceptions;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
@@ -56,7 +57,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
/// <summary>
|
||||
/// Запустить polling для приема обновлений от Telegram.
|
||||
/// </summary>
|
||||
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, CancellationToken ct)
|
||||
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
|
||||
{
|
||||
_client = new TelegramBotClient(_token);
|
||||
|
||||
@@ -66,17 +67,31 @@ 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) =>
|
||||
{
|
||||
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex);
|
||||
|
||||
if (ex is ApiRequestException apiEx)
|
||||
{
|
||||
if (apiEx.ErrorCode == 409)
|
||||
{
|
||||
_logger.Log(LogLevel.Critical, $"{MessengerType} остановлен.");
|
||||
await _.Close(ct2);
|
||||
}
|
||||
}
|
||||
await Task.CompletedTask;
|
||||
},
|
||||
|
||||
cancellationToken: ct
|
||||
);
|
||||
|
||||
await _client.SetMyCommands(commands.Where(t => t.Publish).Select(t => new BotCommand(t.Name, t.Description ?? t.Name.TrimStart('/'))), cancellationToken: ct);
|
||||
|
||||
var me = await _client.GetMe();
|
||||
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
|
||||
@@ -85,21 +100,25 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SendTextAsync(string chatId, string text, MessageFormat format,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
|
||||
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,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null)
|
||||
{
|
||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
InlineKeyboardMarkup? inlineMarkup = null;
|
||||
ReplyMarkup? markup = null;
|
||||
|
||||
if (inline is not null && inline.Any())
|
||||
{
|
||||
markup = new InlineKeyboardMarkup(
|
||||
inlineMarkup = new InlineKeyboardMarkup(
|
||||
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
||||
.ToArray()
|
||||
);
|
||||
@@ -154,17 +173,44 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
text = text.Substring(0, Capabilities.MaxMessageLength);
|
||||
}
|
||||
|
||||
await _client.SendMessage(
|
||||
if (!string.IsNullOrWhiteSpace(messageId))
|
||||
{
|
||||
await _client.EditMessageText(
|
||||
messageId: int.Parse(messageId),
|
||||
chatId: long.Parse(chatId),
|
||||
text: text,
|
||||
parseMode: parseMode,
|
||||
replyMarkup: inlineMarkup,
|
||||
cancellationToken: ct
|
||||
);
|
||||
|
||||
return messageId;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (inlineMarkup is not null) markup = inlineMarkup;
|
||||
|
||||
var message = await _client.SendMessage(
|
||||
chatId: long.Parse(chatId),
|
||||
text: text,
|
||||
parseMode: parseMode,
|
||||
replyMarkup: markup,
|
||||
cancellationToken: ct
|
||||
);
|
||||
|
||||
return message.Id.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct)
|
||||
public async Task SendFileAsync(string chatId,
|
||||
FileDescriptor file,
|
||||
string? caption = null,
|
||||
MessageFormat? captionFormat = null,
|
||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||
CancellationToken ct = default
|
||||
)
|
||||
{
|
||||
if (_client is null)
|
||||
{
|
||||
@@ -226,20 +272,46 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
}
|
||||
}
|
||||
|
||||
ReplyMarkup? markup = null;
|
||||
|
||||
if (inline is not null && inline.Any())
|
||||
{
|
||||
markup = new InlineKeyboardMarkup(
|
||||
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
||||
.ToArray()
|
||||
);
|
||||
}
|
||||
else if (reply is not null)
|
||||
{
|
||||
if (reply.Any())
|
||||
{
|
||||
markup = new ReplyKeyboardMarkup(
|
||||
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
||||
)
|
||||
{
|
||||
ResizeKeyboard = true
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
markup = new ReplyKeyboardRemove();
|
||||
}
|
||||
}
|
||||
|
||||
// В зависимости от FileKind выбираем подходящий метод
|
||||
switch (file.Kind)
|
||||
{
|
||||
case FileKind.Photo:
|
||||
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||
break;
|
||||
case FileKind.Video:
|
||||
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, cancellationToken: ct);
|
||||
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||
break;
|
||||
case FileKind.Audio:
|
||||
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||
break;
|
||||
default:
|
||||
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -247,62 +319,6 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
/// <inheritdoc />
|
||||
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string?> StartProgressAsync(PageContext ctx, string title, CancellationToken ct)
|
||||
{
|
||||
if (_client is null)
|
||||
{
|
||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||
return null;
|
||||
}
|
||||
|
||||
string text = "0%";
|
||||
if (!string.IsNullOrEmpty(title))
|
||||
{
|
||||
text = title + Environment.NewLine + text;
|
||||
}
|
||||
|
||||
var message = await _client.SendMessage(
|
||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
||||
text: text,
|
||||
cancellationToken: ct
|
||||
);
|
||||
|
||||
return message.Id.ToString();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task UpdateProgressAsync(PageContext ctx, string messageId, string title, int percent, CancellationToken ct)
|
||||
{
|
||||
if (_client is null)
|
||||
{
|
||||
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||
return;
|
||||
}
|
||||
|
||||
percent = Math.Clamp(percent, 0, 100);
|
||||
|
||||
string text = $"{percent}%";
|
||||
if (!string.IsNullOrEmpty(title))
|
||||
{
|
||||
text = title + Environment.NewLine + text;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _client.EditMessageText(
|
||||
messageId: int.Parse(messageId),
|
||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
||||
text: text,
|
||||
cancellationToken: ct
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Log(LogLevel.Critical, ex.Message, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
||||
{
|
||||
_logger.Log(LogLevel.Warn, "Albums not supported. Degraded to sequential sends.");
|
||||
foreach (var (file, caption, captionFormat) in _items)
|
||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
||||
{
|
||||
// Telegram не поддерживает document в альбомах — деградация
|
||||
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
|
||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,20 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<PackageId>BotPages</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<Authors>FrigaT</Authors>
|
||||
<Company>FrigaT</Company>
|
||||
<Product>BotPages</Product>
|
||||
<Description>Платформонезависимый framework для создания диалоговых ботов с системой страниц.</Description>
|
||||
<Copyright>Copyright © 2025 FrigaT</Copyright>
|
||||
<RepositoryUrl>https://git.frigat.duckdns.org/FrigaT/BotPages</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<PackageProjectUrl>https://git.frigat.duckdns.org/FrigaT/BotPages</PackageProjectUrl>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
|
||||
@@ -7,20 +8,20 @@ namespace Demo.Pages;
|
||||
/// Страница ввода деталей заявки.
|
||||
/// Страница с параметрами и получением состояния.
|
||||
/// </summary>
|
||||
public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
||||
public sealed class DetailsPage : StatefullPage<string>
|
||||
{
|
||||
[Statefull("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()
|
||||
{
|
||||
Title = args.Title,
|
||||
Title = args,
|
||||
};
|
||||
|
||||
return new MessageBuilder(ctx)
|
||||
.Text($"Заголовок: {args.Title}\nДобавьте детали или нажмите Далее.")
|
||||
.Text($"Заголовок: {args}\nДобавьте детали или нажмите Далее.")
|
||||
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
||||
.Reply("Отмена")
|
||||
.SendAsync(ct);
|
||||
@@ -52,12 +53,15 @@ public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
||||
await SaveState(ctx, ct);
|
||||
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Аргументы для страницы DetailsPage.
|
||||
/// </summary>
|
||||
public sealed class DetailsArgs
|
||||
{
|
||||
public string Title { get; set; } = "";
|
||||
internal static string Command => "/create_request {title?}";
|
||||
internal static string CommandDescription => "создание заявки /create_request {title}";
|
||||
internal static CommandHandler CommandHandler = async (ctx, args, ct) =>
|
||||
{
|
||||
string? title = "";
|
||||
args?.TryGetValue("title", out title);
|
||||
|
||||
// Навигация на страницу по имени
|
||||
await ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, title ?? "", ct);
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Abstractions;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
|
||||
[Route("FileSend")]
|
||||
public sealed class FileSendPage : SingletonPage
|
||||
{
|
||||
public override Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||
|
||||
@@ -20,7 +20,7 @@ public sealed class FilesPage : SingletonPage
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct);
|
||||
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct: ct);
|
||||
}
|
||||
|
||||
//Обращение через Storage
|
||||
|
||||
@@ -12,8 +12,8 @@ public sealed class SubmitPage : SingletonPage
|
||||
{
|
||||
var progress = new MessageBuilder(ctx);
|
||||
|
||||
await progress
|
||||
.Progress("Отправка заявки", 7)
|
||||
var messageId = await progress
|
||||
.Text("Отправка заявки\n7%")
|
||||
.SendAsync(ct);
|
||||
|
||||
int i = 7;
|
||||
@@ -22,7 +22,8 @@ public sealed class SubmitPage : SingletonPage
|
||||
i += 25;
|
||||
Thread.Sleep(TimeSpan.FromMilliseconds(200));
|
||||
await progress
|
||||
.Progress("Отправка заявки", i)
|
||||
.Text($"Отправка заявки\n{i}%")
|
||||
.EditMessage(messageId!)
|
||||
.SendAsync(ct);
|
||||
}
|
||||
while (i < 100);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Abstractions;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
/// <summary>
|
||||
@@ -23,7 +24,7 @@ public sealed class TitlePage : SingletonPage
|
||||
}
|
||||
else
|
||||
{
|
||||
return ctx.Navigation.GoToAsync<DetailsPage, DetailsArgs>(ctx, new DetailsArgs { Title = text }, ct);
|
||||
return ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, text, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Abstractions;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
|
||||
@@ -8,6 +9,7 @@ namespace Demo.Pages;
|
||||
/// Стартовая страница демо‑бота.
|
||||
/// Обычная страница с кнопками
|
||||
/// </summary>
|
||||
[Route("Welcome")]
|
||||
public sealed class WelcomePage : SingletonPage
|
||||
{
|
||||
public override async Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Logging;
|
||||
using BotPages.Core.Middleware;
|
||||
using BotPages.Core.Routing;
|
||||
using BotPages.Core.Storage;
|
||||
using BotPages.Telegram;
|
||||
using Demo.Pages;
|
||||
@@ -18,9 +19,27 @@ namespace Demo
|
||||
var state = new InMemoryStateStorage();
|
||||
using var cts = new CancellationTokenSource();
|
||||
|
||||
// Можно использовать команды для открытия страниц с роутингом
|
||||
// /open Welcome
|
||||
// /open FileSend
|
||||
CommandHandler openHandler = async (ctx, args, ct) =>
|
||||
{
|
||||
if (args is null || !args.TryGetValue("page", out var pageName))
|
||||
{
|
||||
await ctx.SendTextAsync("Не указана страница для открытия.", ct: ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Навигация на страницу по имени
|
||||
await ctx.Navigation.GoToAsync(pageName, ctx, ct);
|
||||
};
|
||||
|
||||
var app = new BotPagesApp(state, logger)
|
||||
.AddDefaultPage<WelcomePage>()
|
||||
.MapCommand<WelcomePage>("/start")
|
||||
.MapCommand<WelcomePage>("/start", true, "Главная")
|
||||
.MapCommand("/open {page}", openHandler, true, "открыть станицу /open {page}")
|
||||
.MapCommand(DetailsPage.Command, DetailsPage.CommandHandler, true, DetailsPage.CommandDescription)
|
||||
.AutoMapRoute()
|
||||
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
||||
.AddMiddleware(new LoggingMiddleware(logger))
|
||||
.AddTelegramAdapter(token, "Telegram")
|
||||
|
||||
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