6 Commits

Author SHA1 Message Date
47921b1621 Доработано управление жизненным циклом
All checks were successful
CI / build-test (push) Successful in 38s
Release / pack-and-publish (release) Successful in 39s
2026-02-07 03:47:09 +03:00
5dc071c750 Доработка работы с несколькими адаптерами 2026-02-06 07:45:19 +03:00
cd280369bc Добавлены новые методы отправки сообщений 2026-02-06 05:58:15 +03:00
69ff3cf7d4 Исправлена очистка кнопок при отправке сообщения
All checks were successful
CI / build-test (push) Successful in 42s
Release / pack-and-publish (release) Successful in 47s
2026-01-13 21:24:27 +03:00
0ed47b2b90 Исправлен возврат messageId при отправке сообщения
All checks were successful
CI / build-test (push) Successful in 38s
Release / pack-and-publish (release) Successful in 43s
2026-01-13 21:22:06 +03:00
FrigaT
f29e72a6f2 Добавлен метод удаления сообщения
All checks were successful
CI / build-test (push) Successful in 48s
Release / pack-and-publish (release) Successful in 51s
2026-01-13 20:38:41 +03:00
26 changed files with 1654 additions and 237 deletions

View File

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

View File

@@ -1,6 +1,28 @@
namespace BotPages.Core.Abstractions; using BotPages.Core.Context;
namespace BotPages.Core.Abstractions;
/// <summary> /// <summary>
/// Ключ для идентификации пользовательской сессии. /// Ключ для идентификации пользовательской сессии.
/// </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.Adapter.Id,
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.Context;
using BotPages.Core.Messaging;
namespace BotPages.Core.Abstractions; namespace BotPages.Core.Abstractions;
@@ -8,6 +9,16 @@ namespace BotPages.Core.Abstractions;
/// </summary> /// </summary>
public interface IMessengerAdapter public interface IMessengerAdapter
{ {
/// <summary>
/// Уникальный идентификатор адаптера.
/// </summary>
string Id { get; }
/// <summary>
/// Тип адаптера (Telegram, VK, WhatsApp и т.д.).
/// </summary>
string Type { get; }
/// <summary> /// <summary>
/// Доступные возможности мессенджера. /// Доступные возможности мессенджера.
/// </summary> /// </summary>
@@ -18,6 +29,58 @@ public interface IMessengerAdapter
/// </summary> /// </summary>
Task<string?> SendAsync(SendRequest request, CancellationToken ct = default); Task<string?> SendAsync(SendRequest request, CancellationToken ct = default);
/// <summary>
/// Универсальный метод удаления сообщения.
/// </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>
/// Создать билдер альбома для отправки медиагруппы. /// Создать билдер альбома для отправки медиагруппы.
/// </summary> /// </summary>
@@ -34,10 +97,16 @@ public interface IMessengerAdapter
/// </summary> /// </summary>
public interface IMessengerAdapterSetup : IMessengerAdapter public interface IMessengerAdapterSetup : IMessengerAdapter
{ {
/// <summary>
/// Внутренний метод для установки ID адаптера.
/// </summary>
void SetAdapterId(string adapterId);
/// <summary> /// <summary>
/// Запуск работы адаптера /// Запуск работы адаптера
/// </summary> /// </summary>
/// <param name="onUpdate"></param> /// <param name="onUpdate"></param>
/// <param name="commands"></param>
/// <param name="ct"></param> /// <param name="ct"></param>
/// <returns></returns> /// <returns></returns>
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct); Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct);

View File

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

@@ -1,50 +1,128 @@
namespace BotPages.Core.Abstractions; namespace BotPages.Core.Abstractions;
/// <summary> /// <summary>
/// Реализация <see cref="IMessengerAdapterFactory"/>, позволяющая регистрировать и разрешать несколько адаптеров мессенджеров. /// Реализация <see cref="IMessengerAdapterFactory"/>, позволяющая регистрировать и разрешать несколько адаптеров.
/// </summary> /// </summary>
public sealed class MultiAdapterFactory : IMessengerAdapterFactory 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>
/// Список зарегистрированных адаптеров. /// Список всех зарегистрированных адаптеров.
/// </summary> /// </summary>
public Dictionary<string, IMessengerAdapterSetup> Adapters => _adapters; public IReadOnlyList<IMessengerAdapterSetup> AllAdapters => _allAdapters;
/// <summary> /// <summary>
/// Зарегистрировать адаптер для указанного типа мессенджера. /// Зарегистрировать адаптер с уникальным идентификатором.
/// </summary> /// </summary>
/// <param name="messengerType"> public IMessengerAdapterFactory Register(string adapterId, IMessengerAdapterSetup adapter)
/// Тип мессенджера (например, "Telegram", "Slack", "VK").
/// </param>
/// <param name="adapter">
/// Экземпляр адаптера, реализующий <see cref="IMessengerAdapter"/>.
/// </param>
/// <returns>
/// Текущий экземпляр <see cref="MultiAdapterFactory"/> для цепочки вызовов.
/// </returns>
public IMessengerAdapterFactory Register(string messengerType, 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));
// Устанавливаем идентификатор в адаптер
adapter.SetAdapterId(adapterId);
_allAdapters.Add(adapter);
_adaptersById[adapterId] = adapter;
// Группируем по типу
var adapterType = adapter.Type;
if (!_adaptersByType.TryGetValue(adapterType, out var typeList))
{
typeList = new List<IMessengerAdapterSetup>();
_adaptersByType[adapterType] = typeList;
}
typeList.Add(adapter);
return this; return this;
} }
/// <summary> /// <summary>
/// Получить адаптер для указанного мессенджера. /// Зарегистрировать адаптер с автоматически сгенерированным ID.
/// </summary> /// </summary>
/// <param name="messengerType"> public IMessengerAdapterFactory Register(IMessengerAdapterSetup adapter)
/// Тип мессенджера (например, "Telegram", "Slack", "VK"). {
/// </param> var adapterId = GenerateAdapterId(adapter);
/// <returns> return Register(adapterId, adapter);
/// Экземпляр <see cref="IMessengerAdapter"/>, зарегистрированный для данного типа мессенджера. }
/// </returns>
/// <exception cref="InvalidOperationException"> /// <summary>
/// Выбрасывается, если адаптер для указанного типа не зарегистрирован. /// Получить адаптер по ID.
/// </exception> /// </summary>
public IMessengerAdapter Resolve(string messengerType) public IMessengerAdapter Resolve(string adapterId)
=> _adapters.TryGetValue(messengerType, out var adapter) {
? adapter if (_adaptersById.TryGetValue(adapterId, out var adapter))
: throw new InvalidOperationException($"No adapter registered for {messengerType}"); {
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 = adapter.Type;
if (_adaptersByType.TryGetValue(adapterType, out var typeList))
{
typeList.Remove(adapter);
if (typeList.Count == 0)
{
_adaptersByType.Remove(adapterType);
}
}
return true;
}
return false;
}
private static string GenerateAdapterId(IMessengerAdapter adapter)
{
var adapterType = adapter.Type;
var guid = Guid.NewGuid().ToString("N").Substring(0, 8);
return $"{adapterType}_{guid}".ToLowerInvariant();
}
} }

