8 Commits

Author SHA1 Message Date
fce6e8d013 Добавлено скрытие Reply клавиатуры
All checks were successful
CI / build-test (push) Successful in 35s
Release / pack-and-publish (release) Successful in 34s
2025-12-06 08:36:04 +03:00
57b3706241 Выделены отдельные расширения
All checks were successful
CI / build-test (push) Successful in 29s
Release / pack-and-publish (release) Successful in 32s
2025-12-06 07:52:01 +03:00
f9584c5afe доработка роутинга
All checks were successful
CI / build-test (push) Successful in 48s
Release / pack-and-publish (release) Successful in 34s
2025-12-06 07:31:59 +03:00
07df710ce6 Добавлено автоматические заполнение маршрутов для страниц 2025-12-06 07:31:18 +03:00
d97fcaaa20 Доработан формат подписи файлов
All checks were successful
CI / build-test (push) Successful in 35s
Release / pack-and-publish (release) Successful in 38s
2025-12-05 20:13:27 +03:00
308f1af33a Добавлен формат сообщения при отправке документа
Some checks failed
CI / build-test (push) Failing after 36s
Release / pack-and-publish (release) Failing after 34s
2025-12-05 20:04:42 +03:00
5085958219 Доработан адаптер телеграма
All checks were successful
CI / build-test (push) Successful in 36s
Release / pack-and-publish (release) Successful in 39s
2025-12-05 19:54:22 +03:00
634a9292dc Добавлена возможность отсылать сообщения в другие чаты
All checks were successful
CI / build-test (push) Successful in 33s
2025-12-05 19:45:59 +03:00
19 changed files with 281 additions and 110 deletions

View File

@@ -6,7 +6,7 @@
public interface IAlbumBuilder
{
/// <summary>Добавить элемент в альбом.</summary>
IAlbumBuilder Add(FileDescriptor file, string? caption = null);
IAlbumBuilder Add(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null);
/// <summary>Отправить альбом.</summary>
Task SendAsync(CancellationToken ct = default);
}

View File

@@ -9,17 +9,19 @@ namespace BotPages.Core.Abstractions;
/// </summary>
public interface IMessengerAdapter
{
Capabilities Capabilities { get; }
/// <summary>
/// Отправить текстовое сообщение в чат.
/// </summary>
Task SendTextAsync(PageContext ctx, string text, MessageFormat format,
Task SendTextAsync(string chatId, string text, MessageFormat format,
IEnumerable<IEnumerable<InlineButton>>? inline,
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
/// <summary>
/// Отправить файл в чат.
/// </summary>
Task SendFileAsync(PageContext ctx, FileDescriptor file, string? caption, CancellationToken ct);
Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct);
/// <summary>
/// Создать билдер альбома для отправки медиагруппы.

View File

@@ -4,6 +4,7 @@ using BotPages.Core.Abstractions;
using BotPages.Core.Context;
using BotPages.Core.Logging;
using BotPages.Core.Routing;
using System.Reflection;
/// <summary>
/// Основное приложение BotPages.
@@ -90,6 +91,45 @@ public sealed class BotPagesApp
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>
@@ -161,7 +201,7 @@ public sealed class BotPagesApp
if (page is null)
{
await ctx.Navigation.GoToHome(ctx, ct);
await ctx.Navigation.GoToHomeAsync(ctx, ct);
return;
}

View File

@@ -15,7 +15,4 @@ public sealed class ChatContext
/// <summary>Идентификатор треда (опционально).</summary>
public string? ThreadId { get; init; }
/// <summary>Возможности мессенджера.</summary>
public Capabilities Capabilities { get; init; } = new();
}

View File

@@ -22,41 +22,6 @@ public sealed class PageContext
/// <summary>Адаптер мессенджера.</summary>
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>

View File

@@ -0,0 +1,31 @@
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 SendTextAsync(this PageContext ctx, string text, MessageFormat format = MessageFormat.Plain,
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
CancellationToken ct = default)
=> ctx.Adapter.SendTextAsync(ctx.Update.Chat.Id, text, format, inline, reply, 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);
}

