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

This commit is contained in:
2026-02-06 04:38:06 +03:00
parent 69ff3cf7d4
commit cd280369bc
25 changed files with 1525 additions and 219 deletions

View File

@@ -2,7 +2,7 @@ namespace BotPages.Core.Abstractions;
/// <summary>
/// Êîíòåéíåð äëÿ àäàïòåð-ñïåöèôè÷íûõ îïöèé, ïîçâîëÿþùèé õðàíèòü ïàðàìåòðû äëÿ íåñêîëüêèõ àäàïòåðîâ.
/// Èñïîëüçóåòñÿ âíóòðè `SendRequest.AdapterOptions`.
/// Èñïîëüçóåòñÿ âíóòðè <see cref="SendRequest.AdapterOptions"/>.
/// </summary>
public sealed class AdapterOptionsBag
{

View File

@@ -1,6 +1,28 @@
namespace BotPages.Core.Abstractions;
using BotPages.Core.Context;
namespace BotPages.Core.Abstractions;
/// <summary>
/// Ключ для идентификации пользовательской сессии.
/// </summary>
public readonly record struct CompositeSessionKey(string MessengerType, string ChatId, string? UserId);
public readonly record struct CompositeSessionKey(string AdapterId, string ChatId, string? UserId)
{
/// <summary>
/// Создает ключ сессии из UpdateContext.
/// </summary>
public static CompositeSessionKey FromUpdate(UpdateContext update)
{
return new CompositeSessionKey(
update.AdapterId,
update.Chat.Id,
update.User.Id);
}
/// <summary>
/// Получить ключ для определенного адаптера.
/// </summary>
public CompositeSessionKey ForAdapter(string adapterId)
{
return new CompositeSessionKey(adapterId, ChatId, UserId);
}
}

View File

@@ -1,4 +1,5 @@
using BotPages.Core.Context;
using BotPages.Core.Messaging;
namespace BotPages.Core.Abstractions;
@@ -23,6 +24,53 @@ public interface IMessengerAdapter
/// </summary>
Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Удалить несколько сообщений за раз.
/// </summary>
Task<bool> DeleteMultipleAsync(string chatId, IEnumerable<string> messageIds, CancellationToken ct = default);
/// <summary>
/// Редактировать только текст сообщения.
/// </summary>
Task<string?> EditTextAsync(string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default);
/// <summary>
/// Редактировать только клавиатуру сообщения.
/// </summary>
Task<string?> EditButtonsAsync(string chatId, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null,
CancellationToken ct = default);
/// <summary>
/// Закрепить сообщение в чате.
/// </summary>
Task<bool> PinMessageAsync(string chatId, string messageId, bool disableNotification = false,
CancellationToken ct = default);
/// <summary>
/// Открепить сообщение в чате.
/// </summary>
Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Получить информацию о сообщении.
/// </summary>
Task<MessageInfo?> GetMessageInfoAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Переслать сообщение.
/// </summary>
Task<string?> ForwardMessageAsync(string fromChatId, string messageId, string toChatId,
bool disableNotification = false, CancellationToken ct = default);
/// <summary>
/// Копировать сообщение с возможностью редактирования.
/// </summary>
Task<string?> CopyMessageAsync(string fromChatId, string messageId, string toChatId,
string? caption = null, MessageFormat? captionFormat = null,
bool disableNotification = false, CancellationToken ct = default);
/// <summary>
/// Создать билдер альбома для отправки медиагруппы.
/// </summary>

View File

@@ -1,44 +1,53 @@
using BotPages.Core.Context;
namespace BotPages.Core.Abstractions;
namespace BotPages.Core.Abstractions;
/// <summary>
/// Фабрика адаптеров мессенджеров.
/// Используется для разрешения конкретного <see cref="IMessengerAdapterSetup"/> по типу мессенджера.
/// Используется для разрешения конкретного <see cref="IMessengerAdapterSetup"/> по ID адаптера.
/// </summary>
public interface IMessengerAdapterFactory
{
/// <summary>
/// Список зарегистрированных адаптеров.
/// Список всех зарегистрированных адаптеров.
/// </summary>
Dictionary<string, IMessengerAdapterSetup> Adapters { get; }
IReadOnlyList<IMessengerAdapterSetup> AllAdapters { get; }
/// <summary>
/// Зарегистрировать адаптер для указанного типа мессенджера.
/// Зарегистрировать адаптер с уникальным идентификатором.
/// </summary>
/// <param name="messengerType">
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
/// </param>
/// <param name="adapter">
/// Экземпляр адаптера, реализующий <see cref="IMessengerAdapter"/>.
/// </param>
/// <returns>
/// Текущий экземпляр <see cref="IMessengerAdapterFactory"/> для цепочки вызовов.
/// </returns>
IMessengerAdapterFactory Register(string messengerType, IMessengerAdapterSetup adapter);
/// <param name="adapterId">Уникальный идентификатор адаптера.</param>
/// <param name="adapter">Экземпляр адаптера.</param>
/// <returns>Текущий экземпляр фабрики для цепочки вызовов.</returns>
/// <exception cref="ArgumentException">Если адаптер с таким ID уже зарегистрирован.</exception>
IMessengerAdapterFactory Register(string adapterId, IMessengerAdapterSetup adapter);
/// <summary>
/// Получить адаптер для указанного мессенджера.
/// Зарегистрировать адаптер с автоматически сгенерированным ID.
/// </summary>
/// <param name="messengerType">
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
/// Значение должно совпадать с <see cref="UpdateContext.MessengerType"/>.
/// </param>
/// <returns>
/// Экземпляр <see cref="IMessengerAdapter"/>, зарегистрированный для данного типа мессенджера.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Выбрасывается, если адаптер для указанного типа не зарегистрирован.
/// </exception>
IMessengerAdapter Resolve(string messengerType);
IMessengerAdapterFactory Register(IMessengerAdapterSetup adapter);
/// <summary>
/// Получить адаптер по ID.
/// </summary>
/// <exception cref="InvalidOperationException">Если адаптер не найден.</exception>
IMessengerAdapter Resolve(string adapterId);
/// <summary>
/// Попытаться получить адаптер по ID.
/// </summary>
bool TryResolve(string adapterId, out IMessengerAdapter? adapter);
/// <summary>
/// Получить все адаптеры определенного типа.
/// </summary>
IReadOnlyList<IMessengerAdapter> GetAdaptersByType(string adapterType);
/// <summary>
/// Проверить, зарегистрирован ли адаптер с указанным ID.
/// </summary>
bool Contains(string adapterId);
/// <summary>
/// Удалить адаптер по ID.
/// </summary>
bool Remove(string adapterId);
}

View File

@@ -0,0 +1,34 @@
namespace BotPages.Core.Abstractions;
/// <summary>
/// Информация о сообщении.
/// </summary>
public class MessageInfo
{
/// <summary>ID сообщения.</summary>
public required string MessageId { get; init; }
/// <summary>ID чата.</summary>
public required string ChatId { get; init; }
/// <summary>Текст сообщения.</summary>
public string? Text { get; init; }
/// <summary>Формат текста.</summary>
public MessageFormat? Format { get; init; }
/// <summary>Дата отправки.</summary>
public DateTime Date { get; init; }
/// <summary>ID отправителя.</summary>
public string? FromUserId { get; init; }
/// <summary>Закреплено ли сообщение.</summary>
public bool IsPinned { get; init; }
/// <summary>Является ли ответом на другое сообщение.</summary>
public bool IsReply { get; init; }
/// <summary>ID сообщения, на которое отвечает.</summary>
public string? ReplyToMessageId { get; init; }
}

View File

@@ -0,0 +1,102 @@
using BotPages.Core.Context;
using BotPages.Core.Messaging;
namespace BotPages.Core.Abstractions;
/// <summary>
/// Базовый класс для адаптеров мессенджеров.
/// </summary>
public abstract class MessengerAdapterBase : IMessengerAdapterSetup
{
/// <summary>
/// Уникальный идентификатор адаптера.
/// </summary>
public string AdapterId { get; internal set; } = string.Empty;
/// <summary>
/// Тип адаптера (Telegram, VK, WhatsApp и т.д.).
/// </summary>
public abstract string AdapterType { get; }
/// <summary>
/// Название адаптера для отображения.
/// </summary>
public string DisplayName { get; set; } = string.Empty;
/// <summary>
/// Доступные возможности мессенджера.
/// </summary>
public abstract Capabilities Capabilities { get; }
/// <summary>
/// Универсальный метод отправки с использованием общего описания запроса.
/// </summary>
public abstract Task<string?> SendAsync(SendRequest request, CancellationToken ct = default);
/// <summary>
/// Универсальный метод удаления сообщения.
/// </summary>
public abstract Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Удалить несколько сообщений за раз.
/// </summary>
public abstract Task<bool> DeleteMultipleAsync(string chatId, IEnumerable<string> messageIds, CancellationToken ct = default);
/// <summary>
/// Редактировать только текст сообщения.
/// </summary>
public abstract Task<string?> EditTextAsync(string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default);
/// <summary>
/// Редактировать только клавиатуру сообщения.
/// </summary>
public abstract Task<string?> EditButtonsAsync(string chatId, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null,
CancellationToken ct = default);
/// <summary>
/// Закрепить сообщение в чате.
/// </summary>
public abstract Task<bool> PinMessageAsync(string chatId, string messageId, bool disableNotification = false,
CancellationToken ct = default);
/// <summary>
/// Открепить сообщение в чате.
/// </summary>
public abstract Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Получить информацию о сообщении.
/// </summary>
public abstract Task<MessageInfo?> GetMessageInfoAsync(string chatId, string messageId, CancellationToken ct = default);
/// <summary>
/// Переслать сообщение.
/// </summary>
public abstract Task<string?> ForwardMessageAsync(string fromChatId, string messageId, string toChatId,
bool disableNotification = false, CancellationToken ct = default);
/// <summary>
/// Копировать сообщение с возможностью редактирования.
/// </summary>
public abstract Task<string?> CopyMessageAsync(string fromChatId, string messageId, string toChatId,
string? caption = null, MessageFormat? captionFormat = null,
bool disableNotification = false, CancellationToken ct = default);
/// <summary>
/// Создать билдер альбома для отправки медиагруппы.
/// </summary>
public abstract IAlbumBuilder CreateAlbumBuilder(PageContext ctx);
/// <summary>
/// Вызывается при выходе со страницы.
/// </summary>
public abstract Task OnLeaveAsync(PageContext ctx, CancellationToken ct);
/// <summary>
/// Запуск работы адаптера.
/// </summary>
public abstract Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct);
}