View File

@@ -39,4 +39,66 @@ public sealed class SendRequest
/// Содержит имена/ключи адаптеров и соответствующие объекты опций. /// Содержит имена/ключи адаптеров и соответствующие объекты опций.
/// </summary> /// </summary>
public AdapterOptionsBag? AdapterOptions { get; init; } 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

@@ -5,12 +5,13 @@ using BotPages.Core.Context;
using BotPages.Core.Logging; using BotPages.Core.Logging;
using BotPages.Core.Routing; using BotPages.Core.Routing;
using System.Reflection; using System.Reflection;
using System.Threading;
/// <summary> /// <summary>
/// Основное приложение BotPages. /// Основное приложение BotPages.
/// Управляет маршрутизацией, командами, middleware и страницами. /// Управляет маршрутизацией, командами, middleware и страницами.
/// </summary> /// </summary>
public sealed class BotPagesApp public sealed class BotPagesApp : IDisposable, IAsyncDisposable
{ {
private readonly IMessengerAdapterFactory _adapterFactory; private readonly IMessengerAdapterFactory _adapterFactory;
private readonly List<IPageMiddleware> _middlewares = new(); private readonly List<IPageMiddleware> _middlewares = new();
@@ -19,12 +20,21 @@ public sealed class BotPagesApp
private readonly IStateStorage _state; private readonly IStateStorage _state;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly NavigationService _navigation; private readonly NavigationService _navigation;
private CancellationTokenSource? _internalCts;
private bool _isRunning;
private bool _disposed;
/// <summary> /// <summary>
/// Серсвис логирования. /// Серсвис логирования.
/// </summary> /// </summary>
public ILogger Logger => _logger; public ILogger Logger => _logger;
/// <summary>
/// ТОкен отмены приложения. Отменяется при вызове Stop() или при отмене внешнего токена, переданного в RunAsync.
/// </summary>
public CancellationToken CancellationToken => _internalCts?.Token ?? CancellationToken.None;
/// <summary> /// <summary>
/// Создать приложение BotPages. /// Создать приложение BotPages.
/// </summary> /// </summary>
@@ -38,14 +48,40 @@ public sealed class BotPagesApp
} }
/// <summary> /// <summary>
/// Добавить адаптер. /// Добавить адаптер с указанием ID.
/// </summary> /// </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; 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>
/// Установить страницу по умолчанию. /// Установить страницу по умолчанию.
/// </summary> /// </summary>
@@ -151,14 +187,14 @@ public sealed class BotPagesApp
/// <summary> /// <summary>
/// Обработать входящее обновление. /// Обработать входящее обновление.
/// </summary> /// </summary>
public async Task HandleUpdateAsync(UpdateContext update, CancellationToken ct) public async Task HandleUpdateAsync(UpdateContext update)
{ {
var ctx = await CreatePageContextAsync(update, ct); var ctx = await CreatePageContextAsync(update);
// Команды выше событий страниц // Команды выше событий страниц
if (update.Kind == UpdateKind.Text && update.Text is not null && update.Text.StartsWith("/")) if (update.Kind == UpdateKind.Text && update.Text is not null && update.Text.StartsWith("/"))
{ {
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null) if (_commands.TryDispatch(ctx, update.Text, this.CancellationToken, out var dispatched) && dispatched is not null)
{ {
await dispatched; await dispatched;
return; return;
@@ -168,74 +204,72 @@ public sealed class BotPagesApp
// Конвейер middleware // Конвейер middleware
var pipeline = BuildPipeline(ctx, async () => var pipeline = BuildPipeline(ctx, async () =>
{ {
await DispatchToPageAsync(ctx, update, ct); await DispatchToPageAsync(ctx, update);
}); });
await pipeline(); await pipeline();
} }
/// <summary>
/// Создать контекст страницы для текущего обновления.
/// </summary>
private async Task<PageContext> CreatePageContextAsync(UpdateContext update)
{
var sessionKey = CompositeSessionKey.FromUpdate(update);
var ctx = new PageContext
{
Update = update,
SessionKey = sessionKey,
StateStorage = _state,
Navigation = _navigation,
Adapter = _adapterFactory.Resolve(update.Adapter.Id),
AdapterFactory = _adapterFactory,
};
return await Task.FromResult(ctx);
}
private Func<Task> BuildPipeline(PageContext ctx, Func<Task> terminal) private Func<Task> BuildPipeline(PageContext ctx, Func<Task> terminal)
{ {
Func<Task> next = terminal; Func<Task> next = terminal;
foreach (var mw in _middlewares.AsEnumerable().Reverse()) foreach (var mw in _middlewares.AsEnumerable().Reverse())
{ {
var prev = next; var prev = next;
next = () => mw.InvokeAsync(ctx, prev, _currentCt); next = () => mw.InvokeAsync(ctx, prev, this.CancellationToken);
} }
return next; return next;
} }
// Технические поля для конвейера
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>
/// Отправить обновление на текущую страницу. /// Отправить обновление на текущую страницу.
/// </summary> /// </summary>
private async Task DispatchToPageAsync(PageContext ctx, UpdateContext update, CancellationToken ct) private async Task DispatchToPageAsync(PageContext ctx, UpdateContext update)
{ {
var page = ResolveCurrentPage(ctx); var page = ResolveCurrentPage(ctx);
if (page is null) if (page is null)
{ {
await ctx.Navigation.GoToHomeAsync(ctx, ct); await ctx.Navigation.GoToHomeAsync(ctx, this.CancellationToken);
return; return;
} }
try try
{ {
await page.OnUpdate(ctx, update, ct); await page.OnUpdate(ctx, update, this.CancellationToken);
if (update.Kind.HasFlag(UpdateKind.Text) && update.Text is not null) await page.OnText(ctx, update.Text, ct); if (update.Kind.HasFlag(UpdateKind.Text) && update.Text is not null) await page.OnText(ctx, update.Text, this.CancellationToken);
if (update.Kind.HasFlag(UpdateKind.Button) && update.Text is not null) await page.OnButton(ctx, update.Text, ct); if (update.Kind.HasFlag(UpdateKind.Button) && update.Text is not null) await page.OnButton(ctx, update.Text, this.CancellationToken);
if (update.Kind.HasFlag(UpdateKind.File) && update.Files.Count > 0) await page.OnFile(ctx, update.Files, ct); if (update.Kind.HasFlag(UpdateKind.File) && update.Files.Count > 0) await page.OnFile(ctx, update.Files, this.CancellationToken);
if (update.Kind.HasFlag(UpdateKind.Pin) && update.PinInfo is not null) await page.OnPin(ctx, update.PinInfo, this.CancellationToken);
if (update.Kind.HasFlag(UpdateKind.Delete) && update.DeleteInfo is not null) await page.OnDelete(ctx, update.DeleteInfo, this.CancellationToken);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.Log(LogLevel.Critical, "Unhandled page error.", ex); _logger.Log(LogLevel.Critical, "Unhandled page error.", ex);
await page.OnError(ctx, ex, ct); await page.OnError(ctx, ex, this.CancellationToken);
} }
} }
@@ -245,16 +279,166 @@ public sealed class BotPagesApp
private Page? ResolveCurrentPage(PageContext ctx) private Page? ResolveCurrentPage(PageContext ctx)
=> _navigation.ResolveCurrentPage(ctx); => _navigation.ResolveCurrentPage(ctx);
/// <summary>
/// Запустить приложение и синхронно ожидать его завершения.
/// </summary>
/// <param name="ct">Токен отмены для остановки приложения извне</param>
public void Run(CancellationToken ct = default)
{
RunAsync(ct).Wait();
}
/// <summary> /// <summary>
/// Сборка и запуск приложения. /// Сборка и запуск приложения.
/// </summary> /// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task Build(CancellationToken cancellationToken) public async Task RunAsync() => await RunAsync(new CancellationTokenSource().Token);
/// <summary>
/// Сборка и запуск приложения.
/// </summary>
/// <returns></returns>
public async Task RunAsync(CancellationToken ct = default)
{ {
foreach (var adapter in _adapterFactory.Adapters) if (_isRunning)
throw new InvalidOperationException("Application is already running.");
if (_disposed)
throw new ObjectDisposedException(nameof(BotPagesApp));
_internalCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
try
{ {
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken); _logger.Log(LogLevel.Info, "Starting BotPages application...");
var adapterTasks = new List<Task>();
foreach (var adapter in _adapterFactory.AllAdapters)
{
var adapterTask = adapter.StartAdapterAsync(HandleUpdateAsync, _commands.Commands, CancellationToken);
adapterTasks.Add(adapterTask);
}
await Task.WhenAll(adapterTasks);
_isRunning = true;
_logger.Log(LogLevel.Info, "BotPages application started successfully.");
}
catch (Exception ex)
{
_internalCts?.Dispose();
_internalCts = null;
_logger.Log(LogLevel.Critical, "Failed to start BotPages application.", ex);
throw;
}
_isRunning = true;
}
/// <summary>
/// Остановить работу приложения.
/// </summary>
public void Stop()
{
if (!_isRunning || _disposed)
return;
_logger.Log(LogLevel.Info, "Stopping BotPages application...");
_internalCts?.Cancel();
}
/// <summary>
/// Синхронно ожидать завершения работы приложения.
/// </summary>
/// <exception cref="InvalidOperationException">Если приложение не запущено</exception>
public void Wait()
{
if (!_isRunning)
throw new InvalidOperationException("Application is not running.");
try
{
// Ждем, пока токен не будет отменен
WaitHandle.WaitAny([_internalCts.Token.WaitHandle]);
}
catch (AggregateException ex) when (ex.InnerException is OperationCanceledException)
{
// Игнорируем отмену операции
}
finally
{
_isRunning = false;
}
}
/// <summary>
/// Асинхронно ожидать завершения работы приложения.
/// Ожидает, пока не будет вызван <see cref="Stop"/> или внешний <see cref="CancellationTokenSource"/> не будет отменен.
/// </summary>
public async Task WaitAsync()
{
if (!_isRunning || _internalCts == null)
return;
try
{
var tcs = new TaskCompletionSource<bool>();
using (_internalCts.Token.Register(() => tcs.TrySetResult(true)))
{
await tcs.Task;
}
}
catch (ObjectDisposedException)
{
// Токен уже освобожден
}
finally
{
_isRunning = false;
}
}
/// <inheritdoc/>
public void Dispose()
{
DisposeAsync().AsTask().Wait();
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
_disposed = true;
// Останавливаем приложение, если оно запущено
if (_isRunning)
{
Stop();
}
_internalCts?.Dispose();
foreach (var adapter in _adapterFactory.AllAdapters)
{
try
{
if (adapter is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
else if (adapter is IDisposable disposable)
{
disposable.Dispose();
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Warn, $"Error disposing adapter {adapter.Id}: {ex.Message}");
}
} }
} }
} }

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> /// <summary>Хранилище состояния.</summary>
public required IStateStorage StateStorage { get; init; } public required IStateStorage StateStorage { get; init; }
/// <summary>Сервис навигации.</summary> /// <summary>Сервис навигации.</summary>
public required NavigationService Navigation { get; init; } public required NavigationService Navigation { get; init; }
/// <summary>Адаптер мессенджера.</summary>
/// <summary>Фабрика адаптеров (для получения других адаптеров).</summary>
public required IMessengerAdapterFactory AdapterFactory { get; init; }
/// <summary>Текущий адаптер мессенджера.</summary>
public required IMessengerAdapter Adapter { get; init; } public required IMessengerAdapter Adapter { get; init; }
/// <summary> /// <summary>
@@ -26,4 +31,36 @@ public sealed class PageContext
/// </summary> /// </summary>
public IAlbumBuilder Albums => Adapter.CreateAlbumBuilder(this); 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.Adapter.Type;
/// <summary>
/// Получить текущий ID адаптера.
/// </summary>
public string CurrentAdapterId => Update.Adapter.Id;
/// <summary>
/// Получить все адаптеры.
/// </summary>
public IReadOnlyList<IMessengerAdapter> AllAdapters => AdapterFactory.AllAdapters;
} }