View 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);
}

View 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);
}

View File

@@ -12,11 +12,12 @@ public sealed class MessageBuilder
private MessageFormat _format = MessageFormat.Plain;
private readonly List<List<InlineButton>> _inline = new();
private readonly List<List<ReplyButton>> _reply = new();
private readonly List<(FileDescriptor file, string? caption)> _files = new();
private readonly List<(FileDescriptor file, string? caption)> _album = 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;
/// <summary>Создать билдер сообщений.</summary>
public MessageBuilder(PageContext ctx) => _ctx = ctx;
@@ -64,9 +65,20 @@ public sealed class MessageBuilder
return this;
}
/// <summary>
/// Отключение Reply клавиатуры.
/// </summary>
/// <returns></returns>
public MessageBuilder DisableReply()
{
_disableReplyKeyboard = true;
return this;
}
/// <summary>Добавить replyкнопку.</summary>
public MessageBuilder Reply(params ReplyButton[] label)
{
_disableReplyKeyboard = false;
_reply.Add(label.ToList());
return this;
}
@@ -74,6 +86,7 @@ public sealed class MessageBuilder
/// <summary>Добавить строку replyкнопок.</summary>
public MessageBuilder Reply(IEnumerable<ReplyButton> row)
{
_disableReplyKeyboard = false;
_reply.Add(row.ToList());
return this;
}
@@ -81,21 +94,22 @@ public sealed class MessageBuilder
/// <summary>Добавить строку replyкнопок.</summary>
public MessageBuilder Reply(IEnumerable<IEnumerable<ReplyButton>> row)
{
_disableReplyKeyboard = false;
_reply.AddRange(row.Select(t => t.ToList()).ToList());
return this;
}
/// <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;
}
/// <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;
}
@@ -113,19 +127,23 @@ public sealed class MessageBuilder
// Текст
if (!string.IsNullOrWhiteSpace(_text))
{
await _ctx.SendTextAsync(_text, _format, _inline, _reply, ct);
List<List<ReplyButton>>? reply = null;
if (_disableReplyKeyboard) reply = new();
else if (_reply.Any()) reply = _reply;
await _ctx.SendTextAsync(_text, _format, _inline, reply, ct);
}
// Файлы
foreach (var (file, caption) in _files)
await _ctx.SendFileAsync(file, caption, ct);
foreach (var (file, caption, captionFormat) in _files)
await _ctx.SendFileAsync(file, caption, captionFormat, ct);
// Альбом
if (_album.Count > 0)
{
var builder = _ctx.Albums;
foreach (var (file, caption) in _album)
builder.Add(file, caption);
foreach (var (file, caption, captionFormat) in _album)
builder.Add(file, caption, captionFormat);
await builder.SendAsync(ct);
}

View File

@@ -31,7 +31,7 @@ public sealed class NavigationService
/// <summary>
/// Перейти по маршруту без аргументов.
/// </summary>
public Task GoToHome(PageContext ctx, CancellationToken ct)
public Task GoToHomeAsync(PageContext ctx, CancellationToken ct)
{
return NavigateAsync(_defaultPage!, ctx, null, ct);
}

View File

@@ -1,4 +1,6 @@
namespace BotPages.Core.Routing;
using System.Reflection;
namespace BotPages.Core.Routing;
/// <summary>
/// Реестр маршрутов страниц.
@@ -26,4 +28,14 @@ internal sealed class RoutesRegistry
/// Получить снимок всех маршрутов.
/// </summary>
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);
}
}

View File

@@ -12,11 +12,15 @@ public static class BotPagesAppExtension
/// </summary>
/// <param name="app"></param>
/// <param name="token"></param>
/// <param name="messengerType"></param>
/// <returns></returns>
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token)
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string messengerType = "")
{
var telegram = new TelegramAdapter(app.Logger, token);
app.AddAdapter(telegram.MessagerType, telegram);
if (!string.IsNullOrWhiteSpace(messengerType)) telegram.MessengerType = messengerType;
app.AddAdapter(telegram.MessengerType, telegram);
return app;
}
}