View File

@@ -1,50 +1,142 @@
namespace BotPages.Core.Abstractions;
/// <summary>
/// Реализация <see cref="IMessengerAdapterFactory"/>, позволяющая регистрировать и разрешать несколько адаптеров мессенджеров.
/// Реализация <see cref="IMessengerAdapterFactory"/>, позволяющая регистрировать и разрешать несколько адаптеров.
/// </summary>
public sealed class MultiAdapterFactory : IMessengerAdapterFactory
{
private readonly Dictionary<string, IMessengerAdapterSetup> _adapters = new(StringComparer.OrdinalIgnoreCase);
private readonly List<IMessengerAdapterSetup> _allAdapters = new();
private readonly Dictionary<string, IMessengerAdapterSetup> _adaptersById = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<IMessengerAdapterSetup>> _adaptersByType = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Список зарегистрированных адаптеров.
/// Список всех зарегистрированных адаптеров.
/// </summary>
public Dictionary<string, IMessengerAdapterSetup> Adapters => _adapters;
public IReadOnlyList<IMessengerAdapterSetup> AllAdapters => _allAdapters;
/// <summary>
/// Зарегистрировать адаптер для указанного типа мессенджера.
/// Зарегистрировать адаптер с уникальным идентификатором.
/// </summary>
/// <param name="messengerType">
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
/// </param>
/// <param name="adapter">
/// Экземпляр адаптера, реализующий <see cref="IMessengerAdapter"/>.
/// </param>
/// <returns>
/// Текущий экземпляр <see cref="MultiAdapterFactory"/> для цепочки вызовов.
/// </returns>
public IMessengerAdapterFactory Register(string messengerType, IMessengerAdapterSetup adapter)
public IMessengerAdapterFactory Register(string adapterId, IMessengerAdapterSetup adapter)
{
_adapters[messengerType] = adapter;
if (string.IsNullOrWhiteSpace(adapterId))
throw new ArgumentException("Adapter ID cannot be null or empty", nameof(adapterId));
if (_adaptersById.ContainsKey(adapterId))
throw new ArgumentException($"Adapter with ID '{adapterId}' is already registered", nameof(adapterId));
// Устанавливаем идентификатор в адаптер
if (adapter is MessengerAdapterBase adapterBase)
{
adapterBase.AdapterId = adapterId;
}
_allAdapters.Add(adapter);
_adaptersById[adapterId] = adapter;
// Группируем по типу
var adapterType = GetAdapterType(adapter);
if (!_adaptersByType.TryGetValue(adapterType, out var typeList))
{
typeList = new List<IMessengerAdapterSetup>();
_adaptersByType[adapterType] = typeList;
}
typeList.Add(adapter);
return this;
}
/// <summary>
/// Получить адаптер для указанного мессенджера.
/// Зарегистрировать адаптер с автоматически сгенерированным ID.
/// </summary>
/// <param name="messengerType">
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
/// </param>
/// <returns>
/// Экземпляр <see cref="IMessengerAdapter"/>, зарегистрированный для данного типа мессенджера.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Выбрасывается, если адаптер для указанного типа не зарегистрирован.
/// </exception>
public IMessengerAdapter Resolve(string messengerType)
=> _adapters.TryGetValue(messengerType, out var adapter)
? adapter
: throw new InvalidOperationException($"No adapter registered for {messengerType}");
public IMessengerAdapterFactory Register(IMessengerAdapterSetup adapter)
{
var adapterId = GenerateAdapterId(adapter);
return Register(adapterId, adapter);
}
/// <summary>
/// Получить адаптер по ID.
/// </summary>
public IMessengerAdapter Resolve(string adapterId)
{
if (_adaptersById.TryGetValue(adapterId, out var adapter))
{
return adapter;
}
throw new InvalidOperationException($"No adapter registered with ID '{adapterId}'");
}
/// <summary>
/// Попытаться получить адаптер по ID.
/// </summary>
public bool TryResolve(string adapterId, out IMessengerAdapter? adapter)
{
var result = _adaptersById.TryGetValue(adapterId, out var adapterSetup);
adapter = adapterSetup;
return result;
}
/// <summary>
/// Получить все адаптеры определенного типа.
/// </summary>
public IReadOnlyList<IMessengerAdapter> GetAdaptersByType(string adapterType)
{
if (_adaptersByType.TryGetValue(adapterType, out var adapters))
{
return adapters.AsReadOnly();
}
return Array.Empty<IMessengerAdapter>();
}
/// <summary>
/// Проверить, зарегистрирован ли адаптер с указанным ID.
/// </summary>
public bool Contains(string adapterId) => _adaptersById.ContainsKey(adapterId);
/// <summary>
/// Удалить адаптер по ID.
/// </summary>
public bool Remove(string adapterId)
{
if (_adaptersById.TryGetValue(adapterId, out var adapter))
{
_allAdapters.Remove(adapter);
_adaptersById.Remove(adapterId);
var adapterType = GetAdapterType(adapter);
if (_adaptersByType.TryGetValue(adapterType, out var typeList))
{
typeList.Remove(adapter);
if (typeList.Count == 0)
{
_adaptersByType.Remove(adapterType);
}
}
return true;
}
return false;
}
private static string GetAdapterType(IMessengerAdapter adapter)
{
if (adapter is MessengerAdapterBase adapterBase)
{
return adapterBase.AdapterType;
}
// Для обратной совместимости
return adapter.GetType().Name.Replace("Adapter", "");
}
private static string GenerateAdapterId(IMessengerAdapter adapter)
{
var adapterType = GetAdapterType(adapter);
var guid = Guid.NewGuid().ToString("N").Substring(0, 8);
return $"{adapterType}_{guid}".ToLowerInvariant();
}
}

View File