View File

@@ -1,4 +1,5 @@
using BotPages.Core.Abstractions; using BotPages.Core.Abstractions;
using BotPages.Core.Messaging;
namespace BotPages.Core; namespace BotPages.Core;
@@ -9,8 +10,118 @@ namespace BotPages.Core;
public static class PageContextAdapterExtensions public static class PageContextAdapterExtensions
{ {
/// <summary> /// <summary>
/// Отправить универсальный запрос через привязанный адаптер. /// Отправить сообщение универсальным запросом через привязанный адаптер.
/// </summary> /// </summary>
public static Task<string?> SendAsync(this PageContext ctx, SendRequest request, CancellationToken ct = default) public static Task<string?> SendAsync(this PageContext ctx, SendRequest request, CancellationToken ct = default)
=> ctx.Adapter.SendAsync(request, ct); => ctx.Adapter.SendAsync(request, ct);
/// <summary>
/// Удалить сообщение через привязанный адаптер.
/// </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; 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>
/// Контекст входящего обновления от мессенджера. /// Контекст входящего обновления от мессенджера.
@@ -27,8 +8,8 @@ public enum UpdateKind
/// </summary> /// </summary>
public sealed class UpdateContext public sealed class UpdateContext
{ {
/// <summary>Тип мессенджера.</summary> /// <summary>Адаптер, от которого пришло обновление.</summary>
public required string MessengerType { get; init; } public required IMessengerAdapter Adapter { get; init; }
/// <summary> /// <summary>
/// Данные пользователя, от которого пришло обновление. /// Данные пользователя, от которого пришло обновление.
@@ -51,9 +32,34 @@ public sealed class UpdateContext
/// </summary> /// </summary>
public string? Text { get; init; } public string? Text { get; init; }
/// <summary>
/// ID сообщения, к которому относится обновление.
/// </summary>
public string? MessageId { get; init; }
/// <summary>
/// ID сообщения, на которое дан ответ (если есть).
/// </summary>
public string? ReplyToMessageId { get; init; }
/// <summary> /// <summary>
/// Список файлов, если Kind = File. /// Список файлов, если Kind = File.
/// Может содержать один или несколько файлов. /// Может содержать один или несколько файлов.
/// </summary> /// </summary>
public List<FileDescriptor> Files { get; init; } = new(); 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> /// <summary>
/// Fluentбилдер для отправки сообщений (текст, кнопки, файлы, альбомы, прогресс). /// Fluentбилдер для отправки сообщений (текст, кнопки, файлы, альбомы, прогресс).
/// Поддерживает указание адаптер-специфичных опций через `WithAdapterOption`. /// Поддерживает указание адаптер-специфичных опций через <see cref="WithAdapterOption{T}(string, T)"/>.
/// </summary> /// </summary>
public sealed class MessageBuilder public sealed class MessageBuilder
{ {
@@ -16,12 +16,78 @@ public sealed class MessageBuilder
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new(); private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _files = new();
private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new(); private readonly List<(FileDescriptor file, string? caption, MessageFormat? captionFormat)> _album = new();
private bool _disableReplyKeyboard; private bool _disableReplyKeyboard;
private string? _editMessageId = null;
private AdapterOptionsBag? _adapterOptions = null; private AdapterOptionsBag? _adapterOptions = 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> /// <summary>Создать билдер сообщений.</summary>
public MessageBuilder(PageContext ctx) => _ctx = ctx; 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> /// <summary>
/// Установить опции для конкретного адаптера. Ключ адаптера определяется адаптером (напр., "telegram"). /// Установить опции для конкретного адаптера. Ключ адаптера определяется адаптером (напр., "telegram").
/// </summary> /// </summary>
@@ -40,10 +106,68 @@ public sealed class MessageBuilder
return this; return this;
} }
/// <summary>Редактировать сообщение.</summary> /// <summary>Стиль сообщения.</summary>
public MessageBuilder EditMessage(string messagId) public MessageBuilder Style(MessageStyle style)
{ {
_editMessageId = messagId; _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; return this;
} }
@@ -129,30 +253,153 @@ public sealed class MessageBuilder
return this; return this;
} }
/// <summary>Удалить сообщение.</summary>
public async Task DeleteAsync(string messageId, CancellationToken ct = default)
{
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> /// <summary>Отправить собранное сообщение.</summary>
public async Task<string?> SendAsync(CancellationToken ct = default) public async Task<string?> SendAsync(CancellationToken ct = default)
=> await SendAsync(string.Empty, ct);
/// <summary>Редактировать сообщение.</summary>
public async Task<string?> SendAsync(string messageId, CancellationToken ct = default)
{ {
string? messageId = null; _messageId = string.IsNullOrWhiteSpace(messageId) ? null : messageId;
string? outMessageId = null;
List<List<ReplyButton>>? reply = null; List<List<ReplyButton>>? reply = null;
if (_disableReplyKeyboard) reply = new(); if (_disableReplyKeyboard) reply = new();
else if (_reply.Any()) reply = _reply; else if (_reply.Any()) reply = _reply;
// Определяем целевой адаптер
var adapter = GetEffectiveAdapter();
// Определяем целевой чат
var targetChatId = GetEffectiveChatId();
// Текст // Текст
if (!string.IsNullOrWhiteSpace(_text)) if (!string.IsNullOrWhiteSpace(_text))
{ {
var req = new SendRequest var req = new SendRequest
{ {
ChatId = _ctx.Update.Chat.Id, ChatId = targetChatId,
Text = _text, Text = _text,
TextFormat = _format, TextFormat = _format,
Inline = _inline, Inline = _inline,
Reply = reply, Reply = reply,
MessageId = _editMessageId, MessageId = _messageId,
ReplyToMessageId = _replyToMessageId,
QuoteReply = _quoteReply,
QuoteTitle = _quoteTitle,
DisableWebPagePreview = _disableWebPagePreview,
DisableNotification = _disableNotification,
ProtectContent = _protectContent,
Style = _style,
ScheduleDate = _scheduleDate,
Topic = _topic,
AdapterOptions = _adapterOptions AdapterOptions = _adapterOptions
}; };
messageId = await _ctx.SendAsync(req, ct); outMessageId = await adapter.SendAsync(req, ct);
} }
// Файлы // Файлы
@@ -160,36 +407,84 @@ public sealed class MessageBuilder
{ {
var req = new SendRequest var req = new SendRequest
{ {
ChatId = _ctx.Update.Chat.Id, ChatId = targetChatId,
File = file, File = file,
Caption = caption, Caption = caption,
CaptionFormat = captionFormat, CaptionFormat = captionFormat,
Inline = _inline, Inline = _inline,
Reply = reply, Reply = reply,
ReplyToMessageId = _replyToMessageId,
QuoteReply = _quoteReply,
QuoteTitle = _quoteTitle,
DisableWebPagePreview = _disableWebPagePreview,
DisableNotification = _disableNotification,
ProtectContent = _protectContent,
Style = _style,
ScheduleDate = _scheduleDate,
Topic = _topic,
AdapterOptions = _adapterOptions AdapterOptions = _adapterOptions
}; };
var res = await _ctx.SendAsync(req, ct); var res = await adapter.SendAsync(req, ct);
// сохранить первый возвращённый id сообщения // сохранить первый возвращённый id сообщения
if (messageId is null && res is not null) messageId = res; if (outMessageId is null && res is not null) outMessageId = res;
} }
// Альбом // Альбом
if (_album.Count > 0) 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) foreach (var (file, caption, captionFormat) in _album)
builder.Add(file, caption, captionFormat); builder.Add(file, caption, captionFormat);
await builder.SendAsync(ct); await builder.SendAsync(ct);
} }
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; _text = null;
_files.Clear(); _files.Clear();
_album.Clear(); _album.Clear();
_editMessageId = null;
_adapterOptions = null; _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 messageId; 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) 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.Adapter.Id} | Chat: {ctx.Update.Chat.Id} | User: {ctx.Update.User.Id}");
// Логируем текст, кнопки, файлы // Логируем текст, кнопки, файлы
if (ctx.Update.Text is not null) if (ctx.Update.Text is not null)

