2 Commits

Author SHA1 Message Date
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
8 changed files with 50 additions and 46 deletions

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, CancellationToken ct);
/// <summary>
/// Создать билдер альбома для отправки медиагруппы.

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

@@ -49,13 +49,13 @@ public sealed class PageContext
IEnumerable<IEnumerable<InlineButton>>? inline = null,
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
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, CancellationToken ct = default)
=> Adapter.SendFileAsync(this, file, caption, ct);
=> Adapter.SendFileAsync(this.Update.Chat.Id, file, caption, ct);
/// <summary>
/// Получить билдер альбомов.

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;
}
@@ -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}.");
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 +157,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, 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)
@@ -182,16 +192,16 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
switch (file.Kind)
{
case FileKind.Photo:
await _client.SendPhoto(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
break;
case FileKind.Video:
await _client.SendVideo(chatId, inputFile, caption: caption ?? "", cancellationToken: ct);
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", cancellationToken: ct);
break;
case FileKind.Audio:
await _client.SendAudio(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
break;
default:
await _client.SendDocument(chatId, inputFile, caption ?? "", cancellationToken: ct);
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", cancellationToken: ct);
break;
}
}
@@ -204,7 +214,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 +238,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

@@ -49,11 +49,11 @@ 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);
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, ct);
return;
}
@@ -95,7 +95,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
{
// Telegram не поддерживает document в альбомах — деградация
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
await _adapter.SendFileAsync(_ctx, file, caption, ct);
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, 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

@@ -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();