Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9584c5afe | |||
| 07df710ce6 | |||
| d97fcaaa20 | |||
| 308f1af33a |
@@ -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);
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public interface IMessengerAdapter
|
||||
/// <summary>
|
||||
/// Отправить файл в чат.
|
||||
/// </summary>
|
||||
Task SendFileAsync(string chatId, FileDescriptor file, string? caption, CancellationToken ct);
|
||||
Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Создать билдер альбома для отправки медиагруппы.
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -51,11 +51,17 @@ public sealed class PageContext
|
||||
CancellationToken ct = default)
|
||||
=> Adapter.SendTextAsync(this.Update.Chat.Id, text, format, inline, reply, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Отправить файл.
|
||||
/// </summary>
|
||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null, CancellationToken ct = default)
|
||||
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Отправить файл.
|
||||
/// </summary>
|
||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
||||
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, ct);
|
||||
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, null, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Получить билдер альбомов.
|
||||
|
||||
@@ -12,8 +12,8 @@ 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;
|
||||
@@ -86,16 +86,16 @@ public sealed class MessageBuilder
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
@@ -117,15 +117,15 @@ public sealed class MessageBuilder
|
||||
}
|
||||
|
||||
// Файлы
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SendFileAsync(string chatId, FileDescriptor file, string? caption, CancellationToken ct)
|
||||
public async Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct)
|
||||
{
|
||||
if (_client is null)
|
||||
{
|
||||
@@ -188,20 +188,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(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
|
||||
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
break;
|
||||
case FileKind.Video:
|
||||
await _client.SendVideo(long.Parse(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(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
|
||||
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
break;
|
||||
default:
|
||||
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
|
||||
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -52,13 +52,13 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
||||
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.Update.Chat.Id, 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.Update.Chat.Id, file, caption, ct);
|
||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
5
TZ.md
5
TZ.md
@@ -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);
|
||||
```
|
||||
- Порядок регистрации = порядок выполнения.
|
||||
|
||||
Reference in New Issue
Block a user