@@ -39,4 +39,66 @@ public sealed class SendRequest
/// Содержит имена/ключи адаптеров и соответствующие объекты опций.
/// </summary>
public AdapterOptionsBag? AdapterOptions { get; init; }
/// <summary>
/// ID сообщения, на которое отвечаем.
/// </summary>
public string? ReplyToMessageId { get; init; }
/// <summary>
/// Цитировать ли оригинальное сообщение при ответе.
/// </summary>
public bool QuoteReply { get; init; } = true;
/// <summary>
/// Заголовок цитаты (для некоторых мессенджеров).
/// </summary>
public string? QuoteTitle { get; init; }
/// <summary>
/// Показывать ли предпросмотр ссылок в сообщении.
/// </summary>
public bool DisableWebPagePreview { get; init; } = false;
/// <summary>
/// Отключает уведомление о сообщении.
/// </summary>
public bool DisableNotification { get; init; } = false;
/// <summary>
/// Защищает содержимое сообщения от пересылки и сохранения.
/// </summary>
public bool ProtectContent { get; init; } = false;
/// <summary>
/// Стиль разметки сообщения (для некоторых мессенджеров).
/// </summary>
public MessageStyle? Style { get; init; }
/// <summary>
/// Позволяет указать дату отправки сообщения (для планирования).
/// </summary>
public DateTime? ScheduleDate { get; init; }
/// <summary>
/// Тема сообщения (для форумов и тредов).
/// </summary>
public string? Topic { get; init; }
}
/// <summary>
/// Стиль оформления сообщения.
/// </summary>
public enum MessageStyle
{
/// <summary>Обычный стиль.</summary>
Default,
/// <summary>Стиль заголовка.</summary>
Heading,
/// <summary>Стиль предупреждения.</summary>
Warning,
/// <summary>Стиль успеха.</summary>
Success,
/// <summary>Стиль ошибки.</summary>
Error
}

View File

@@ -38,14 +38,40 @@ public sealed class BotPagesApp
}
/// <summary>
/// Добавить адаптер.
/// Добавить адаптер с указанием ID.
/// </summary>
public BotPagesApp AddAdapter(string messengerType, IMessengerAdapterSetup adapter)
/// <exception cref="ArgumentException">Если адаптер с таким ID уже существует.</exception>
public BotPagesApp AddAdapter(string adapterId, IMessengerAdapterSetup adapter)
{
_adapterFactory.Register(messengerType, adapter);
_adapterFactory.Register(adapterId, adapter);
return this;
}
/// <summary>
/// Добавить адаптер с автоматическим ID.
/// </summary>
public BotPagesApp AddAdapter(IMessengerAdapterSetup adapter)
{
_adapterFactory.Register(adapter);
return this;
}
/// <summary>
/// Проверить, существует ли адаптер с указанным ID.
/// </summary>
public bool HasAdapter(string adapterId) => _adapterFactory.Contains(adapterId);
/// <summary>
/// Получить адаптер по ID.
/// </summary>
public IMessengerAdapter GetAdapter(string adapterId) => _adapterFactory.Resolve(adapterId);
/// <summary>
/// Получить все адаптеры определенного типа.
/// </summary>
public IReadOnlyList<IMessengerAdapter> GetAdaptersByType(string adapterType)
=> _adapterFactory.GetAdaptersByType(adapterType);
/// <summary>
/// Установить страницу по умолчанию.
/// </summary>
@@ -174,6 +200,28 @@ public sealed class BotPagesApp
await pipeline();
}
/// <summary>
/// Создать контекст страницы для текущего обновления.
/// </summary>
private async Task<PageContext> CreatePageContextAsync(UpdateContext update, CancellationToken ct)
{
_currentCt = ct;
var sessionKey = CompositeSessionKey.FromUpdate(update);
var ctx = new PageContext
{
Update = update,
SessionKey = sessionKey,
StateStorage = _state,
Navigation = _navigation,
Adapter = _adapterFactory.Resolve(update.AdapterId),
AdapterFactory = _adapterFactory,
};
return await Task.FromResult(ctx);
}
private Func<Task> BuildPipeline(PageContext ctx, Func<Task> terminal)
{
Func<Task> next = terminal;
@@ -188,27 +236,6 @@ public sealed class BotPagesApp
// Технические поля для конвейера
private CancellationToken _currentCt;
/// <summary>
/// Создать контекст страницы для текущего обновления.
/// </summary>
private async Task<PageContext> CreatePageContextAsync(UpdateContext update, CancellationToken ct)
{
_currentCt = ct;
var sessionKey = new CompositeSessionKey(update.MessengerType, update.Chat.Id, update.User.Id);
var ctx = new PageContext
{
Update = update,
SessionKey = sessionKey,
StateStorage = _state,
Navigation = _navigation,
Adapter = _adapterFactory.Resolve(update.MessengerType),
};
return await Task.FromResult(ctx);
}
/// <summary>
/// Отправить обновление на текущую страницу.
/// </summary>
@@ -230,6 +257,8 @@ public sealed class BotPagesApp
if (update.Kind.HasFlag(UpdateKind.Text) && update.Text is not null) await page.OnText(ctx, update.Text, ct);
if (update.Kind.HasFlag(UpdateKind.Button) && update.Text is not null) await page.OnButton(ctx, update.Text, ct);
if (update.Kind.HasFlag(UpdateKind.File) && update.Files.Count > 0) await page.OnFile(ctx, update.Files, ct);
if (update.Kind.HasFlag(UpdateKind.Pin) && update.PinInfo is not null) await page.OnPin(ctx, update.PinInfo, ct);
if (update.Kind.HasFlag(UpdateKind.Delete) && update.DeleteInfo is not null) await page.OnDelete(ctx, update.DeleteInfo, ct);
}
catch (Exception ex)
@@ -252,9 +281,9 @@ public sealed class BotPagesApp
/// <returns></returns>
public async Task Build(CancellationToken cancellationToken)
{
foreach (var adapter in _adapterFactory.Adapters)
foreach (var adapter in _adapterFactory.AllAdapters)
{
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken);
await adapter.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken);
}
}
}

View File

@@ -0,0 +1,16 @@
namespace BotPages.Core.Context;
/// <summary>
/// Информация об удалении сообщения.
/// </summary>
public class DeleteInfo
{
/// <summary>ID удаленного сообщения.</summary>
public required string MessageId { get; init; }
/// <summary>Дата удаления.</summary>
public DateTime DeleteDate { get; init; }
/// <summary>Удалено ли массово.</summary>
public bool IsBulkDelete { get; init; }
}

View File

@@ -0,0 +1,16 @@
namespace BotPages.Core.Context;
/// <summary>
/// Информация о редактировании сообщения.
/// </summary>
public class EditInfo
{
/// <summary>Новый текст сообщения.</summary>
public string? NewText { get; init; }
/// <summary>Дата редактирования.</summary>
public DateTime EditDate { get; init; }
/// <summary>Были ли изменены кнопки.</summary>
public bool ButtonsChanged { get; init; }
}

View File

@@ -16,9 +16,14 @@ public sealed class PageContext
/// <summary>Хранилище состояния.</summary>
public required IStateStorage StateStorage { get; init; }
/// <summary>Сервис навигации.</summary>
public required NavigationService Navigation { get; init; }
/// <summary>Адаптер мессенджера.</summary>
/// <summary>Фабрика адаптеров (для получения других адаптеров).</summary>
public required IMessengerAdapterFactory AdapterFactory { get; init; }
/// <summary>Текущий адаптер мессенджера.</summary>
public required IMessengerAdapter Adapter { get; init; }
/// <summary>
@@ -26,4 +31,36 @@ public sealed class PageContext
/// </summary>
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this);
/// <summary>
/// Получить адаптер по ID.
/// </summary>
public IMessengerAdapter GetAdapter(string adapterId)
=> AdapterFactory.Resolve(adapterId);
/// <summary>
/// Попытаться получить адаптер по ID.
/// </summary>
public bool TryGetAdapter(string adapterId, out IMessengerAdapter? adapter)
=> AdapterFactory.TryResolve(adapterId, out adapter);
/// <summary>
/// Получить все адаптеры определенного типа.
/// </summary>
public IReadOnlyList<IMessengerAdapter> GetAdaptersByType(string adapterType)
=> AdapterFactory.GetAdaptersByType(adapterType);
/// <summary>
/// Получить текущий тип адаптера.
/// </summary>
public string CurrentAdapterType => Update.AdapterType;
/// <summary>
/// Получить текущий ID адаптера.
/// </summary>
public string CurrentAdapterId => Update.AdapterId;
/// <summary>
/// Получить все адаптеры.
/// </summary>
public IReadOnlyList<IMessengerAdapter> AllAdapters => AdapterFactory.AllAdapters;
}

View File