View File

@@ -26,20 +26,32 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
private readonly ILogger _logger;
private TelegramBotClient? _client;
private string _token;
private string _messagerType;
private static Capabilities _capabilities = new()
{
SupportsInlineButtons = true,
SupportsReplyButtons = true,
SupportsAlbums = true,
SupportsFormattingMarkdown = true,
SupportsFormattingHtml = true,
MaxMessageLength = 4096,
};
/// <summary>Создать адаптер Telegram.</summary>
public TelegramAdapter(ILogger logger, string token)
{
_logger = logger;
_token = token;
_messagerType = "Telegram: " + Guid.NewGuid().ToString();
}
/// <summary>
///Идентификатор мессенджера / адаптера
/// </summary>
public string MessagerType => _messagerType;
public string MessengerType { get; set; } = "Telegram: " + Guid.NewGuid().ToString();
/// <summary>
/// Доступные возможности адаптера.
/// </summary>
public Capabilities Capabilities => _capabilities;
/// <summary>
/// Запустить polling для приема обновлений от Telegram.
@@ -51,14 +63,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
_client.StartReceiving(
updateHandler: async (_, update, ct2) =>
{
var mapped = TelegramUpdateMapper.Map(_messagerType, update, _client);
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
if (mapped is not null)
await onUpdate(mapped);
},
errorHandler: async (_, ex, ct2) =>
{
_logger.Log(LogLevel.Warn, $"{_messagerType} error.", ex);
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex);
await Task.CompletedTask;
},
@@ -67,19 +79,19 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
var me = await _client.GetMe();
_logger.Log(LogLevel.Info, $"{_messagerType} started: @{me.Username}");
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
return;
}
/// <inheritdoc />
public async Task SendTextAsync(PageContext ctx, string text, MessageFormat format,
public async Task SendTextAsync(string chatId, string text, MessageFormat format,
IEnumerable<IEnumerable<InlineButton>>? inline,
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return;
}
@@ -92,14 +104,21 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
.ToArray()
);
}
else if (reply is not null && reply.Any())
else if (reply is not null)
{
markup = new ReplyKeyboardMarkup(
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
)
if (reply.Any())
{
ResizeKeyboard = true
};
markup = new ReplyKeyboardMarkup(
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
)
{
ResizeKeyboard = true
};
}
else
{
markup = new ReplyKeyboardRemove();
}
}
var parseMode = ParseMode.None;
@@ -129,14 +148,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
}
// Длина сообщения
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}.");
text = text.Substring(0, ctx.Update.Chat.Capabilities.MaxMessageLength);
_logger.Log(LogLevel.Warn, $"Message too long ({text.Length}). Truncated to {Capabilities.MaxMessageLength}.");
text = text.Substring(0, Capabilities.MaxMessageLength);
}
await _client.SendMessage(
chatId: long.Parse(ctx.Update.Chat.Id),
chatId: long.Parse(chatId),
text: text,
parseMode: parseMode,
replyMarkup: markup,
@@ -145,16 +164,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
}
/// <inheritdoc />
public async Task SendFileAsync(PageContext ctx, FileDescriptor file, string? caption, CancellationToken ct)
public async Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return;
}
var chatId = long.Parse(ctx.Update.Chat.Id);
// Получаем поток, если он задан
Stream? stream = null;
if (file.GetStreamAsync is not null)
@@ -178,20 +195,51 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
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;
}
}
// В зависимости от FileKind выбираем подходящий метод
switch (file.Kind)
{
case FileKind.Photo:
await _client.SendPhoto(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
break;
case FileKind.Video:
await _client.SendVideo(chatId, inputFile, caption: caption ?? "", cancellationToken: ct);
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, cancellationToken: ct);
break;
case FileKind.Audio:
await _client.SendAudio(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
break;
default:
await _client.SendDocument(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
break;
}
}
@@ -204,7 +252,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return null;
}
@@ -228,7 +276,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return;
}

View File