View File

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

View File

@@ -1,4 +1,5 @@
using BotPages.Core; using BotPages.Core;
using System;
namespace BotPages.Telegram; namespace BotPages.Telegram;
@@ -8,25 +9,28 @@ namespace BotPages.Telegram;
public static class BotPagesAppExtension public static class BotPagesAppExtension
{ {
/// <summary> /// <summary>
/// Добавление адаптера для телеграмм в <see cref="BotPages.Core.Abstractions.IMessengerAdapterFactory"/> /// Добавление адаптера для Telegram.
/// </summary> /// </summary>
/// <param name="app"></param> /// <exception cref="ArgumentException">Если адаптер с таким ID уже существует.</exception>
/// <param name="token"></param> public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string adapterId, TelegramOptions? options = null)
/// <param name="messengerType"></param> {
/// <returns></returns> if (app.HasAdapter(adapterId))
public static BotPagesApp AddTelegramAdapter(this BotPagesApp app, string token, string messengerType = "") {
=> app.AddTelegramAdapter(token, null, messengerType); 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> /// <summary>
/// Добавление адаптера для телеграмм с опциями. /// Добавить Telegram бота с автоматическим ID.
/// </summary> /// </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); var telegram = new TelegramAdapter(app.Logger, token, options);
app.AddAdapter(telegram);
if (!string.IsNullOrWhiteSpace(messengerType)) telegram.MessengerType = messengerType;
app.AddAdapter(telegram.MessengerType, telegram);
return app; 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; namespace BotPages.Telegram;
/// <summary> /// <summary>
/// Адаптер для Telegram на базе Telegram.Bot. /// Адаптер для Telegram на базе Telegram.Bot.
/// Реализует отправку текста, кнопок, файлов, альбомов и прогресса. /// Реализует отправку текста, кнопок, файлов, альбомов и прогресса.
/// </summary> /// </summary>
public sealed class TelegramAdapter : IMessengerAdapterSetup public sealed class TelegramAdapter : IMessengerAdapterSetup
{ {
internal static readonly string AdapterType = typeof(TelegramAdapter).FullName;
private readonly ILogger _logger; private readonly ILogger _logger;
private TelegramBotClient? _client; private TelegramBotClient? _client;
private string _token; private string _token;
@@ -45,12 +42,24 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
_logger = logger; _logger = logger;
_token = token; _token = token;
_options = options ?? new TelegramOptions(); _options = options ?? new TelegramOptions();
Id = Guid.NewGuid().ToString();
DisplayName = $"Telegram {Id}";
} }
/// <inheritdoc/>
public string Type => "Telegram";
/// <inheritdoc/>
public string Id { get; set; }
/// <summary> /// <summary>
///Идентификатор мессенджера / адаптера /// Получение отображаемого имени бота (например, "Telegram: @mybot"). Доступно после запуска адаптера.
/// </summary> /// </summary>
public string MessengerType { get; set; } = "Telegram: " + Guid.NewGuid().ToString(); public string DisplayName { get; private set; }
/// <inheritdoc/>
public void SetAdapterId(string adapterId) => Id = adapterId;
/// <summary> /// <summary>
/// Доступные возможности адаптера. /// Доступные возможности адаптера.
@@ -67,7 +76,7 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
_client.StartReceiving( _client.StartReceiving(
updateHandler: async (_, update, ct2) => updateHandler: async (_, update, ct2) =>
{ {
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client); var mapped = TelegramUpdateMapper.Map(this, update, _client);
if (mapped is not null) if (mapped is not null)
await onUpdate(mapped); await onUpdate(mapped);
if (update.CallbackQuery is not null) if (update.CallbackQuery is not null)
@@ -78,18 +87,18 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
errorHandler: async (_, ex, ct2) => errorHandler: async (_, ex, ct2) =>
{ {
_logger.Log(LogLevel.Warn, $"{MessengerType} error.", ex); _logger.Log(LogLevel.Warn, $"{Type} ({Id}) error.", ex);
await Task.CompletedTask; await Task.CompletedTask;
}, },
cancellationToken: ct cancellationToken: ct
); );
await _client.SetMyCommands(commands.Where(t => t.Publish).Select(t => new BotCommand(t.Name, t.Description ?? t.Name.TrimStart('/'))), 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(); var me = await _client.GetMe();
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}"); DisplayName = $"Telegram: @{me.Username}";
_logger.Log(LogLevel.Info, $"{Type} ({Id}) started: {DisplayName}");
return; return;
} }
@@ -102,41 +111,264 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
{ {
if (_client is null) if (_client is null)
{ {
_logger.Log(LogLevel.Critical, $"{MessengerType} client is not initialized."); _logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null; return null;
} }
// Определите параметры адаптера (TelegramOptions) из папки или используйте параметры адаптера по умолчанию. // Определите параметры адаптера (TelegramOptions) из папки или используйте параметры адаптера по умолчанию.
TelegramOptions telegramOptions = _options; 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; telegramOptions = opt;
} }
var disableNotification = !telegramOptions.NotifyOnSend; var disableNotification = !telegramOptions.NotifyOnSend || req.DisableNotification;
// Build markup // Build markup
var inlineMarkup = BuildInlineMarkup(req.Inline); var inlineMarkup = BuildInlineMarkup(req.Inline);
ReplyMarkup? markup = BuildReplyMarkup(req.Reply); ReplyMarkup? markup = BuildReplyMarkup(req.Reply);
// Ответ на сообщение
int? replyToMessageId = null;
if (!string.IsNullOrEmpty(req.ReplyToMessageId) && int.TryParse(req.ReplyToMessageId, out var replyId))
{
replyToMessageId = replyId;
}
// Файлы: сейчас поддерживается один файл через SendRequest.File. // Файлы: сейчас поддерживается один файл через SendRequest.File.
// При необходимости для нескольких файлов следует использовать альбомы (CreateAlbumBuilder) // При необходимости для нескольких файлов следует использовать альбомы (CreateAlbumBuilder)
if (req.File is not null) if (req.File is not null)
{ {
if (inlineMarkup is not null) markup = inlineMarkup; 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(); return sent?.MessageId.ToString();
} }
// Текст // Текст
if (!string.IsNullOrWhiteSpace(req.Text)) 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; return null;
} }
/// <inheritdoc/>
public Task DeleteAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return Task.CompletedTask;
}
return _client.DeleteMessage(chatId, Convert.ToInt32(messageId), ct);
}
/// <inheritdoc/>
public async Task<bool> DeleteMultipleAsync(string chatId, IEnumerable<string> messageIds, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} 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 async Task<string?> EditTextAsync(string chatId, string messageId, string text,
MessageFormat? format = null, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
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 async Task<string?> EditButtonsAsync(string chatId, string messageId,
IEnumerable<IEnumerable<InlineButton>>? inlineButtons = null, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} 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 async Task<bool> PinMessageAsync(string chatId, string messageId, bool disableNotification = false,
CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} 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 async Task<bool> UnpinMessageAsync(string chatId, string messageId, CancellationToken ct = default)
{
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} 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 async Task<MessageInfo?> GetMessageInfoAsync(string chatId, string messageId, CancellationToken ct = default)
{
throw new NotImplementedException();
}
/// <inheritdoc/>
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, $"{Type} 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 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, $"{Type} 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 --- // --- Helpers ---
private InlineKeyboardMarkup? BuildInlineMarkup(IEnumerable<IEnumerable<InlineButton>>? inline) private InlineKeyboardMarkup? BuildInlineMarkup(IEnumerable<IEnumerable<InlineButton>>? inline)
@@ -170,6 +402,7 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
{ {
MessageFormat.Html => ParseMode.Html, MessageFormat.Html => ParseMode.Html,
MessageFormat.Markdown => ParseMode.MarkdownV2, MessageFormat.Markdown => ParseMode.MarkdownV2,
MessageFormat.Plain => ParseMode.None,
_ => ParseMode.None, _ => ParseMode.None,
}; };
} }
@@ -197,22 +430,77 @@ 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)
{ {
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
var inputFile = await CreateInputFileAsync(file, ct); var inputFile = await CreateInputFileAsync(file, ct);
var parseMode = GetParseMode(captionFormat); var parseMode = GetParseMode(captionFormat);
return file.Kind switch return file.Kind switch
{ {
FileKind.Photo => await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct), FileKind.Photo => await _client.SendPhoto(
FileKind.Video => await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct), long.Parse(chatId),
FileKind.Audio => await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct), inputFile,
_ => await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, disableNotification: disableNotification, cancellationToken: ct), 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)
{ {
if (_client is null)
{
_logger.Log(LogLevel.Critical, $"{Type} client is not initialized.");
return null;
}
var format = req.TextFormat ?? MessageFormat.Plain; var format = req.TextFormat ?? MessageFormat.Plain;
var parseMode = GetParseMode(format); var parseMode = GetParseMode(format);
@@ -230,6 +518,10 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
chatId: long.Parse(req.ChatId), chatId: long.Parse(req.ChatId),
text: text, text: text,
parseMode: parseMode, parseMode: parseMode,
linkPreviewOptions: new()
{
IsDisabled = disableWebPagePreview,
},
replyMarkup: inlineMarkup, replyMarkup: inlineMarkup,
cancellationToken: ct cancellationToken: ct
); );
@@ -244,8 +536,14 @@ public sealed class TelegramAdapter : IMessengerAdapterSetup
chatId: long.Parse(req.ChatId), chatId: long.Parse(req.ChatId),
text: text, text: text,
parseMode: parseMode, parseMode: parseMode,
linkPreviewOptions: new()
{
IsDisabled = disableWebPagePreview,
},
replyMarkup: markup, replyMarkup: markup,
replyParameters: replyToMessageId,
disableNotification: disableNotification, disableNotification: disableNotification,
protectContent: protectContent,
cancellationToken: ct cancellationToken: ct
); );