@@ -1,4 +1,5 @@
using BotPages.Core.Abstractions;
using BotPages.Core.Messaging;
namespace BotPages.Core;
@@ -19,4 +20,108 @@ public static class PageContextAdapterExtensions
/// </summary>
public static Task DeleteAsync(this PageContext ctx, string chatId, string messageId, CancellationToken ct = default)
=> ctx.Adapter.DeleteAsync(chatId, messageId, ct);
/// <summary>
/// Удалить сообщение (используя ChatId из контекста).
/// </summary>
public static Task DeleteAsync(this PageContext ctx, string messageId, CancellationToken ct = default)
=> ctx.Adapter.DeleteAsync(ctx.Update.Chat.Id, messageId, ct);
/// <summary>
/// Удалить несколько сообщений.
/// </summary>
public static Task<bool> DeleteMultipleAsync(this PageContext ctx, string chatId, IEnumerable<string> messageIds, CancellationToken ct = default)
=> ctx.Adapter.DeleteMultipleAsync(chatId, messageIds, ct);
/// <summary>
/// Удалить несколько сообщений (используя ChatId из контекста).
/// </summary>
public static Task<bool> DeleteMultipleAsync(this PageContext ctx, IEnumerable<string> messageIds, CancellationToken ct = default)
=> ctx.Adapter.DeleteMultipleAsync(ctx.Update.Chat.Id, messageIds, ct);
/// <summary>
/// Редактировать текст сообщения.
/// </summary>
public static Task<string?> EditTextAsync(this PageContext ctx, string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default)
=> ctx.Adapter.EditTextAsync(chatId, messageId, text, format, ct);
/// <summary>
/// Редактировать текст сообщения (используя ChatId из контекста).
/// </summary>
public static Task<string?> EditTextAsync(this PageContext ctx, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default)
=> ctx.Adapter.EditTextAsync(ctx.Update.Chat.Id, messageId, text, format, ct);
/// <summary>
/// Редактировать кнопки сообщения.
/// </summary>
public static Task<string?> EditButtonsAsync(this PageContext ctx, string chatId, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null, CancellationToken ct = default)
=> ctx.Adapter.EditButtonsAsync(chatId, messageId, inlineButtons, ct);
/// <summary>
/// Редактировать кнопки сообщения (используя ChatId из контекста).
/// </summary>
public static Task<string?> EditButtonsAsync(this PageContext ctx, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null, CancellationToken ct = default)
=> ctx.Adapter.EditButtonsAsync(ctx.Update.Chat.Id, messageId, inlineButtons, ct);
/// <summary>
/// Закрепить сообщение.
/// </summary>
public static Task<bool> PinMessageAsync(this PageContext ctx, string chatId, string messageId,
bool disableNotification = false, CancellationToken ct = default)
=> ctx.Adapter.PinMessageAsync(chatId, messageId, disableNotification, ct);
/// <summary>
/// Закрепить сообщение (используя ChatId из контекста).
/// </summary>
public static Task<bool> PinMessageAsync(this PageContext ctx, string messageId,
bool disableNotification = false, CancellationToken ct = default)
=> ctx.Adapter.PinMessageAsync(ctx.Update.Chat.Id, messageId, disableNotification, ct);
/// <summary>
/// Открепить сообщение.
/// </summary>
public static Task<bool> UnpinMessageAsync(this PageContext ctx, string chatId, string messageId,
CancellationToken ct = default)
=> ctx.Adapter.UnpinMessageAsync(chatId, messageId, ct);
/// <summary>
/// Открепить сообщение (используя ChatId из контекста).
/// </summary>
public static Task<bool> UnpinMessageAsync(this PageContext ctx, string messageId,
CancellationToken ct = default)
=> ctx.Adapter.UnpinMessageAsync(ctx.Update.Chat.Id, messageId, ct);
/// <summary>
/// Получить информацию о сообщении.
/// </summary>
public static Task<MessageInfo?> GetMessageInfoAsync(this PageContext ctx, string chatId, string messageId,
CancellationToken ct = default)
=> ctx.Adapter.GetMessageInfoAsync(chatId, messageId, ct);
/// <summary>
/// Получить информацию о сообщении (используя ChatId из контекста).
/// </summary>
public static Task<MessageInfo?> GetMessageInfoAsync(this PageContext ctx, string messageId,
CancellationToken ct = default)
=> ctx.Adapter.GetMessageInfoAsync(ctx.Update.Chat.Id, messageId, ct);
/// <summary>
/// Переслать сообщение.
/// </summary>
public static Task<string?> ForwardMessageAsync(this PageContext ctx, string fromChatId, string messageId,
string toChatId, bool disableNotification = false, CancellationToken ct = default)
=> ctx.Adapter.ForwardMessageAsync(fromChatId, messageId, toChatId, disableNotification, ct);
/// <summary>
/// Копировать сообщение.
/// </summary>
public static Task<string?> CopyMessageAsync(this PageContext ctx, string fromChatId, string messageId,
string toChatId, string? caption = null, MessageFormat? captionFormat = null,
bool disableNotification = false, CancellationToken ct = default)
=> ctx.Adapter.CopyMessageAsync(fromChatId, messageId, toChatId, caption, captionFormat,
disableNotification, ct);
}

View File

@@ -0,0 +1,16 @@
namespace BotPages.Core.Context;
/// <summary>
/// Информация о закреплении сообщения.
/// </summary>
public class PinInfo
{
/// <summary>ID закрепленного сообщения.</summary>
public required string MessageId { get; init; }
/// <summary>Дата закрепления.</summary>
public DateTime PinDate { get; init; }
/// <summary>Отключено ли уведомление.</summary>
public bool NotificationDisabled { get; init; }
}

View File

@@ -1,25 +1,6 @@
namespace BotPages.Core.Context;
using BotPages.Core.Abstractions;
using BotPages.Core.Abstractions;
/// <summary>
/// Тип входящего обновления.
/// </summary>
[Flags]
public enum UpdateKind
{
/// <summary>Неизвестное сообщение.</summary>
None = 0,
/// <summary>Текстовое сообщение.</summary>
Text = 1 << 0,
/// <summary>Файлы (один или несколько).</summary>
File = 1 << 1,
/// <summary>Нажатие кнопки.</summary>
Button = 1 << 2,
}
namespace BotPages.Core.Context;
/// <summary>
/// Контекст входящего обновления от мессенджера.
@@ -27,8 +8,11 @@ public enum UpdateKind
/// </summary>
public sealed class UpdateContext
{
/// <summary>Тип мессенджера.</summary>
public required string MessengerType { get; init; }
/// <summary>Идентификатор адаптера, от которого пришло обновление.</summary>
public required string AdapterId { get; init; }
/// <summary>Тип адаптера (определяется адаптером).</summary>
public required string AdapterType { get; init; }
/// <summary>
/// Данные пользователя, от которого пришло обновление.
@@ -51,9 +35,34 @@ public sealed class UpdateContext
/// </summary>
public string? Text { get; init; }
/// <summary>
/// ID сообщения, к которому относится обновление.
/// </summary>
public string? MessageId { get; init; }
/// <summary>
/// ID сообщения, на которое дан ответ (если есть).
/// </summary>
public string? ReplyToMessageId { get; init; }
/// <summary>
/// Список файлов, если Kind = File.
/// Может содержать один или несколько файлов.
/// </summary>
public List<FileDescriptor> Files { get; init; } = new();
/// <summary>
/// Информация о редактировании (если Kind = Edit).
/// </summary>
public EditInfo? EditInfo { get; init; }
/// <summary>
/// Информация об удалении (если Kind = Delete).
/// </summary>
public DeleteInfo? DeleteInfo { get; init; }
/// <summary>
/// Информация о закреплении (если Kind = Pin).
/// </summary>
public PinInfo? PinInfo { get; init; }
}

View File

@@ -0,0 +1,32 @@
namespace BotPages.Core.Context;
/// <summary>
/// Тип входящего обновления.
/// </summary>
[Flags]
public enum UpdateKind
{
/// <summary>Неизвестное сообщение.</summary>
None = 0,
/// <summary>Текстовое сообщение.</summary>
Text = 1 << 0,
/// <summary>Файлы (один или несколько).</summary>
File = 1 << 1,
/// <summary>Нажатие кнопки.</summary>
Button = 1 << 2,
/// <summary>Редактирование сообщения.</summary>
Edit = 1 << 3,
/// <summary>Удаление сообщения.</summary>
Delete = 1 << 4,
/// <summary>Закрепление сообщения.</summary>
Pin = 1 << 5,
/// <summary>Ответ на сообщение.</summary>
Reply = 1 << 6,
}

