Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f9584c5afe | |||
| 07df710ce6 | |||
| d97fcaaa20 | |||
| 308f1af33a | |||
| 5085958219 | |||
| 634a9292dc |
@@ -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);
|
||||||
}
|
}
|
||||||
@@ -9,17 +9,19 @@ namespace BotPages.Core.Abstractions;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IMessengerAdapter
|
public interface IMessengerAdapter
|
||||||
{
|
{
|
||||||
|
Capabilities Capabilities { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение в чат.
|
/// Отправить текстовое сообщение в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendTextAsync(PageContext ctx, string text, MessageFormat format,
|
Task SendTextAsync(string chatId, string text, MessageFormat format,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
|
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл в чат.
|
/// Отправить файл в чат.
|
||||||
/// </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>
|
/// <summary>
|
||||||
/// Создать билдер альбома для отправки медиагруппы.
|
/// Создать билдер альбома для отправки медиагруппы.
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -90,6 +91,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>
|
||||||
|
|||||||
@@ -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();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,13 +49,19 @@ public sealed class PageContext
|
|||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
=> Adapter.SendTextAsync(this, text, format, inline, reply, ct);
|
=> 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>
|
||||||
/// Отправить файл.
|
/// Отправить файл.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Task SendFileAsync(FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
public Task SendFileAsync(FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
||||||
=> Adapter.SendFileAsync(this, file, caption, ct);
|
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, null, ct);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить билдер альбомов.
|
/// Получить билдер альбомов.
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ 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 string? _progressTitle = null;
|
||||||
private int? _progressPercent = null;
|
private int? _progressPercent = null;
|
||||||
private string? _progressMessageId = null;
|
private string? _progressMessageId = null;
|
||||||
@@ -86,16 +86,16 @@ public sealed class MessageBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <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;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,15 +117,15 @@ public sealed class MessageBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Файлы
|
// Файлы
|
||||||
foreach (var (file, caption) in _files)
|
foreach (var (file, caption, captionFormat) in _files)
|
||||||
await _ctx.SendFileAsync(file, caption, ct);
|
await _ctx.SendFileAsync(file, caption, captionFormat, 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,15 @@ public static class BotPagesAppExtension
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="app"></param>
|
/// <param name="app"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
|
/// <param name="messengerType"></param>
|
||||||
/// <returns></returns>
|
/// <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);
|
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;
|
return app;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,20 +26,32 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
private TelegramBotClient? _client;
|
private TelegramBotClient? _client;
|
||||||
private string _token;
|
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>
|
/// <summary>Создать адаптер Telegram.</summary>
|
||||||
public TelegramAdapter(ILogger logger, string token)
|
public TelegramAdapter(ILogger logger, string token)
|
||||||
{
|
{
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_token = token;
|
_token = token;
|
||||||
_messagerType = "Telegram: " + Guid.NewGuid().ToString();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///Идентификатор мессенджера / адаптера
|
///Идентификатор мессенджера / адаптера
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string MessagerType => _messagerType;
|
public string MessengerType { get; set; } = "Telegram: " + Guid.NewGuid().ToString();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Доступные возможности адаптера.
|
||||||
|
/// </summary>
|
||||||
|
public Capabilities Capabilities => _capabilities;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Запустить polling для приема обновлений от Telegram.
|
/// Запустить polling для приема обновлений от Telegram.
|
||||||
@@ -51,14 +63,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
_client.StartReceiving(
|
_client.StartReceiving(
|
||||||
updateHandler: async (_, update, ct2) =>
|
updateHandler: async (_, update, ct2) =>
|
||||||
{
|
{
|
||||||
var mapped = TelegramUpdateMapper.Map(_messagerType, 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, $"{_messagerType} error.", ex);
|
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex);
|
||||||
await Task.CompletedTask;
|
await Task.CompletedTask;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -67,19 +79,19 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
|
|
||||||
|
|
||||||
var me = await _client.GetMe();
|
var me = await _client.GetMe();
|
||||||
_logger.Log(LogLevel.Info, $"{_messagerType} 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 SendTextAsync(string chatId, string text, MessageFormat format,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
IEnumerable<IEnumerable<InlineButton>>? inline,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
|
IEnumerable<IEnumerable<ReplyButton>>? reply, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,14 +141,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}.");
|
_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(
|
await _client.SendMessage(
|
||||||
chatId: long.Parse(ctx.Update.Chat.Id),
|
chatId: long.Parse(chatId),
|
||||||
text: text,
|
text: text,
|
||||||
parseMode: parseMode,
|
parseMode: parseMode,
|
||||||
replyMarkup: markup,
|
replyMarkup: markup,
|
||||||
@@ -145,16 +157,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <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)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, $"{_messagerType} 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)
|
||||||
@@ -178,20 +188,51 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// В зависимости от 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, 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, 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, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
await _client.SendDocument(chatId, inputFile, caption ?? "", cancellationToken: ct);
|
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,7 +245,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,7 +269,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Critical, $"{_messagerType} client is not initialized.");
|
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ public static class TelegramUpdateMapper
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Маппинг Telegram Update в UpdateContext BotPages.
|
/// Маппинг Telegram Update в UpdateContext BotPages.
|
||||||
/// </summary>
|
/// </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 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 = MessagerType,
|
MessengerType = MessengerType,
|
||||||
User = userContext,
|
User = userContext,
|
||||||
Chat = chatContext,
|
Chat = chatContext,
|
||||||
Text = text,
|
Text = text,
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ namespace Demo
|
|||||||
.MapCommand<WelcomePage>("/start")
|
.MapCommand<WelcomePage>("/start")
|
||||||
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
||||||
.AddMiddleware(new LoggingMiddleware(logger))
|
.AddMiddleware(new LoggingMiddleware(logger))
|
||||||
.AddTelegramAdapter(token)
|
.AddTelegramAdapter(token, "Telegram")
|
||||||
.Build(cts.Token);
|
.Build(cts.Token);
|
||||||
|
|
||||||
Console.ReadKey();
|
Console.ReadKey();
|
||||||
|
|||||||
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