Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67de9e197a | |||
| edc718b1f9 | |||
| 8af03fa52b | |||
| d6f54bb0e6 | |||
| db122e8aef | |||
| fce6e8d013 | |||
| 57b3706241 | |||
| f9584c5afe | |||
| 07df710ce6 | |||
| d97fcaaa20 | |||
| 308f1af33a | |||
| 5085958219 | |||
| 634a9292dc | |||
| a94327f0c8 |
@@ -6,7 +6,7 @@
|
|||||||
public interface IAlbumBuilder
|
public interface IAlbumBuilder
|
||||||
{
|
{
|
||||||
/// <summary>Добавить элемент в альбом.</summary>
|
/// <summary>Добавить элемент в альбом.</summary>
|
||||||
IAlbumBuilder Add(FileDescriptor file, string? caption = null);
|
IAlbumBuilder Add(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null);
|
||||||
/// <summary>Отправить альбом.</summary>
|
/// <summary>Отправить альбом.</summary>
|
||||||
Task SendAsync(CancellationToken ct = default);
|
Task SendAsync(CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Context;
|
||||||
|
using BotPages.Core.Messaging;
|
||||||
|
|
||||||
namespace BotPages.Core.Abstractions;
|
namespace BotPages.Core.Abstractions;
|
||||||
|
|
||||||
@@ -8,35 +9,55 @@ namespace BotPages.Core.Abstractions;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IMessengerAdapter
|
public interface IMessengerAdapter
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Доступные возможности мессенджера.
|
||||||
|
/// </summary>
|
||||||
|
Capabilities Capabilities { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение в чат.
|
/// Отправить текстовое сообщение в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendTextAsync(PageContext ctx, string text, MessageFormat format,
|
Task<string?> SendTextAsync(string chatId,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
string text,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
|
MessageFormat format = MessageFormat.Plain,
|
||||||
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
string? messageId = null,
|
||||||
|
CancellationToken ct = default
|
||||||
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл в чат.
|
/// Отправить файл в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendFileAsync(PageContext ctx, FileDescriptor file, string? caption, 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>
|
||||||
/// Создать билдер альбома для отправки медиагруппы.
|
/// Создать билдер альбома для отправки медиагруппы.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
IAlbumBuilder CreateAlbumBuilder(PageContext ctx);
|
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>
|
||||||
/// Вызывается при выходе со страницы.
|
/// Вызывается при выходе со страницы.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task OnLeaveAsync(PageContext ctx, CancellationToken ct);
|
Task OnLeaveAsync(PageContext ctx, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Контракт конфигурации адаптера.
|
||||||
|
/// </summary>
|
||||||
|
public interface IMessangerAdapterSetup : IMessengerAdapter
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Запуск работы адаптера
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="onUpdate"></param>
|
||||||
|
/// <param name="ct"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct);
|
||||||
|
}
|
||||||
@@ -4,16 +4,35 @@ namespace BotPages.Core.Abstractions;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Фабрика адаптеров мессенджеров.
|
/// Фабрика адаптеров мессенджеров.
|
||||||
/// Используется для разрешения конкретного <see cref="IMessengerAdapter"/> по типу мессенджера.
|
/// Используется для разрешения конкретного <see cref="IMessangerAdapterSetup"/> по типу мессенджера.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IMessengerAdapterFactory
|
public interface IMessengerAdapterFactory
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Список зарегистрированных адаптеров.
|
||||||
|
/// </summary>
|
||||||
|
Dictionary<string, IMessangerAdapterSetup> Adapters { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Зарегистрировать адаптер для указанного типа мессенджера.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="messengerType">
|
||||||
|
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
|
||||||
|
/// </param>
|
||||||
|
/// <param name="adapter">
|
||||||
|
/// Экземпляр адаптера, реализующий <see cref="IMessengerAdapter"/>.
|
||||||
|
/// </param>
|
||||||
|
/// <returns>
|
||||||
|
/// Текущий экземпляр <see cref="MultiAdapterFactory"/> для цепочки вызовов.
|
||||||
|
/// </returns>
|
||||||
|
IMessengerAdapterFactory Register(string messengerType, IMessangerAdapterSetup adapter);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить адаптер для указанного мессенджера.
|
/// Получить адаптер для указанного мессенджера.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="messengerType">
|
/// <param name="messengerType">
|
||||||
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
|
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
|
||||||
/// Значение должно совпадать с <see cref="UpdateContext.User"/>.<see cref="UserContext.MessengerType"/>.
|
/// Значение должно совпадать с <see cref="UpdateContext.MessengerType"/>.
|
||||||
/// </param>
|
/// </param>
|
||||||
/// <returns>
|
/// <returns>
|
||||||
/// Экземпляр <see cref="IMessengerAdapter"/>, зарегистрированный для данного типа мессенджера.
|
/// Экземпляр <see cref="IMessengerAdapter"/>, зарегистрированный для данного типа мессенджера.
|
||||||
|
|||||||
@@ -6,7 +6,12 @@
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class MultiAdapterFactory : IMessengerAdapterFactory
|
public sealed class MultiAdapterFactory : IMessengerAdapterFactory
|
||||||
{
|
{
|
||||||
private readonly Dictionary<string, IMessengerAdapter> _adapters = new(StringComparer.OrdinalIgnoreCase);
|
private readonly Dictionary<string, IMessangerAdapterSetup> _adapters = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Список зарегистрированных адаптеров.
|
||||||
|
/// </summary>
|
||||||
|
public Dictionary<string, IMessangerAdapterSetup> Adapters => _adapters;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Зарегистрировать адаптер для указанного типа мессенджера.
|
/// Зарегистрировать адаптер для указанного типа мессенджера.
|
||||||
@@ -20,7 +25,7 @@ public sealed class MultiAdapterFactory : IMessengerAdapterFactory
|
|||||||
/// <returns>
|
/// <returns>
|
||||||
/// Текущий экземпляр <see cref="MultiAdapterFactory"/> для цепочки вызовов.
|
/// Текущий экземпляр <see cref="MultiAdapterFactory"/> для цепочки вызовов.
|
||||||
/// </returns>
|
/// </returns>
|
||||||
public MultiAdapterFactory Register(string messengerType, IMessengerAdapter adapter)
|
public IMessengerAdapterFactory Register(string messengerType, IMessangerAdapterSetup adapter)
|
||||||
{
|
{
|
||||||
_adapters[messengerType] = adapter;
|
_adapters[messengerType] = adapter;
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ using BotPages.Core.Abstractions;
|
|||||||
using BotPages.Core.Context;
|
using BotPages.Core.Context;
|
||||||
using BotPages.Core.Logging;
|
using BotPages.Core.Logging;
|
||||||
using BotPages.Core.Routing;
|
using BotPages.Core.Routing;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Основное приложение BotPages.
|
/// Основное приложение BotPages.
|
||||||
@@ -19,16 +20,30 @@ public sealed class BotPagesApp
|
|||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private readonly NavigationService _navigation;
|
private readonly NavigationService _navigation;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Серсвис логирования.
|
||||||
|
/// </summary>
|
||||||
|
public ILogger Logger => _logger;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создать приложение BotPages.
|
/// Создать приложение BotPages.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public BotPagesApp(IMessengerAdapterFactory adapterFactory, IStateStorage state, ILogger logger)
|
public BotPagesApp(IStateStorage state, ILogger logger)
|
||||||
{
|
{
|
||||||
_adapterFactory = adapterFactory;
|
|
||||||
_state = state;
|
_state = state;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
|
|
||||||
_navigation = new NavigationService(_routes);
|
_navigation = new NavigationService(_routes);
|
||||||
|
_adapterFactory = new MultiAdapterFactory();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить адаптер.
|
||||||
|
/// </summary>
|
||||||
|
public BotPagesApp AddAdapter(string messengerType, IMessangerAdapterSetup adapter)
|
||||||
|
{
|
||||||
|
_adapterFactory.Register(messengerType, adapter);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -54,16 +69,34 @@ public sealed class BotPagesApp
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public BotPagesApp MapCommand<TPage>(string commandTemplate) where TPage : Page
|
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;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Зарегистрировать команду с кастомным обработчиком.
|
/// Зарегистрировать команду с кастомным обработчиком.
|
||||||
/// </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;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +109,45 @@ public sealed class BotPagesApp
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Зарегистрировать все маршруты для страницы.
|
||||||
|
/// Маршрутом является <see cref="RouteAttribute"/>.
|
||||||
|
/// Так же берется полное название класса.
|
||||||
|
/// </summary>
|
||||||
|
public BotPagesApp AutoMapRoute()
|
||||||
|
{
|
||||||
|
// Берём все загруженные сборки в текущем AppDomain
|
||||||
|
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||||
|
|
||||||
|
// Находим все типы, которые наследуются от Page
|
||||||
|
var pageTypes = assemblies
|
||||||
|
.SelectMany(a =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return a.GetTypes();
|
||||||
|
}
|
||||||
|
catch (ReflectionTypeLoadException ex)
|
||||||
|
{
|
||||||
|
// Если часть типов не загрузилась — берём только успешные
|
||||||
|
return ex.Types.Where(t => t != null)!;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.Where(t => t != null
|
||||||
|
&& t.IsClass
|
||||||
|
&& !t.IsAbstract
|
||||||
|
&& t.IsSubclassOf(typeof(Page)))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// Выводим полные имена
|
||||||
|
foreach (var type in pageTypes)
|
||||||
|
{
|
||||||
|
_routes.Map(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обработать входящее обновление.
|
/// Обработать входящее обновление.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -88,7 +160,6 @@ public sealed class BotPagesApp
|
|||||||
{
|
{
|
||||||
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null)
|
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Info, $"Command '{update.Text}' dispatched.");
|
|
||||||
await dispatched;
|
await dispatched;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -147,7 +218,7 @@ public sealed class BotPagesApp
|
|||||||
|
|
||||||
if (page is null)
|
if (page is null)
|
||||||
{
|
{
|
||||||
await ctx.Navigation.GoToHome(ctx, ct);
|
await ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,4 +244,17 @@ public sealed class BotPagesApp
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private Page? ResolveCurrentPage(PageContext ctx)
|
private Page? ResolveCurrentPage(PageContext ctx)
|
||||||
=> _navigation.ResolveCurrentPage(ctx);
|
=> _navigation.ResolveCurrentPage(ctx);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Сборка и запуск приложения.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cancellationToken"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task Build(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
foreach (var adapter in _adapterFactory.Adapters)
|
||||||
|
{
|
||||||
|
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -15,7 +15,4 @@ public sealed class ChatContext
|
|||||||
|
|
||||||
/// <summary>Идентификатор треда (опционально).</summary>
|
/// <summary>Идентификатор треда (опционально).</summary>
|
||||||
public string? ThreadId { get; init; }
|
public string? ThreadId { get; init; }
|
||||||
|
|
||||||
/// <summary>Возможности мессенджера.</summary>
|
|
||||||
public Capabilities Capabilities { get; init; } = new();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,87 +22,9 @@ public sealed class PageContext
|
|||||||
/// <summary>Адаптер мессенджера.</summary>
|
/// <summary>Адаптер мессенджера.</summary>
|
||||||
public required IMessengerAdapter Adapter { get; init; }
|
public required IMessengerAdapter Adapter { get; init; }
|
||||||
|
|
||||||
//Storage
|
|
||||||
|
|
||||||
/// <summary>Получить состояние по ключу.</summary>
|
|
||||||
public Task<T?> GetStorageAsync<T>(string key, CancellationToken ct)
|
|
||||||
=> StateStorage.GetAsync<T>(SessionKey, key, ct);
|
|
||||||
|
|
||||||
/// <summary>Сохранить состояние по ключу.</summary>
|
|
||||||
public Task SetStorageAsync<T>(string key, T state, CancellationToken ct)
|
|
||||||
=> StateStorage.SetAsync<T>(SessionKey, key, state, ct);
|
|
||||||
|
|
||||||
/// <summary>Удалить состояние по ключу.</summary>
|
|
||||||
public Task<bool> RemoveStorageAsync(string key, CancellationToken ct)
|
|
||||||
=> StateStorage.RemoveAsync(SessionKey, key, ct);
|
|
||||||
|
|
||||||
/// <summary>Удалить все состояния по ключу.</summary>
|
|
||||||
public Task<bool> ClearStorageAsync(CancellationToken ct)
|
|
||||||
=> StateStorage.ClearAsync(SessionKey, ct);
|
|
||||||
|
|
||||||
//Adapter
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Отправить текстовое сообщение.
|
|
||||||
/// </summary>
|
|
||||||
public Task SendTextAsync(string text, MessageFormat format = MessageFormat.Plain,
|
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
|
||||||
CancellationToken ct = default)
|
|
||||||
=> Adapter.SendTextAsync(this, text, format, inline, reply, ct);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Отправить файл.
|
|
||||||
/// </summary>
|
|
||||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
|
||||||
=> Adapter.SendFileAsync(this, file, caption, ct);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить билдер альбомов.
|
/// Получить билдер альбомов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this);
|
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;
|
|
||||||
|
|
||||||
}
|
}
|
||||||
41
BotPages.Core/Context/PageContextAdapterExtensions.cs
Normal file
41
BotPages.Core/Context/PageContextAdapterExtensions.cs
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
using BotPages.Core.Abstractions;
|
||||||
|
using BotPages.Core.Messaging;
|
||||||
|
|
||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="IMessengerAdapter"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextAdapterExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Отправить текстовое сообщение.
|
||||||
|
/// </summary>
|
||||||
|
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, messageId, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Отправить файл.
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
38
BotPages.Core/Context/PageContextNavigationExtensions.cs
Normal file
38
BotPages.Core/Context/PageContextNavigationExtensions.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="NavigationService"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextNavigationExtensions
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToHomeAsync(this PageContext ctx, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync(this PageContext ctx, string route, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToAsync(route, ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти по маршруту с аргументами.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TArgs>(this PageContext ctx, string route, TArgs args, CancellationToken ct)
|
||||||
|
=> ctx.Navigation.GoToAsync<TArgs>(route, args, ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти на страницу без аргументов.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TPage>(this PageContext ctx, CancellationToken ct) where TPage : Page
|
||||||
|
=> ctx.Navigation.GoToAsync<TPage>(ctx, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Перейти на страницу с аргументами.
|
||||||
|
/// </summary>
|
||||||
|
public static Task GoToAsync<TPage, TArgs>(this PageContext ctx, TArgs args, CancellationToken ct) where TPage : StatefullPage<TArgs>
|
||||||
|
=> ctx.Navigation.GoToAsync<TPage, TArgs>(ctx, args!, ct);
|
||||||
|
}
|
||||||
26
BotPages.Core/Context/PageContextStorageExtensions.cs
Normal file
26
BotPages.Core/Context/PageContextStorageExtensions.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
using BotPages.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace BotPages.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения <see cref="PageContext"/> для работы с <see cref="IStateStorage"/>
|
||||||
|
/// </summary>
|
||||||
|
public static class PageContextStorageExtensions
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>Получить состояние по ключу.</summary>
|
||||||
|
public static Task<T?> GetStorageAsync<T>(this PageContext ctx, string key, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.GetAsync<T>(ctx.SessionKey, key, ct);
|
||||||
|
|
||||||
|
/// <summary>Сохранить состояние по ключу.</summary>
|
||||||
|
public static Task SetStorageAsync<T>(this PageContext ctx, string key, T state, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.SetAsync<T>(ctx.SessionKey, key, state, ct);
|
||||||
|
|
||||||
|
/// <summary>Удалить состояние по ключу.</summary>
|
||||||
|
public static Task<bool> RemoveStorageAsync(this PageContext ctx, string key, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.RemoveAsync(ctx.SessionKey, key, ct);
|
||||||
|
|
||||||
|
/// <summary>Удалить все состояния по ключу.</summary>
|
||||||
|
public static Task<bool> ClearStorageAsync(this PageContext ctx, CancellationToken ct)
|
||||||
|
=> ctx.StateStorage.ClearAsync(ctx.SessionKey, ct);
|
||||||
|
}
|
||||||
@@ -25,6 +25,9 @@ public class ButtonAttribute : Attribute
|
|||||||
public string? Value { get; }
|
public string? Value { get; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширение для работы с кнопками.
|
||||||
|
/// </summary>
|
||||||
public static class ButtonExtensions
|
public static class ButtonExtensions
|
||||||
{
|
{
|
||||||
private static readonly Dictionary<Type, Dictionary<string, object>> _cacheName = new();
|
private static readonly Dictionary<Type, Dictionary<string, object>> _cacheName = new();
|
||||||
|
|||||||
@@ -12,11 +12,10 @@ public sealed class MessageBuilder
|
|||||||
private MessageFormat _format = MessageFormat.Plain;
|
private MessageFormat _format = MessageFormat.Plain;
|
||||||
private readonly List<List<InlineButton>> _inline = new();
|
private readonly List<List<InlineButton>> _inline = new();
|
||||||
private readonly List<List<ReplyButton>> _reply = new();
|
private readonly List<List<ReplyButton>> _reply = new();
|
||||||
private readonly List<(FileDescriptor file, string? caption)> _files = new();
|
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new();
|
||||||
private readonly List<(FileDescriptor file, string? caption)> _album = new();
|
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
|
||||||
private string? _progressTitle = null;
|
private bool _disableReplyKeyboard;
|
||||||
private int? _progressPercent = null;
|
private string? _editMessageId = null;
|
||||||
private string? _progressMessageId = null;
|
|
||||||
|
|
||||||
/// <summary>Создать билдер сообщений.</summary>
|
/// <summary>Создать билдер сообщений.</summary>
|
||||||
public MessageBuilder(PageContext ctx) => _ctx = ctx;
|
public MessageBuilder(PageContext ctx) => _ctx = ctx;
|
||||||
@@ -29,6 +28,13 @@ public sealed class MessageBuilder
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Редактировать сообщение.</summary>
|
||||||
|
public MessageBuilder EditMessage(string messagId)
|
||||||
|
{
|
||||||
|
_editMessageId = messagId;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Добавить inline‑кнопку.</summary>
|
/// <summary>Добавить inline‑кнопку.</summary>
|
||||||
public MessageBuilder Inline(string label, string value)
|
public MessageBuilder Inline(string label, string value)
|
||||||
{
|
{
|
||||||
@@ -64,9 +70,20 @@ public sealed class MessageBuilder
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Отключение Reply клавиатуры.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public MessageBuilder DisableReply()
|
||||||
|
{
|
||||||
|
_disableReplyKeyboard = true;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Добавить reply‑кнопку.</summary>
|
/// <summary>Добавить reply‑кнопку.</summary>
|
||||||
public MessageBuilder Reply(params ReplyButton[] label)
|
public MessageBuilder Reply(params ReplyButton[] label)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.Add(label.ToList());
|
_reply.Add(label.ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -74,6 +91,7 @@ public sealed class MessageBuilder
|
|||||||
/// <summary>Добавить строку reply‑кнопок.</summary>
|
/// <summary>Добавить строку reply‑кнопок.</summary>
|
||||||
public MessageBuilder Reply(IEnumerable<ReplyButton> row)
|
public MessageBuilder Reply(IEnumerable<ReplyButton> row)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.Add(row.ToList());
|
_reply.Add(row.ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -81,73 +99,65 @@ public sealed class MessageBuilder
|
|||||||
/// <summary>Добавить строку reply‑кнопок.</summary>
|
/// <summary>Добавить строку reply‑кнопок.</summary>
|
||||||
public MessageBuilder Reply(IEnumerable<IEnumerable<ReplyButton>> row)
|
public MessageBuilder Reply(IEnumerable<IEnumerable<ReplyButton>> row)
|
||||||
{
|
{
|
||||||
|
_disableReplyKeyboard = false;
|
||||||
_reply.AddRange(row.Select(t => t.ToList()).ToList());
|
_reply.AddRange(row.Select(t => t.ToList()).ToList());
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Добавить файл для отправки.</summary>
|
/// <summary>Добавить файл для отправки.</summary>
|
||||||
public MessageBuilder File(FileDescriptor file, string? caption = null)
|
public MessageBuilder File(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null)
|
||||||
{
|
{
|
||||||
_files.Add((file, caption));
|
_files.Add((file, caption, captionFormat));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Добавить файл в альбом.</summary>
|
/// <summary>Добавить файл в альбом.</summary>
|
||||||
public MessageBuilder Album(FileDescriptor file, string? caption = null)
|
public MessageBuilder Album(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null)
|
||||||
{
|
{
|
||||||
_album.Add((file, caption));
|
_album.Add((file, caption, captionFormat));
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Установить прогресс операции.</summary>
|
|
||||||
public MessageBuilder Progress(string title, int percent = 0)
|
|
||||||
{
|
|
||||||
_progressTitle = title;
|
|
||||||
_progressPercent = percent;
|
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Отправить собранное сообщение.</summary>
|
/// <summary>Отправить собранное сообщение.</summary>
|
||||||
public async Task SendAsync(CancellationToken ct = default)
|
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;
|
||||||
|
|
||||||
// Текст
|
// Текст
|
||||||
if (!string.IsNullOrWhiteSpace(_text))
|
if (!string.IsNullOrWhiteSpace(_text))
|
||||||
{
|
{
|
||||||
await _ctx.SendTextAsync(_text, _format, _inline, _reply, ct);
|
messageId = await _ctx.SendTextAsync(_text, _format, _inline, reply, _editMessageId, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Файлы
|
// Файлы
|
||||||
foreach (var (file, caption) in _files)
|
foreach (var (file, caption, captionFormat) in _files)
|
||||||
await _ctx.SendFileAsync(file, caption, ct);
|
await _ctx.SendFileAsync(file: file
|
||||||
|
, caption: caption
|
||||||
|
, captionFormat: captionFormat
|
||||||
|
, reply: reply
|
||||||
|
, inline: _inline
|
||||||
|
, ct: ct
|
||||||
|
);
|
||||||
|
|
||||||
// Альбом
|
// Альбом
|
||||||
if (_album.Count > 0)
|
if (_album.Count > 0)
|
||||||
{
|
{
|
||||||
var builder = _ctx.Albums;
|
var builder = _ctx.Albums;
|
||||||
foreach (var (file, caption) in _album)
|
foreach (var (file, caption, captionFormat) in _album)
|
||||||
builder.Add(file, caption);
|
builder.Add(file, caption, captionFormat);
|
||||||
await builder.SendAsync(ct);
|
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;
|
_text = null;
|
||||||
_files.Clear();
|
_files.Clear();
|
||||||
_album.Clear();
|
_album.Clear();
|
||||||
|
|
||||||
if (_progressPercent >= 100)
|
_editMessageId = null;
|
||||||
{
|
|
||||||
_progressTitle = null;
|
return messageId;
|
||||||
_progressMessageId = null;
|
|
||||||
_progressPercent = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ public sealed class NavigationService
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перейти по маршруту без аргументов.
|
/// Перейти по маршруту без аргументов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Task GoToHome(PageContext ctx, CancellationToken ct)
|
public Task GoToHomeAsync(PageContext ctx, CancellationToken ct)
|
||||||
{
|
{
|
||||||
return NavigateAsync(_defaultPage!, ctx, null, ct);
|
return NavigateAsync(_defaultPage!, ctx, null, ct);
|
||||||
}
|
}
|
||||||
|
|||||||
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,40 @@
|
|||||||
|
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реестр команд, доступных из любого места.
|
/// Реестр команд, доступных из любого места.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class CommandsRegistry
|
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>
|
||||||
/// Зарегистрировать команду, ведущую на страницу.
|
/// Зарегистрировать команду, ведущую на страницу.
|
||||||
/// </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);
|
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>
|
||||||
/// Зарегистрировать команду с кастомным обработчиком.
|
/// Зарегистрировать команду с кастомным обработчиком.
|
||||||
/// </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);
|
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;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,11 +44,17 @@ internal sealed class CommandsRegistry
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool TryDispatch(PageContext ctx, string command, CancellationToken ct, out Task? task)
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,14 +62,27 @@ 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
|
|
||||||
var escaped = Regex.Escape(template)
|
var escaped = Regex.Escape(template)
|
||||||
.Replace("\\{", "{").Replace("\\}", "}");
|
.Replace("\\{", "{").Replace("\\}", "}");
|
||||||
var pattern = "^" + escaped
|
|
||||||
.Replace("{page}", "(?<page>\\S+)")
|
var pattern = "^" + Regex.Replace(escaped, @"\{(\w+)(\?)?\}", m =>
|
||||||
.Replace("{id?}", "(?<id>\\S+)?") + "$";
|
{
|
||||||
|
var name = m.Groups[1].Value;
|
||||||
|
var optional = m.Groups[2].Success;
|
||||||
|
return optional ? $"(?<{name}>\\S+)?" : $"(?<{name}>\\S+)";
|
||||||
|
}) + "$";
|
||||||
|
|
||||||
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
namespace BotPages.Core.Routing;
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace BotPages.Core.Routing;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реестр маршрутов страниц.
|
/// Реестр маршрутов страниц.
|
||||||
@@ -26,4 +28,14 @@ internal sealed class RoutesRegistry
|
|||||||
/// Получить снимок всех маршрутов.
|
/// Получить снимок всех маршрутов.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IReadOnlyDictionary<string, Type> Snapshot() => _routes;
|
public IReadOnlyDictionary<string, Type> Snapshot() => _routes;
|
||||||
|
|
||||||
|
internal void Map(Type? type)
|
||||||
|
{
|
||||||
|
foreach(var attr in type.GetCustomAttributes<RouteAttribute>(inherit: true))
|
||||||
|
{
|
||||||
|
_routes.Add(attr.Template, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
_routes.Add(type.FullName, type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ public sealed class InMemoryStateStorage : IStateStorage
|
|||||||
public Task<bool> RemoveAsync(CompositeSessionKey session, string key, CancellationToken ct)
|
public Task<bool> RemoveAsync(CompositeSessionKey session, string key, CancellationToken ct)
|
||||||
=> Task.FromResult(_store.TryGetValue(session, out var dict) ? dict.TryRemove(key, out _) : true);
|
=> Task.FromResult(_store.TryGetValue(session, out var dict) ? dict.TryRemove(key, out _) : true);
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
public Task<bool> ClearAsync(CompositeSessionKey session, CancellationToken ct)
|
public Task<bool> ClearAsync(CompositeSessionKey session, CancellationToken ct)
|
||||||
=> Task.FromResult(_store.TryRemove(session, out _));
|
=> Task.FromResult(_store.TryRemove(session, out _));
|
||||||
}
|
}
|
||||||
26
BotPages.Telegram/BotPagesAppExtension.cs
Normal file
26
BotPages.Telegram/BotPagesAppExtension.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
using BotPages.Core;
|
||||||
|
|
||||||
|
namespace BotPages.Telegram;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Расширения для <see cref="BotPagesApp"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static class BotPagesAppExtension
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Добавление адаптера для телеграмм в <see cref="BotPages.Core.Abstractions.IMessengerAdapterFactory"/>
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="app"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <param name="messengerType"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string messengerType = "")
|
||||||
|
{
|
||||||
|
var telegram = new TelegramAdapter(app.Logger, token);
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(messengerType)) telegram.MessengerType = messengerType;
|
||||||
|
|
||||||
|
app.AddAdapter(telegram.MessengerType, telegram);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,66 +21,97 @@ namespace BotPages.Telegram;
|
|||||||
/// Адаптер для Telegram на базе Telegram.Bot.
|
/// Адаптер для Telegram на базе Telegram.Bot.
|
||||||
/// Реализует отправку текста, кнопок, файлов, альбомов и прогресса.
|
/// Реализует отправку текста, кнопок, файлов, альбомов и прогресса.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class TelegramAdapter : IMessengerAdapter
|
public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||||
{
|
{
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private TelegramBotClient? _client;
|
private TelegramBotClient? _client;
|
||||||
|
private string _token;
|
||||||
|
private static Capabilities _capabilities = new()
|
||||||
|
{
|
||||||
|
SupportsInlineButtons = true,
|
||||||
|
SupportsReplyButtons = true,
|
||||||
|
SupportsAlbums = true,
|
||||||
|
SupportsFormattingMarkdown = true,
|
||||||
|
SupportsFormattingHtml = true,
|
||||||
|
MaxMessageLength = 4096,
|
||||||
|
};
|
||||||
|
|
||||||
/// <summary>Создать адаптер Telegram.</summary>
|
/// <summary>Создать адаптер Telegram.</summary>
|
||||||
public TelegramAdapter(ILogger logger) => _logger = logger;
|
public TelegramAdapter(ILogger logger, string token)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
///Идентификатор мессенджера / адаптера
|
||||||
|
/// </summary>
|
||||||
|
public string MessengerType { get; set; } = "Telegram: " + Guid.NewGuid().ToString();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Доступные возможности адаптера.
|
||||||
|
/// </summary>
|
||||||
|
public Capabilities Capabilities => _capabilities;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Запустить polling для приема обновлений от Telegram.
|
/// Запустить polling для приема обновлений от Telegram.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task StartPollingAsync(string token, 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);
|
_client = new TelegramBotClient(_token);
|
||||||
|
|
||||||
_client.StartReceiving(
|
_client.StartReceiving(
|
||||||
updateHandler: async (_, update, ct2) =>
|
updateHandler: async (_, update, ct2) =>
|
||||||
{
|
{
|
||||||
var mapped = TelegramUpdateMapper.Map(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);
|
||||||
},
|
},
|
||||||
|
|
||||||
errorHandler: async (_, ex, ct2) =>
|
errorHandler: async (_, ex, ct2) =>
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Warn, "Telegram error.", ex);
|
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex);
|
||||||
await Task.CompletedTask;
|
await Task.CompletedTask;
|
||||||
},
|
},
|
||||||
|
|
||||||
cancellationToken: ct
|
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();
|
var me = await _client.GetMe();
|
||||||
_logger.Log(LogLevel.Info, $"Telegram started: @{me.Username}");
|
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SendTextAsync(PageContext ctx, string text, MessageFormat format,
|
public async Task<string?> SendTextAsync(string chatId, string text,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
string? messageId = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, "Telegram client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
InlineKeyboardMarkup? inlineMarkup = null;
|
||||||
ReplyMarkup? markup = null;
|
ReplyMarkup? markup = null;
|
||||||
|
|
||||||
if (inline is not null && inline.Any())
|
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())
|
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
||||||
.ToArray()
|
.ToArray()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
else if (reply is not null && reply.Any())
|
else if (reply is not null)
|
||||||
|
{
|
||||||
|
if (reply.Any())
|
||||||
{
|
{
|
||||||
markup = new ReplyKeyboardMarkup(
|
markup = new ReplyKeyboardMarkup(
|
||||||
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
||||||
@@ -89,6 +120,11 @@ public sealed class TelegramAdapter : IMessengerAdapter
|
|||||||
ResizeKeyboard = true
|
ResizeKeyboard = true
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
markup = new ReplyKeyboardRemove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var parseMode = ParseMode.None;
|
var parseMode = ParseMode.None;
|
||||||
|
|
||||||
@@ -117,32 +153,57 @@ public sealed class TelegramAdapter : IMessengerAdapter
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Длина сообщения
|
// Длина сообщения
|
||||||
if (text.Length > ctx.Update.Chat.Capabilities.MaxMessageLength)
|
if (text.Length > Capabilities.MaxMessageLength)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Warn, $"Message too long ({text.Length}). Truncated to {ctx.Update.Chat.Capabilities.MaxMessageLength}.");
|
_logger.Log(LogLevel.Warn, $"Message too long ({text.Length}). Truncated to {Capabilities.MaxMessageLength}.");
|
||||||
text = text.Substring(0, ctx.Update.Chat.Capabilities.MaxMessageLength);
|
text = text.Substring(0, Capabilities.MaxMessageLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
await _client.SendMessage(
|
if (!string.IsNullOrWhiteSpace(messageId))
|
||||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
{
|
||||||
|
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,
|
text: text,
|
||||||
parseMode: parseMode,
|
parseMode: parseMode,
|
||||||
replyMarkup: markup,
|
replyMarkup: markup,
|
||||||
cancellationToken: ct
|
cancellationToken: ct
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return message.Id.ToString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SendFileAsync(PageContext ctx, FileDescriptor file, string? caption, 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)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, "Telegram client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var chatId = long.Parse(ctx.Update.Chat.Id);
|
|
||||||
|
|
||||||
// Получаем поток, если он задан
|
// Получаем поток, если он задан
|
||||||
Stream? stream = null;
|
Stream? stream = null;
|
||||||
if (file.GetStreamAsync is not null)
|
if (file.GetStreamAsync is not null)
|
||||||
@@ -166,20 +227,77 @@ public sealed class TelegramAdapter : IMessengerAdapter
|
|||||||
inputFile = new InputFileId(file.Id);
|
inputFile = new InputFileId(file.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var parseMode = ParseMode.None;
|
||||||
|
|
||||||
|
switch (captionFormat)
|
||||||
|
{
|
||||||
|
case MessageFormat.Html:
|
||||||
|
{
|
||||||
|
parseMode = ParseMode.Html;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MessageFormat.Plain:
|
||||||
|
{
|
||||||
|
parseMode = ParseMode.None;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case MessageFormat.Markdown:
|
||||||
|
{
|
||||||
|
parseMode = ParseMode.MarkdownV2;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case null:
|
||||||
|
{
|
||||||
|
parseMode = ParseMode.None;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
_logger.Log(LogLevel.Warn, $"MessageFormat '{captionFormat}' not supported. Degraded to plain text.");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 выбираем подходящий метод
|
// В зависимости от FileKind выбираем подходящий метод
|
||||||
switch (file.Kind)
|
switch (file.Kind)
|
||||||
{
|
{
|
||||||
case FileKind.Photo:
|
case FileKind.Photo:
|
||||||
await _client.SendPhoto(chatId, inputFile, caption ?? "", cancellationToken: ct);
|
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
case FileKind.Video:
|
case FileKind.Video:
|
||||||
await _client.SendVideo(chatId, inputFile, caption: caption ?? "", cancellationToken: ct);
|
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
case FileKind.Audio:
|
case FileKind.Audio:
|
||||||
await _client.SendAudio(chatId, inputFile, caption ?? "", cancellationToken: ct);
|
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
await _client.SendDocument(chatId, inputFile, caption ?? "", cancellationToken: ct);
|
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,62 +305,6 @@ public sealed class TelegramAdapter : IMessengerAdapter
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
|
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, "Telegram 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, "Telegram 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 />
|
/// <inheritdoc />
|
||||||
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
|
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
private readonly PageContext _ctx;
|
private readonly PageContext _ctx;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private readonly TelegramBotClient? _client;
|
private readonly TelegramBotClient? _client;
|
||||||
private readonly List<(FileDescriptor file, string? caption)> _items = new();
|
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _items = new();
|
||||||
|
|
||||||
/// <summary>Создать билдер альбома.</summary>
|
/// <summary>Создать билдер альбома.</summary>
|
||||||
public TelegramAlbumBuilder(TelegramAdapter adapter, PageContext ctx, ILogger logger, TelegramBotClient? client)
|
public TelegramAlbumBuilder(TelegramAdapter adapter, PageContext ctx, ILogger logger, TelegramBotClient? client)
|
||||||
@@ -32,9 +32,9 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public IAlbumBuilder Add(FileDescriptor file, string? caption = null)
|
public IAlbumBuilder Add(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null)
|
||||||
{
|
{
|
||||||
_items.Add((file, caption));
|
_items.Add((file, caption, captionFormat));
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,16 +49,16 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
|
|
||||||
var chatId = long.Parse(_ctx.Update.Chat.Id);
|
var chatId = long.Parse(_ctx.Update.Chat.Id);
|
||||||
|
|
||||||
if (!_ctx.Update.Chat.Capabilities.SupportsAlbums)
|
if (!_adapter.Capabilities.SupportsAlbums)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Warn, "Albums not supported. Degraded to sequential sends.");
|
_logger.Log(LogLevel.Warn, "Albums not supported. Degraded to sequential sends.");
|
||||||
foreach (var (file, caption) in _items)
|
foreach (var (file, caption, captionFormat) in _items)
|
||||||
await _adapter.SendFileAsync(_ctx, file, caption, ct);
|
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var media = new List<IAlbumInputMedia>();
|
var media = new List<IAlbumInputMedia>();
|
||||||
foreach (var (file, caption) in _items)
|
foreach (var (file, caption, captionFormat) in _items)
|
||||||
{
|
{
|
||||||
Stream? stream = null;
|
Stream? stream = null;
|
||||||
if (file.GetStreamAsync is not null)
|
if (file.GetStreamAsync is not null)
|
||||||
@@ -95,7 +95,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
{
|
{
|
||||||
// Telegram не поддерживает document в альбомах — деградация
|
// Telegram не поддерживает document в альбомах — деградация
|
||||||
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
|
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
|
||||||
await _adapter.SendFileAsync(_ctx, file, caption, ct);
|
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ public static class TelegramUpdateMapper
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Маппинг Telegram Update в UpdateContext BotPages.
|
/// Маппинг Telegram Update в UpdateContext BotPages.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static UpdateContext Map(Update update, TelegramBotClient client)
|
public static UpdateContext Map(string MessengerType, Update update, TelegramBotClient client)
|
||||||
{
|
{
|
||||||
var chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat;
|
var chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat;
|
||||||
var user = update.Message?.From ?? update.CallbackQuery?.From;
|
var user = update.Message?.From ?? update.CallbackQuery?.From;
|
||||||
@@ -34,15 +34,6 @@ public static class TelegramUpdateMapper
|
|||||||
{
|
{
|
||||||
Id = chat?.Id.ToString() ?? "unknown",
|
Id = chat?.Id.ToString() ?? "unknown",
|
||||||
Title = chat?.Title,
|
Title = chat?.Title,
|
||||||
Capabilities = new Capabilities
|
|
||||||
{
|
|
||||||
SupportsInlineButtons = true,
|
|
||||||
SupportsReplyButtons = true,
|
|
||||||
SupportsAlbums = true,
|
|
||||||
SupportsFormattingMarkdown = true,
|
|
||||||
SupportsFormattingHtml = true,
|
|
||||||
MaxMessageLength = 4096,
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
string? text = null;
|
string? text = null;
|
||||||
@@ -131,7 +122,7 @@ public static class TelegramUpdateMapper
|
|||||||
|
|
||||||
return new UpdateContext
|
return new UpdateContext
|
||||||
{
|
{
|
||||||
MessengerType = "Telegram",
|
MessengerType = MessengerType,
|
||||||
User = userContext,
|
User = userContext,
|
||||||
Chat = chatContext,
|
Chat = chatContext,
|
||||||
Text = text,
|
Text = text,
|
||||||
|
|||||||
@@ -2,8 +2,20 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
<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>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,10 +1,4 @@
|
|||||||
using System;
|
namespace Demo.Models
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace Demo.Models
|
|
||||||
{
|
{
|
||||||
internal class Request
|
internal class Request
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
using System.Xml;
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
|
|
||||||
@@ -8,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);
|
||||||
@@ -43,7 +43,8 @@ public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
|||||||
await ctx.Navigation.GoToAsync<TitlePage>(ctx, ct);
|
await ctx.Navigation.GoToAsync<TitlePage>(ctx, ct);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task OnText(PageContext ctx, string text, CancellationToken ct)
|
public override async Task OnText(PageContext ctx, string text, CancellationToken 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
|
|
||||||
{
|
{
|
||||||
public string Title { get; set; } = "";
|
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;
|
||||||
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;
|
||||||
|
|
||||||
|
[Route("FileSend")]
|
||||||
public sealed class FileSendPage : SingletonPage
|
public sealed class FileSendPage : SingletonPage
|
||||||
{
|
{
|
||||||
public override Task OnEnter(PageContext ctx, CancellationToken ct)
|
public override Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public sealed class FilesPage : SingletonPage
|
|||||||
{
|
{
|
||||||
foreach (var file in files)
|
foreach (var file in files)
|
||||||
{
|
{
|
||||||
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct);
|
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct: ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Обращение через Storage
|
//Обращение через Storage
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ public sealed class SubmitPage : SingletonPage
|
|||||||
{
|
{
|
||||||
var progress = new MessageBuilder(ctx);
|
var progress = new MessageBuilder(ctx);
|
||||||
|
|
||||||
await progress
|
var messageId = await progress
|
||||||
.Progress("Отправка заявки", 7)
|
.Text("Отправка заявки\n7%")
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
|
|
||||||
int i = 7;
|
int i = 7;
|
||||||
@@ -22,12 +22,13 @@ public sealed class SubmitPage : SingletonPage
|
|||||||
i += 25;
|
i += 25;
|
||||||
Thread.Sleep(TimeSpan.FromMilliseconds(200));
|
Thread.Sleep(TimeSpan.FromMilliseconds(200));
|
||||||
await progress
|
await progress
|
||||||
.Progress("Отправка заявки", i)
|
.Text($"Отправка заявки\n{i}%")
|
||||||
|
.EditMessage(messageId!)
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
}
|
}
|
||||||
while (i < 100);
|
while (i < 100);
|
||||||
|
|
||||||
await ctx.Navigation.GoToHome(ctx, ct);
|
await ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task OnLeave(PageContext ctx, CancellationToken ct)
|
public override Task OnLeave(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
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>
|
||||||
@@ -19,11 +20,11 @@ public sealed class TitlePage : SingletonPage
|
|||||||
{
|
{
|
||||||
if (text == "Меню")
|
if (text == "Меню")
|
||||||
{
|
{
|
||||||
return ctx.Navigation.GoToHome(ctx, ct);
|
return ctx.Navigation.GoToHomeAsync(ctx, ct);
|
||||||
}
|
}
|
||||||
else
|
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;
|
||||||
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;
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ namespace Demo.Pages;
|
|||||||
/// Стартовая страница демо‑бота.
|
/// Стартовая страница демо‑бота.
|
||||||
/// Обычная страница с кнопками
|
/// Обычная страница с кнопками
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[Route("Welcome")]
|
||||||
public sealed class WelcomePage : SingletonPage
|
public sealed class WelcomePage : SingletonPage
|
||||||
{
|
{
|
||||||
public override async Task OnEnter(PageContext ctx, CancellationToken ct)
|
public override async Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Abstractions;
|
|
||||||
using BotPages.Core.Logging;
|
using BotPages.Core.Logging;
|
||||||
using BotPages.Core.Middleware;
|
using BotPages.Core.Middleware;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
using BotPages.Core.Storage;
|
using BotPages.Core.Storage;
|
||||||
using BotPages.Telegram;
|
using BotPages.Telegram;
|
||||||
using Demo.Pages;
|
using Demo.Pages;
|
||||||
@@ -17,22 +17,33 @@ namespace Demo
|
|||||||
|
|
||||||
var logger = new ConsoleLogger();
|
var logger = new ConsoleLogger();
|
||||||
var state = new InMemoryStateStorage();
|
var state = new InMemoryStateStorage();
|
||||||
|
|
||||||
var telegram = new TelegramAdapter(logger);
|
|
||||||
var factory = new MultiAdapterFactory()
|
|
||||||
.Register("Telegram", telegram);
|
|
||||||
|
|
||||||
var app = new BotPagesApp(factory, state, logger)
|
|
||||||
.AddDefaultPage<WelcomePage>()
|
|
||||||
.MapCommand<WelcomePage>("/start")
|
|
||||||
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
|
||||||
.AddMiddleware(new LoggingMiddleware(logger));
|
|
||||||
|
|
||||||
using var cts = new CancellationTokenSource();
|
using var cts = new CancellationTokenSource();
|
||||||
|
|
||||||
await telegram.StartPollingAsync(token,
|
// Можно использовать команды для открытия страниц с роутингом
|
||||||
update => app.HandleUpdateAsync(update, CancellationToken.None),
|
// /open Welcome
|
||||||
cts.Token);
|
// /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", 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")
|
||||||
|
.Build(cts.Token);
|
||||||
|
|
||||||
Console.ReadKey();
|
Console.ReadKey();
|
||||||
cts.Cancel();
|
cts.Cancel();
|
||||||
|
|||||||
5
TZ.md
5
TZ.md
@@ -17,7 +17,6 @@
|
|||||||
- **Page** — класс, отвечающий за состояние экрана бота.
|
- **Page** — класс, отвечающий за состояние экрана бота.
|
||||||
- `Page` — базовый класс.
|
- `Page` — базовый класс.
|
||||||
- `Page<TArguments>` — страница с аргументами.
|
- `Page<TArguments>` — страница с аргументами.
|
||||||
- `ModalPage` / `ModalPage<TArguments>` — модальная страница (перехватывает ввод, блокирует переходы).
|
|
||||||
- **Контекст:**
|
- **Контекст:**
|
||||||
- `UserContext` — данные пользователя (UserId, MessengerType).
|
- `UserContext` — данные пользователя (UserId, MessengerType).
|
||||||
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
|
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
|
||||||
@@ -25,7 +24,7 @@
|
|||||||
- **Состояние:**
|
- **Состояние:**
|
||||||
- `IStateStorage` — универсальный интерфейс хранения.
|
- `IStateStorage` — универсальный интерфейс хранения.
|
||||||
- Базовая реализация: InMemory.
|
- Базовая реализация: InMemory.
|
||||||
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId?)`.
|
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId)`.
|
||||||
- История состояний: опционально (None, LastN, TimeWindow, Full).
|
- История состояний: опционально (None, LastN, TimeWindow, Full).
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -125,7 +124,7 @@
|
|||||||
```
|
```
|
||||||
- Пример:
|
- Пример:
|
||||||
```csharp
|
```csharp
|
||||||
app.AddMiddleware<IUpdateMiddleware, LoggingMiddleware>();
|
app.AddMiddleware<LoggingMiddleware>();
|
||||||
app.AddMiddleware<ErrorMiddleware>(params);
|
app.AddMiddleware<ErrorMiddleware>(params);
|
||||||
```
|
```
|
||||||
- Порядок регистрации = порядок выполнения.
|
- Порядок регистрации = порядок выполнения.
|
||||||
|
|||||||
Reference in New Issue
Block a user