Доработка работы с несколькими адаптерами

This commit is contained in:
2026-02-06 07:45:19 +03:00
parent cd280369bc
commit 5dc071c750
10 changed files with 79 additions and 165 deletions

View File

@@ -20,7 +20,7 @@ namespace BotPages.Telegram;
/// Адаптер для Telegram на базе Telegram.Bot.
/// Реализует отправку текста, кнопок, файлов, альбомов и прогресса.
/// </summary>
public sealed class TelegramAdapter : MessengerAdapterBase
public sealed class TelegramAdapter : IMessengerAdapterSetup
{
private readonly ILogger _logger;
private TelegramBotClient? _client;
@@ -43,27 +43,33 @@ public sealed class TelegramAdapter : MessengerAdapterBase
_token = token;
_options = options ?? new TelegramOptions();
// Устанавливаем имя для отображения
DisplayName = $"Telegram Bot";
Id = Guid.NewGuid().ToString();
DisplayName = $"Telegram {Id}";
}
/// <summary>Тип адаптера.</summary>
public override string AdapterType => "Telegram";
/// <inheritdoc/>
public string Type => "Telegram";
/// <inheritdoc/>
public string Id { get; set; }
/// <summary>
/// Идентификатор мессенджера / адаптера
/// Получение отображаемого имени бота (например, "Telegram: @mybot"). Доступно после запуска адаптера.
/// </summary>
public string MessengerType => "Telegram";
public string DisplayName { get; private set; }
/// <inheritdoc/>
public void SetAdapterId(string adapterId) => Id = adapterId;
/// <summary>
/// Доступные возможности адаптера.
/// </summary>
public override Capabilities Capabilities => _capabilities;
public Capabilities Capabilities => _capabilities;
/// <summary>
/// Запустить polling для приема обновлений от Telegram.
/// </summary>
public override async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
{
_client = new TelegramBotClient(_token);
@@ -81,7 +87,7 @@ public sealed class TelegramAdapter : MessengerAdapterBase
errorHandler: async (_, ex, ct2) =>
{
_logger.Log(LogLevel.Warn, $"{AdapterType} ({AdapterId}) error.", ex);
_logger.Log(LogLevel.Warn, $"{Type} ({Id}) error.", ex);
await Task.CompletedTask;
},
@@ -92,7 +98,7 @@ public sealed class TelegramAdapter : MessengerAdapterBase
var me = await _client.GetMe();
DisplayName = $"Telegram: @{me.Username}";
_logger.Log(LogLevel.Info, $"{AdapterType} ({AdapterId}) started: {DisplayName}");
_logger.Log(LogLevel.Info, $"{Type} ({Id}) started: {DisplayName}");
return;
}
@@ -101,17 +107,17 @@ public sealed class TelegramAdapter : MessengerAdapterBase
/// Универсальный внутренний метод отправки — определяет, нужно ли отправлять текст или файл по параметрам.
/// Возвращает id сообщения (или null).
/// </summary>
public override async Task<string?> SendAsync(SendRequest req, CancellationToken ct)
public async Task<string?> SendAsync(SendRequest req, CancellationToken ct)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
// Определите параметры адаптера (TelegramOptions) из папки или используйте параметры адаптера по умолчанию.
TelegramOptions telegramOptions = _options;
if (req.AdapterOptions is AdapterOptionsBag bag && bag.TryGet(AdapterType, out TelegramOptions? opt) && opt is not null)
if (req.AdapterOptions is AdapterOptionsBag bag && bag.TryGet(Type, out TelegramOptions? opt) && opt is not null)
{
telegramOptions = opt;
}
@@ -150,11 +156,11 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default)
public Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return Task.CompletedTask;
}
@@ -162,11 +168,11 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<bool> DeleteMultipleAsync(string chatId, IEnumerable<string> messageIds, CancellationToken ct = default)
public async Task<bool> DeleteMultipleAsync(string chatId, IEnumerable<string> messageIds, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return false;
}
@@ -187,12 +193,12 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<string?> EditTextAsync(string chatId, string messageId, string text,
public async Task<string?> EditTextAsync(string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
@@ -216,12 +222,12 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<string?> EditButtonsAsync(string chatId, string messageId,
public async Task<string?> EditButtonsAsync(string chatId, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
@@ -244,12 +250,12 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<bool> PinMessageAsync(string chatId, string messageId, bool disableNotification = false,
public async Task<bool> PinMessageAsync(string chatId, string messageId, bool disableNotification = false,
CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return false;
}
@@ -271,11 +277,11 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default)
public async Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return false;
}
@@ -296,18 +302,18 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<MessageInfo?> GetMessageInfoAsync(string chatId, string messageId, CancellationToken ct = default)
public async Task<MessageInfo?> GetMessageInfoAsync(string chatId, string messageId, CancellationToken ct = default)
{
throw new NotImplementedException();
}
/// <inheritdoc/>
public override async Task<string?> ForwardMessageAsync(string fromChatId, string messageId, string toChatId,
public async Task<string?> ForwardMessageAsync(string fromChatId, string messageId, string toChatId,
bool disableNotification = false, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
@@ -331,13 +337,13 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc/>
public override async Task<string?> CopyMessageAsync(string fromChatId, string messageId, string toChatId,
public async Task<string?> CopyMessageAsync(string fromChatId, string messageId, string toChatId,
string? caption = null, MessageFormat? captionFormat = null,
bool disableNotification = false, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
@@ -427,6 +433,12 @@ public sealed class TelegramAdapter : MessengerAdapterBase
bool disableNotification, string? caption, MessageFormat? captionFormat, int? replyToMessageId,
bool protectContent, CancellationToken ct)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
var inputFile = await CreateInputFileAsync(file, ct);
var parseMode = GetParseMode(captionFormat);
@@ -482,6 +494,12 @@ public sealed class TelegramAdapter : MessengerAdapterBase
ReplyMarkup? markup, bool disableNotification, int? replyToMessageId,
bool disableWebPagePreview, bool protectContent, CancellationToken ct)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
var format = req.TextFormat ?? MessageFormat.Plain;
var parseMode = GetParseMode(format);
@@ -533,8 +551,8 @@ public sealed class TelegramAdapter : MessengerAdapterBase
}
/// <inheritdoc />
public override IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
/// <inheritdoc />
public override Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
}