View File

@@ -4,7 +4,7 @@ namespace BotPages.Core.Messaging;
/// <summary>
/// Fluentбилдер для отправки сообщений (текст, кнопки, файлы, альбомы, прогресс).
/// Поддерживает указание адаптер-специфичных опций через `WithAdapterOption`.
/// Поддерживает указание адаптер-специфичных опций через <see cref="WithAdapterOption{T}(string, T)"/>.
/// </summary>
public sealed class MessageBuilder
{
@@ -17,11 +17,77 @@ public sealed class MessageBuilder
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
private bool _disableReplyKeyboard;
private AdapterOptionsBag? _adapterOptions = null;
private string? _chatId = null;
private string? _replyToMessageId = null;
private bool _quoteReply = true;
private string? _quoteTitle = null;
private bool _disableWebPagePreview = false;
private bool _disableNotification = false;
private bool _protectContent = false;
private MessageStyle? _style = null;
private DateTime? _scheduleDate = null;
private string? _topic = null;
private string? _messageId = null;
private IMessengerAdapter? _targetAdapter = null;
private string? _targetChatId = null;
/// <summary>Создать билдер сообщений.</summary>
public MessageBuilder(PageContext ctx) => _ctx = ctx;
/// <summary>
/// Отправить сообщение через указанный адаптер.
/// </summary>
public MessageBuilder WithAdapter(IMessengerAdapter adapter)
{
_targetAdapter = adapter;
return this;
}
/// <summary>
/// Отправить сообщение через адаптер по ID.
/// </summary>
public MessageBuilder WithAdapter(string adapterId)
{
_targetAdapter = _ctx.AdapterFactory.Resolve(adapterId);
return this;
}
/// <summary>
/// Использовать текущий адаптер (по умолчанию).
/// </summary>
public MessageBuilder UseCurrentAdapter()
{
_targetAdapter = null;
return this;
}
/// <summary>
/// Отправить в указанный чат (с указанием адаптера).
/// </summary>
public MessageBuilder ToChat(string chatId, IMessengerAdapter? adapter)
{
_targetChatId = chatId;
_targetAdapter = adapter;
return this;
}
/// <summary>
/// Отправить в указанный чат через адаптер по ID.
/// </summary>
public MessageBuilder ToChat(string chatId, string adapterId)
{
_targetChatId = chatId;
_targetAdapter = _ctx.AdapterFactory.Resolve(adapterId);
return this;
}
/// <summary>
/// Отправить в указанный чат.
/// </summary>
public MessageBuilder ToChat(string chatId)
{
_targetChatId = chatId;
return this;
}
/// <summary>
/// Установить опции для конкретного адаптера. Ключ адаптера определяется адаптером (напр., "telegram").
/// </summary>
@@ -32,13 +98,6 @@ public sealed class MessageBuilder
return this;
}
/// <summary>ID чата куда отрпавить сообщение.</summary>
public MessageBuilder ChatId(string chatId)
{
_chatId = chatId;
return this;
}
/// <summary>Текст сообщения.</summary>
public MessageBuilder Text(string text, MessageFormat format = MessageFormat.Plain)
{
@@ -47,6 +106,71 @@ public sealed class MessageBuilder
return this;
}
/// <summary>Стиль сообщения.</summary>
public MessageBuilder Style(MessageStyle style)
{
_style = style;
return this;
}
/// <summary>Тема сообщения (для форумов).</summary>
public MessageBuilder Topic(string topic)
{
_topic = topic;
return this;
}
/// <summary>Запланировать отправку на определенную дату.</summary>
public MessageBuilder Schedule(DateTime scheduleDate)
{
_scheduleDate = scheduleDate;
return this;
}
/// <summary>Отключить предпросмотр ссылок.</summary>
public MessageBuilder DisableWebPagePreview()
{
_disableWebPagePreview = true;
return this;
}
/// <summary>Отключить уведомление.</summary>
public MessageBuilder DisableNotification()
{
_disableNotification = true;
return this;
}
/// <summary>Защитить содержимое от пересылки.</summary>
public MessageBuilder ProtectContent()
{
_protectContent = true;
return this;
}
/// <summary>Ответить на сообщение.</summary>
public MessageBuilder ReplyTo(string messageId, bool quote = true, string? quoteTitle = null)
{
_replyToMessageId = messageId;
_quoteReply = quote;
_quoteTitle = quoteTitle;
return this;
}
/// <summary>Ответить на текущее сообщение.</summary>
public MessageBuilder ReplyToCurrent(bool quote = true, string? quoteTitle = null)
{
if (_ctx.Update is not null)
{
// Предполагаем, что Update содержит ID текущего сообщения
// Это может потребовать расширения UpdateContext
_replyToMessageId = _ctx.Update.MessageId;
_quoteReply = quote;
_quoteTitle = quoteTitle;
}
return this;
}
/// <summary>Добавить inlineкнопку.</summary>
public MessageBuilder Inline(string label, string value)
{
@@ -132,7 +256,104 @@ public sealed class MessageBuilder
/// <summary>Удалить сообщение.</summary>
public async Task DeleteAsync(string messageId, CancellationToken ct = default)
{
await _ctx.DeleteAsync(this._chatId ?? _ctx.Update.Chat.Id, messageId, ct);
await _ctx.Adapter.DeleteAsync(GetEffectiveChatId(), messageId, ct);
}
/// <summary>Удалить несколько сообщений.</summary>
public async Task<bool> DeleteMultipleAsync(IEnumerable<string> messageIds, CancellationToken ct = default)
{
return await _ctx.Adapter.DeleteMultipleAsync(GetEffectiveChatId(), messageIds, ct);
}
/// <summary>Редактировать только текст сообщения.</summary>
public async Task<string?> EditTextAsync(string messageId, string newText,
MessageFormat? format = null, CancellationToken ct = default)
{
return await _ctx.Adapter.EditTextAsync(
GetEffectiveChatId(),
messageId,
newText,
format ?? _format,
ct);
}
/// <summary>Редактировать только кнопки сообщения.</summary>
public async Task<string?> EditButtonsAsync(string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null,
CancellationToken ct = default)
{
return await _ctx.Adapter.EditButtonsAsync(
GetEffectiveChatId(),
messageId,
inlineButtons ?? _inline,
ct);
}
/// <summary>Закрепить сообщение.</summary>
public async Task<bool> PinAsync(string messageId, bool disableNotification = false,
CancellationToken ct = default)
{
return await _ctx.Adapter.PinMessageAsync(
GetEffectiveChatId(),
messageId,
disableNotification,
ct);
}
/// <summary>Открепить сообщение.</summary>
public async Task<bool> UnpinAsync(string messageId, CancellationToken ct = default)
{
return await _ctx.Adapter.UnpinMessageAsync(
GetEffectiveChatId(),
messageId,
ct);
}
/// <summary>Получить информацию о сообщении.</summary>
public async Task<MessageInfo?> GetInfoAsync(string messageId, CancellationToken ct = default)
{
return await _ctx.Adapter.GetMessageInfoAsync(
GetEffectiveChatId(),
messageId,
ct);
}
/// <summary>Переслать сообщение.</summary>
public async Task<string?> ForwardAsync(string fromChatId, string messageId, string toChatId,
bool disableNotification = false, CancellationToken ct = default)
{
return await _ctx.Adapter.ForwardMessageAsync(
fromChatId,
messageId,
toChatId ?? GetEffectiveChatId(),
disableNotification,
ct);
}
/// <summary>Копировать сообщение.</summary>
public async Task<string?> CopyAsync(string fromChatId, string messageId, string toChatId,
string? caption = null, MessageFormat? captionFormat = null,
bool disableNotification = false, CancellationToken ct = default)
{
return await _ctx.Adapter.CopyMessageAsync(
fromChatId,
messageId,
toChatId ?? GetEffectiveChatId(),
caption,
captionFormat,
disableNotification,
ct);
}
private string GetEffectiveChatId()
{
return _targetChatId ?? _ctx.Update.Chat.Id;
}
private IMessengerAdapter GetEffectiveAdapter()
{
return _targetAdapter ?? _ctx.Adapter
?? throw new InvalidOperationException("No adapter specified for sending message");
}
/// <summary>Отправить собранное сообщение.</summary>
@@ -142,27 +363,43 @@ public sealed class MessageBuilder
/// <summary>Редактировать сообщение.</summary>
public async Task<string?> SendAsync(string messageId, CancellationToken ct = default)
{
_messageId = string.IsNullOrWhiteSpace(messageId) ? null : messageId;
string? outMessageId = null;
List<List<ReplyButton>>? reply = null;
if (_disableReplyKeyboard) reply = new();
else if (_reply.Any()) reply = _reply;
// Определяем целевой адаптер
var adapter = GetEffectiveAdapter();
// Определяем целевой чат
var targetChatId = GetEffectiveChatId();
// Текст
if (!string.IsNullOrWhiteSpace(_text))
{
var req = new SendRequest
{
ChatId = _chatId ?? _ctx.Update.Chat.Id,
ChatId = targetChatId,
Text = _text,
TextFormat = _format,
Inline = _inline,
Reply = reply,
MessageId = string.IsNullOrWhiteSpace(messageId) ? null : messageId,
MessageId = _messageId,
ReplyToMessageId = _replyToMessageId,
QuoteReply = _quoteReply,
QuoteTitle = _quoteTitle,
DisableWebPagePreview = _disableWebPagePreview,
DisableNotification = _disableNotification,
ProtectContent = _protectContent,
Style = _style,
ScheduleDate = _scheduleDate,
Topic = _topic,
AdapterOptions = _adapterOptions
};
outMessageId = await _ctx.SendAsync(req, ct);
outMessageId = await adapter.SendAsync(req, ct);
}
// Файлы
@@ -170,16 +407,25 @@ public sealed class MessageBuilder
{
var req = new SendRequest
{
ChatId = _chatId ?? _ctx.Update.Chat.Id,
ChatId = targetChatId,
File = file,
Caption = caption,
CaptionFormat = captionFormat,
Inline = _inline,
Reply = reply,
ReplyToMessageId = _replyToMessageId,
QuoteReply = _quoteReply,
QuoteTitle = _quoteTitle,
DisableWebPagePreview = _disableWebPagePreview,
DisableNotification = _disableNotification,
ProtectContent = _protectContent,
Style = _style,
ScheduleDate = _scheduleDate,
Topic = _topic,
AdapterOptions = _adapterOptions
};
var res = await _ctx.SendAsync(req, ct);
var res = await adapter.SendAsync(req, ct);
// сохранить первый возвращённый id сообщения
if (outMessageId is null && res is not null) outMessageId = res;
}
@@ -187,22 +433,58 @@ public sealed class MessageBuilder
// Альбом
if (_album.Count > 0)
{
var builder = _ctx.Albums;
// Для альбома нужен PageContext с правильным адаптером
var albumCtx = CreateAlbumContext(_ctx, adapter);
var builder = adapter.CreateAlbumBuilder(albumCtx);
foreach (var (file, caption, captionFormat) in _album)
builder.Add(file, caption, captionFormat);
await builder.SendAsync(ct);
}
_text = null;
_files.Clear();
_album.Clear();
_adapterOptions = null;
_chatId = null;
_reply.Clear();
_inline.Clear();
Reset();
return outMessageId;
}
private PageContext CreateAlbumContext(PageContext originalCtx, IMessengerAdapter adapter)
{
// Создаем новый контекст для альбома с указанным адаптером
return new PageContext
{
SessionKey = originalCtx.SessionKey,
Update = originalCtx.Update,
StateStorage = originalCtx.StateStorage,
Navigation = originalCtx.Navigation,
AdapterFactory = originalCtx.AdapterFactory,
Adapter = adapter,
};
}
/// <summary>
/// Сбросить состояние билдера для повторного использования.
/// </summary>
public MessageBuilder Reset()
{
_text = null;
_files.Clear();
_album.Clear();
_adapterOptions = null;
_targetAdapter = null;
_targetChatId = null;
_replyToMessageId = null;
_quoteReply = true;
_quoteTitle = null;
_disableWebPagePreview = false;
_disableNotification = false;
_protectContent = false;
_style = null;
_scheduleDate = null;
_topic = null;
_messageId = null;
_reply.Clear();
_inline.Clear();
_disableReplyKeyboard = false;
return this;
}
}