View File

@@ -19,29 +19,56 @@ public static class TelegramUpdateMapper
/// <summary> /// <summary>
/// Маппинг Telegram Update в UpdateContext BotPages. /// Маппинг Telegram Update в UpdateContext BotPages.
/// </summary> /// </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 chat = update.Message?.Chat ?? update.CallbackQuery?.Message?.Chat ?? update.EditedMessage?.Chat;
var user = update.Message?.From ?? update.CallbackQuery?.From; var user = update.Message?.From ?? update.CallbackQuery?.From ?? update.EditedMessage?.From;
if (chat == null || user == null)
return null;
var userContext = new UserContext var userContext = new UserContext
{ {
Id = user?.Id.ToString() ?? "unknown", Id = user.Id.ToString(),
DisplayName = user?.Username, DisplayName = user.Username,
}; };
var chatContext = new ChatContext var chatContext = new ChatContext
{ {
Id = chat?.Id.ToString() ?? "unknown", Id = chat.Id.ToString(),
Title = chat?.Title, Title = chat.Title,
}; };
string? text = null; string? text = null;
UpdateKind kind = UpdateKind.None; UpdateKind kind = UpdateKind.None;
var files = new List<FileDescriptor>(); 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) 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) if (msg.Text is not null)
{ {
@@ -112,37 +139,80 @@ public static class TelegramUpdateMapper
kind |= UpdateKind.File; kind |= UpdateKind.File;
} }
} }
else if (update.EditedMessage is { } editedMsg)
if (update.CallbackQuery is { } cb)
{ {
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; kind |= UpdateKind.Button;
text = cb.Data; 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 return new UpdateContext
{ {
MessengerType = MessengerType, Adapter = adapter,
User = userContext, User = userContext,
Chat = chatContext, Chat = chatContext,
Text = text, Text = text,
Kind = kind, 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) private static Func<CancellationToken, Task<Stream>> GetStreamAsync(TelegramBotClient client, string fileId)
{ {
return async ct =>
Func<CancellationToken, Task<Stream>> getStreamAsync = async _ =>
{ {
var file = await client.GetFile(fileId); try
{
var file = await client.GetFile(fileId, ct);
var stream = new MemoryStream(); var stream = new MemoryStream();
await client.DownloadFile(file, stream); await client.DownloadFile(file.FilePath!, stream, ct);
stream.Position = 0; stream.Position = 0;
return stream; return stream;
}
catch (Exception ex)
{
return Stream.Null;
throw;
}
}; };
return getStreamAsync;
} }
} }

View File

@@ -23,7 +23,7 @@ public sealed class FileSendPage : SingletonPage
GetStreamAsync = _ => Task.FromResult<Stream>(stream) GetStreamAsync = _ => Task.FromResult<Stream>(stream)
}; };
await new MessageBuilder(ctx) var msg = await new MessageBuilder(ctx)
.Text("Вот пример отправки нового файла 📎", MessageFormat.Markdown) .Text("Вот пример отправки нового файла 📎", MessageFormat.Markdown)
.File(demoFile, "Демонстрационный файл") .File(demoFile, "Демонстрационный файл")
.SendAsync(ct); .SendAsync(ct);