@@ -20,7 +20,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
private readonly PageContext _ctx;
private readonly ILogger _logger;
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>
public TelegramAlbumBuilder(TelegramAdapter adapter, PageContext ctx, ILogger logger, TelegramBotClient? client)
@@ -32,9 +32,9 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
}
/// <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;
}
@@ -49,16 +49,16 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
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.");
foreach (var (file, caption) in _items)
await _adapter.SendFileAsync(_ctx, file, caption, ct);
foreach (var (file, caption, captionFormat) in _items)
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
return;
}
var media = new List<IAlbumInputMedia>();
foreach (var (file, caption) in _items)
foreach (var (file, caption, captionFormat) in _items)
{
Stream? stream = null;
if (file.GetStreamAsync is not null)
@@ -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, file, caption, ct);
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
}
}

View File

@@ -19,7 +19,7 @@ public static class TelegramUpdateMapper
/// <summary>
/// Маппинг Telegram Update в UpdateContext BotPages.
/// </summary>
public static UpdateContext Map(string MessagerType, Update update, TelegramBotClient client)
public static UpdateContext Map(string MessengerType, Update update, TelegramBotClient client)
{
var chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat;
var user = update.Message?.From ?? update.CallbackQuery?.From;
@@ -34,15 +34,6 @@ public static class TelegramUpdateMapper
{
Id = chat?.Id.ToString() ?? "unknown",
Title = chat?.Title,
Capabilities = new Capabilities
{
SupportsInlineButtons = true,
SupportsReplyButtons = true,
SupportsAlbums = true,
SupportsFormattingMarkdown = true,
SupportsFormattingHtml = true,
MaxMessageLength = 4096,
}
};
string? text = null;
@@ -131,7 +122,7 @@ public static class TelegramUpdateMapper
return new UpdateContext
{
MessengerType = MessagerType,
MessengerType = MessengerType,
User = userContext,
Chat = chatContext,
Text = text,

View File

@@ -27,7 +27,7 @@ public sealed class SubmitPage : SingletonPage
}
while (i < 100);
await ctx.Navigation.GoToHome(ctx, ct);
await ctx.Navigation.GoToHomeAsync(ctx, ct);
}
public override Task OnLeave(PageContext ctx, CancellationToken ct)

View File

@@ -19,7 +19,7 @@ public sealed class TitlePage : SingletonPage
{
if (text == "Меню")
{
return ctx.Navigation.GoToHome(ctx, ct);
return ctx.Navigation.GoToHomeAsync(ctx, ct);
}
else
{

View File

@@ -23,7 +23,7 @@ namespace Demo
.MapCommand<WelcomePage>("/start")
.AddMiddleware(new ErrorHandlingMiddleware(logger))
.AddMiddleware(new LoggingMiddleware(logger))
.AddTelegramAdapter(token)
.AddTelegramAdapter(token, "Telegram")
.Build(cts.Token);
Console.ReadKey();

5
TZ.md
View File

@@ -17,7 +17,6 @@
- **Page** — класс, отвечающий за состояние экрана бота.
- `Page` — базовый класс.
- `Page<TArguments>` — страница с аргументами.
- `ModalPage` / `ModalPage<TArguments>` — модальная страница (перехватывает ввод, блокирует переходы).
- **Контекст:**
- `UserContext` — данные пользователя (UserId, MessengerType).
- `ChatContext` — данные чата (ChatId, Title, ThreadId?, ленивое обновление).
@@ -25,7 +24,7 @@
- **Состояние:**
- `IStateStorage` — универсальный интерфейс хранения.
- Базовая реализация: InMemory.
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId?)`.
- Ключ: `CompositeSessionKey(MessengerType:string, ChatId, UserId)`.
- История состояний: опционально (None, LastN, TimeWindow, Full).
---
@@ -125,7 +124,7 @@
```
- Пример:
```csharp
app.AddMiddleware<IUpdateMiddleware, LoggingMiddleware>();
app.AddMiddleware<LoggingMiddleware>();
app.AddMiddleware<ErrorMiddleware>(params);
```
- Порядок регистрации = порядок выполнения.