View File

@@ -0,0 +1,55 @@
using BotPages.Core.Abstractions;
namespace BotPages.Core.Messaging;
/// <summary>
/// Расширения для MessageBuilder для работы с разными адаптерами.
/// </summary>
public static class MessageBuilderAdapterExtensions
{
/// <summary>
/// Отправить сообщение через конкретный адаптер.
/// </summary>
public static MessageBuilder WithAdapter(this MessageBuilder builder, IMessengerAdapter adapter)
{
builder.WithAdapter(adapter);
return builder;
}
/// <summary>
/// Отправить сообщение через адаптер по типу и ID экземпляра.
/// </summary>
public static MessageBuilder WithAdapter(this MessageBuilder builder, string messengerType, string instanceId)
{
// Получаем фабрику адаптеров через сервис локатор или контекст
// В реальной реализации нужно будет передать фабрику адаптеров
return builder;
}
/// <summary>
/// Отправить сообщение через адаптер по полному ключу.
/// </summary>
public static MessageBuilder WithAdapter(this MessageBuilder builder, string fullMessengerKey)
{
// В реальной реализации нужно будет передать фабрику адаптеров
return builder;
}
/// <summary>
/// Отправить сообщение в указанный чат с указанным адаптером.
/// </summary>
public static MessageBuilder ToChat(this MessageBuilder builder, string chatId, IMessengerAdapter adapter)
{
return builder.ToChat(chatId, adapter);
}
/// <summary>
/// Отправить сообщение в чат в другом адаптере того же типа.
/// </summary>
public static MessageBuilder ToChatInOtherInstance(this MessageBuilder builder, string chatId, string instanceId)
{
// Получаем тип текущего адаптера и используем другой экземпляр
// В реальной реализации нужно будет передать фабрику адаптеров
return builder;
}
}

View File