View File

@@ -21,8 +21,7 @@ public sealed class SubmitPage : SingletonPage
Thread.Sleep(TimeSpan.FromMilliseconds(200)); Thread.Sleep(TimeSpan.FromMilliseconds(200));
await new MessageBuilder(ctx) await new MessageBuilder(ctx)
.Text($"Отправка заявки\n{i}%") .Text($"Отправка заявки\n{i}%")
.EditMessage(messageId!) .SendAsync(messageId, ct);
.SendAsync(ct);
} }
while (i < 100); while (i < 100);

View File

@@ -17,7 +17,6 @@ namespace Demo
var logger = new ConsoleLogger(); var logger = new ConsoleLogger();
var state = new InMemoryStateStorage(); var state = new InMemoryStateStorage();
using var cts = new CancellationTokenSource();
// Можно использовать команды для открытия страниц с роутингом // Можно использовать команды для открытия страниц с роутингом
// /open Welcome // /open Welcome
@@ -48,11 +47,20 @@ namespace Demo
.AutoMapRoute() .AutoMapRoute()
.AddMiddleware(new ErrorHandlingMiddleware(logger)) .AddMiddleware(new ErrorHandlingMiddleware(logger))
.AddMiddleware(new LoggingMiddleware(logger)) .AddMiddleware(new LoggingMiddleware(logger))
.AddTelegramAdapter(token, "Telegram") .AddTelegramAdapter(token, "Telegram");
.Build(cts.Token);
Console.ReadKey(); await app.RunAsync();
cts.Cancel();
logger.Log(LogLevel.Info, "Bot is running. Press Ctrl+C to stop.");
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Cancel key pressed");
app.Stop();
e.Cancel = true;
};
await app.WaitAsync();
} }
} }
} }