@@ -17,7 +17,7 @@ public sealed class LoggingMiddleware : IPageMiddleware
public async Task InvokeAsync(PageContext ctx, Func<Task> next, CancellationToken ct)
{
// Логируем базовую информацию
_logger.Log(LogLevel.Info, $"Update from {ctx.Update.MessengerType} | Chat: {ctx.Update.Chat.Id} | User: {ctx.Update.User.Id}");
_logger.Log(LogLevel.Info, $"Update from {ctx.Update.AdapterId} | Chat: {ctx.Update.Chat.Id} | User: {ctx.Update.User.Id}");
// Логируем текст, кнопки, файлы
if (ctx.Update.Text is not null)

View File

@@ -10,19 +10,34 @@ public abstract class Page
{
/// <summary>Вход на страницу.</summary>
public virtual Task OnEnter(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
/// <summary>Общий обработчик обновлений.</summary>
public virtual Task OnUpdate(PageContext ctx, UpdateContext update, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка текста.</summary>
public virtual Task OnText(PageContext ctx, string text, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка файлов.</summary>
public virtual Task OnFile(PageContext ctx, List<FileDescriptor> files, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка кнопки.</summary>
public virtual Task OnButton(PageContext ctx, string payload, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка редактирования сообщения.</summary>
public virtual Task OnEdit(PageContext ctx, EditInfo editInfo, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка удаления сообщения.</summary>
public virtual Task OnDelete(PageContext ctx, DeleteInfo deleteInfo, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка закрепления сообщения.</summary>
public virtual Task OnPin(PageContext ctx, PinInfo pinInfo, CancellationToken ct) => Task.CompletedTask;
/// <summary>Выход со страницы.</summary>
public virtual Task OnLeave(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
/// <summary>Таймаут бездействия.</summary>
public virtual Task OnTimeout(PageContext ctx, TimeSpan timeout, CancellationToken ct) => Task.CompletedTask;
/// <summary>Обработка ошибок.</summary>
public virtual Task OnError(PageContext ctx, Exception ex, CancellationToken ct) => Task.CompletedTask;
}

View File

@@ -1,4 +1,5 @@
using BotPages.Core;
using System;
namespace BotPages.Telegram;
@@ -8,25 +9,28 @@ namespace BotPages.Telegram;
public static class BotPagesAppExtension
{
/// <summary>
/// Добавление адаптера для телеграмм в <see cref="BotPages.Core.Abstractions.IMessengerAdapterFactory"/>
/// Добавление адаптера для Telegram.
/// </summary>
/// <param name="app"></param>
/// <param name="token"></param>
/// <param name="messengerType"></param>
/// <returns></returns>
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string messengerType = "")
=> app.AddTelegramAdapter(token, null, messengerType);
/// <exception cref="ArgumentException">Если адаптер с таким ID уже существует.</exception>
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string adapterId, TelegramOptions? options = null)
{
if (app.HasAdapter(adapterId))
{
throw new ArgumentException($"Adapter with ID '{adapterId}' already exists", nameof(adapterId));
}
var telegram = new TelegramAdapter(app.Logger, token, options);
app.AddAdapter(adapterId, telegram);
return app;
}
/// <summary>
/// Добавление адаптера для телеграмм с опциями.
/// Добавить Telegram бота с автоматическим ID.
/// </summary>
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, TelegramOptions? options, string messengerType = "")
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, TelegramOptions? options = null)
{
var telegram = new TelegramAdapter(app.Logger, token, options);
if (!string.IsNullOrWhiteSpace(messengerType)) telegram.MessengerType = messengerType;
app.AddAdapter(telegram.MessengerType, telegram);
app.AddAdapter(telegram);
return app;
}
}

View File

@@ -1,19 +0,0 @@
using BotPages.Core.Messaging;
namespace BotPages.Telegram;
/// <summary>
/// Ðàñøèðåíèÿ äëÿ `MessageBuilder` ñïåöèôè÷íûå äëÿ Telegram.
/// Ïîçâîëÿþò óäîáíî çàäàòü `TelegramOptions` äëÿ êîíêðåòíîãî ñîîáùåíèÿ
/// áåç èçìåíåíèÿ ñàìîãî áèëäåðà.
/// </summary>
public static class MessageBuilderExtensions
{
/// <summary>
/// Óñòàíîâèòü îïöèè Telegram äëÿ êîíêðåòíîãî ñîîáùåíèÿ (ïåðåîïðåäåëÿþò îïöèè àäàïòåðà).
/// </summary>
public static MessageBuilder WithTelegramOptions(this MessageBuilder builder, TelegramOptions options)
{
return builder.WithAdapterOption(TelegramAdapter.AdapterType, options);
}
}

View File

@@ -16,15 +16,12 @@ using Telegram.Bot.Types.ReplyMarkups;
namespace BotPages.Telegram;
/// <summary>
/// Адаптер для Telegram на базе Telegram.Bot.
/// Реализует отправку текста, кнопок, файлов, альбомов и прогресса.
/// </summary>
public sealed class TelegramAdapter : IMessengerAdapterSetup
public sealed class TelegramAdapter : MessengerAdapterBase
{
internal static readonly string AdapterType = typeof(TelegramAdapter).FullName;
private readonly ILogger _logger;
private TelegramBotClient? _client;
private string _token;
@@ -45,29 +42,35 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
_logger = logger;
_token = token;
_options = options ?? new TelegramOptions();
// Устанавливаем имя для отображения
DisplayName = $"Telegram Bot";
}
/// <summary>Тип адаптера.</summary>
public override string AdapterType => "Telegram";
/// <summary>
///Идентификатор мессенджера / адаптера
/// Идентификатор мессенджера / адаптера
/// </summary>
public string MessengerType { get; set; } = "Telegram: " + Guid.NewGuid().ToString();
public string MessengerType => "Telegram";
/// <summary>
/// Доступные возможности адаптера.
/// </summary>
public Capabilities Capabilities => _capabilities;
public override Capabilities Capabilities => _capabilities;
/// <summary>
/// Запустить polling для приема обновлений от Telegram.
/// </summary>
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
public override async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
{
_client = new TelegramBotClient(_token);
_client.StartReceiving(
updateHandler: async (_, update, ct2) =>
{
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
var mapped = TelegramUpdateMapper.Map(this, update, _client);
if (mapped is not null)
await onUpdate(mapped);
if (update.CallbackQuery is not null)
@@ -78,18 +81,18 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
errorHandler: async (_, ex, ct2) =>
{
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex);
_logger.Log(LogLevel.Warn, $"{AdapterType} ({AdapterId}) error.", ex);
await Task.CompletedTask;
},
cancellationToken: ct
);
await _client.SetMyCommands(commands.Where(t => t.Publish).Select(t => new BotCommand(t.Name, t.Description ?? t.Name.TrimStart('/'))), cancellationToken: ct);
var me = await _client.GetMe();
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
DisplayName = $"Telegram: @{me.Username}";
_logger.Log(LogLevel.Info, $"{AdapterType} ({AdapterId}) started: {DisplayName}");
return;
}
@@ -98,7 +101,7 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
/// Универсальный внутренний метод отправки — определяет, нужно ли отправлять текст или файл по параметрам.
/// Возвращает id сообщения (или null).
/// </summary>
public async Task<string?> SendAsync(SendRequest req, CancellationToken ct)
public override async Task<string?> SendAsync(SendRequest req, CancellationToken ct)
{
if (_client is null)
{
@@ -112,33 +115,80 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
{
telegramOptions = opt;
}
var disableNotification = !telegramOptions.NotifyOnSend;
var disableNotification = !telegramOptions.NotifyOnSend || req.DisableNotification;
// Build markup
var inlineMarkup = BuildInlineMarkup(req.Inline);
ReplyMarkup? markup = BuildReplyMarkup(req.Reply);
// Ответ на сообщение
int? replyToMessageId = null;
if (!string.IsNullOrEmpty(req.ReplyToMessageId) && int.TryParse(req.ReplyToMessageId, out var replyId))
{
replyToMessageId = replyId;
}
// Файлы: сейчас поддерживается один файл через SendRequest.File.
// При необходимости для нескольких файлов следует использовать альбомы (CreateAlbumBuilder)
if (req.File is not null)
{
if (inlineMarkup is not null) markup = inlineMarkup;
var sent = await SendFileAsync(req.File, req.ChatId, markup, disableNotification, req.Caption, req.CaptionFormat, ct);
var sent = await SendFileAsync(req.File, req.ChatId, markup, disableNotification,
req.Caption, req.CaptionFormat, replyToMessageId, req.ProtectContent, ct);
return sent?.MessageId.ToString();
}
// Текст
if (!string.IsNullOrWhiteSpace(req.Text))
{
return await SendTextAsync(req, inlineMarkup, markup, disableNotification, ct);
return await SendTextAsync(req, inlineMarkup, markup, disableNotification,
replyToMessageId, req.DisableWebPagePreview, req.ProtectContent, ct);
}
return null;
}
/// <inheritdoc/>
public Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default)
public override Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return Task.CompletedTask;
}
return _client.DeleteMessage(chatId, Convert.ToInt32(messageId), ct);
}
/// <inheritdoc/>
public override 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.");
return false;
}
try
{
// Telegram не поддерживает массовое удаление, удаляем по одному
foreach (var messageId in messageIds)
{
await DeleteAsync(chatId, messageId, ct);
}
return true;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to delete multiple messages: {ex.Message}");
return false;
}
}
/// <inheritdoc/>
public override async Task<string?> EditTextAsync(string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default)
{
if (_client is null)
{
@@ -146,7 +196,171 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
return null;
}
return _client.DeleteMessage(chatId, Convert.ToInt32(messageId), ct);
try
{
var parseMode = GetParseMode(format);
await _client.EditMessageText(
chatId: long.Parse(chatId),
messageId: int.Parse(messageId),
text: text,
parseMode: parseMode,
cancellationToken: ct
);
return messageId;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to edit text: {ex.Message}");
return null;
}
}
/// <inheritdoc/>
public override 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.");
return null;
}
try
{
var inlineMarkup = BuildInlineMarkup(inlineButtons);
await _client.EditMessageReplyMarkup(
chatId: long.Parse(chatId),
messageId: int.Parse(messageId),
replyMarkup: inlineMarkup,
cancellationToken: ct
);
return messageId;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to edit buttons: {ex.Message}");
return null;
}
}
/// <inheritdoc/>
public override 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.");
return false;
}
try
{
await _client.PinChatMessage(
chatId: long.Parse(chatId),
messageId: int.Parse(messageId),
disableNotification: disableNotification,
cancellationToken: ct
);
return true;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to pin message: {ex.Message}");
return false;
}
}
/// <inheritdoc/>
public override async Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return false;
}
try
{
await _client.UnpinChatMessage(
chatId: long.Parse(chatId),
messageId: int.Parse(messageId),
cancellationToken: ct
);
return true;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to unpin message: {ex.Message}");
return false;
}
}
/// <inheritdoc/>
public override 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,
bool disableNotification = false, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized.");
return null;
}
try
{
var message = await _client.ForwardMessage(
chatId: long.Parse(toChatId),
fromChatId: long.Parse(fromChatId),
messageId: int.Parse(messageId),
disableNotification: disableNotification,
cancellationToken: ct
);
return message.MessageId.ToString();
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to forward message: {ex.Message}");
return null;
}
}
/// <inheritdoc/>
public override 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.");
return null;
}
try
{
var parseMode = GetParseMode(captionFormat);
var message = await _client.CopyMessage(
chatId: long.Parse(toChatId),
fromChatId: long.Parse(fromChatId),
messageId: int.Parse(messageId),
caption: caption,
parseMode: parseMode,
disableNotification: disableNotification,
cancellationToken: ct
);
return message.Id.ToString();
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Failed to copy message: {ex.Message}");
return null;
}
}
// --- Helpers ---
@@ -209,21 +423,64 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
}
}
private async Task<Message?> SendFileAsync(FileDescriptor file, string chatId, ReplyMarkup? markup, bool disableNotification, string? caption, MessageFormat? captionFormat, CancellationToken ct)
private async Task<Message?> SendFileAsync(FileDescriptor file, string chatId, ReplyMarkup? markup,
bool disableNotification, string? caption, MessageFormat? captionFormat, int? replyToMessageId,
bool protectContent, CancellationToken ct)
{
var inputFile = await CreateInputFileAsync(file, ct);
var parseMode = GetParseMode(captionFormat);
return file.Kind switch
{
FileKind.Photo => await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct),
FileKind.Video => await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct),
FileKind.Audio => await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct),
_ => await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct),
FileKind.Photo => await _client.SendPhoto(
long.Parse(chatId),
inputFile,
caption ?? "",
parseMode,
replyParameters: replyToMessageId,
replyMarkup: markup,
disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct),
FileKind.Video => await _client.SendVideo(
long.Parse(chatId),
inputFile,
caption: caption ?? "",
parseMode,
replyParameters: replyToMessageId,
replyMarkup: markup,
disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct),
FileKind.Audio => await _client.SendAudio(
long.Parse(chatId),
inputFile,
caption ?? "",
parseMode,
replyParameters: replyToMessageId,
replyMarkup: markup,
disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct),
_ => await _client.SendDocument(
long.Parse(chatId),
inputFile,
caption ?? "",
parseMode,
replyParameters: replyToMessageId,
replyMarkup: markup,
disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct),
};
}
private async Task<string?> SendTextAsync(SendRequest req, InlineKeyboardMarkup? inlineMarkup, ReplyMarkup? markup, bool disableNotification, CancellationToken ct)
private async Task<string?> SendTextAsync(SendRequest req, InlineKeyboardMarkup? inlineMarkup,
ReplyMarkup? markup, bool disableNotification, int? replyToMessageId,
bool disableWebPagePreview, bool protectContent, CancellationToken ct)
{
var format = req.TextFormat ?? MessageFormat.Plain;
var parseMode = GetParseMode(format);
@@ -242,6 +499,10 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
chatId: long.Parse(req.ChatId),
text: text,
parseMode: parseMode,
linkPreviewOptions: new()
{
IsDisabled = disableWebPagePreview,
},
replyMarkup: inlineMarkup,
cancellationToken: ct
);
@@ -256,8 +517,14 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
chatId: long.Parse(req.ChatId),
text: text,
parseMode: parseMode,
linkPreviewOptions: new()
{
IsDisabled = disableWebPagePreview,
},
replyMarkup: markup,
replyParameters: replyToMessageId,
disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct
);
@@ -266,8 +533,8 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
}
/// <inheritdoc />
public IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
public override IAlbumBuilder CreateAlbumBuilder(PageContext ctx) => new TelegramAlbumBuilder(this, ctx, _logger, _client);
/// <inheritdoc />
public Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
public override Task OnLeaveAsync(PageContext ctx, CancellationToken ct) => Task.CompletedTask;
}

View File

@@ -19,29 +19,56 @@ public static class TelegramUpdateMapper
/// <summary>
/// Маппинг Telegram Update в UpdateContext BotPages.
/// </summary>
public static UpdateContext Map(string MessengerType, Update update, TelegramBotClient client)
public static UpdateContext? Map(TelegramAdapter adapter, Update update, TelegramBotClient client)
{
var chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat;
var user = update.Message?.From ?? update.CallbackQuery?.From;
var chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat ?? update.EditedMessage?.Chat;
var user = update.Message?.From ?? update.CallbackQuery?.From ?? update.EditedMessage?.From;
if (chat == null || user == null)
return null;
var userContext = new UserContext
{
Id = user?.Id.ToString() ?? "unknown",
DisplayName = user?.Username,
Id = user.Id.ToString(),
DisplayName = user.Username,
};
var chatContext = new ChatContext
{
Id = chat?.Id.ToString() ?? "unknown",
Title = chat?.Title,
Id = chat.Id.ToString(),
Title = chat.Title,
};
string? text = null;
UpdateKind kind = UpdateKind.None;
var files = new List<FileDescriptor>();
string? messageId = null;
string? replyToMessageId = null;
EditInfo? editInfo = null;
DeleteInfo? deleteInfo = null;
PinInfo? pinInfo = null;
// Обработка разных типов обновлений
if (update.Message is { } msg)
{
messageId = msg.MessageId.ToString();
if (msg.ReplyToMessage != null)
{
kind |= UpdateKind.Reply;
replyToMessageId = msg.ReplyToMessage.MessageId.ToString();
}
if (msg.PinnedMessage != null)
{
kind |= UpdateKind.Pin;
pinInfo = new PinInfo
{
MessageId = msg.PinnedMessage.MessageId.ToString(),
PinDate = msg.Date,
NotificationDisabled = false // Telegram не передает эту информацию
};
}
if (msg.Text is not null)
{
@@ -112,28 +139,66 @@ public static class TelegramUpdateMapper
kind |= UpdateKind.File;
}
}
if (update.CallbackQuery is { } cb)
else if (update.EditedMessage is { } editedMsg)
{
messageId = editedMsg.MessageId.ToString();
kind |= UpdateKind.Edit;
text = editedMsg.Text;
editInfo = new EditInfo
{
NewText = editedMsg.Text,
EditDate = editedMsg.EditDate ?? DateTime.UtcNow
};
}
else if (update.CallbackQuery is { } cb)
{
messageId = cb.Message?.MessageId.ToString();
kind |= UpdateKind.Button;
text = cb.Data;
}
else if (update.ChannelPost is { } channelPost)
{
messageId = channelPost.MessageId.ToString();
if (channelPost.Text is not null)
{
text = channelPost.Text;
kind |= UpdateKind.Text;
}
}
else if (update.EditedChannelPost is { } editedChannelPost)
{
messageId = editedChannelPost.MessageId.ToString();
kind |= UpdateKind.Edit;
text = editedChannelPost.Text;
editInfo = new EditInfo
{
NewText = editedChannelPost.Text,
EditDate = editedChannelPost.EditDate ?? DateTime.UtcNow
};
}
return new UpdateContext
{
MessengerType = MessengerType,
AdapterId = adapter.AdapterId,
AdapterType = adapter.AdapterType,
User = userContext,
Chat = chatContext,
Text = text,
Kind = kind,
Files = files
MessageId = messageId,
ReplyToMessageId = replyToMessageId,
Files = files,
EditInfo = editInfo,
DeleteInfo = deleteInfo,
PinInfo = pinInfo
};
}
private static Func<CancellationToken, Task<Stream>> GetStreamAsync(TelegramBotClient client, string fileId)
{
Func<CancellationToken, Task<Stream>> getStreamAsync = async _ =>
{
var file = await client.GetFile(fileId);

View File

@@ -51,8 +51,16 @@ namespace Demo
.AddTelegramAdapter(token, "Telegram")
.Build(cts.Token);
Console.ReadKey();
cts.Cancel();
Console.WriteLine("Bot is running. Press Ctrl+C to stop.");
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Cancel key pressed");
cts.Cancel();
e.Cancel = true;
};
app.Wait();
}
}
}