Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67de9e197a | |||
| edc718b1f9 | |||
| 8af03fa52b | |||
| d6f54bb0e6 |
@@ -9,22 +9,33 @@ namespace BotPages.Core.Abstractions;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IMessengerAdapter
|
public interface IMessengerAdapter
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Доступные возможности мессенджера.
|
||||||
|
/// </summary>
|
||||||
Capabilities Capabilities { get; }
|
Capabilities Capabilities { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение в чат.
|
/// Отправить текстовое сообщение в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<string?> SendTextAsync(string chatId, string text, MessageFormat format,
|
Task<string?> SendTextAsync(string chatId,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
string text,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
string? messageId,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
CancellationToken ct
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
string? messageId = null,
|
||||||
|
CancellationToken ct = default
|
||||||
);
|
);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл в чат.
|
/// Отправить файл в чат.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct);
|
Task SendFileAsync(string chatId,
|
||||||
|
FileDescriptor file,
|
||||||
|
string? caption = null,
|
||||||
|
MessageFormat? captionFormat = null,
|
||||||
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Создать билдер альбома для отправки медиагруппы.
|
/// Создать билдер альбома для отправки медиагруппы.
|
||||||
@@ -48,5 +59,5 @@ public interface IMessangerAdapterSetup : IMessengerAdapter
|
|||||||
/// <param name="onUpdate"></param>
|
/// <param name="onUpdate"></param>
|
||||||
/// <param name="ct"></param>
|
/// <param name="ct"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, CancellationToken ct);
|
Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<Routing.Command> commands, CancellationToken ct);
|
||||||
}
|
}
|
||||||
@@ -69,16 +69,34 @@ public sealed class BotPagesApp
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public BotPagesApp MapCommand<TPage>(string commandTemplate) where TPage : Page
|
public BotPagesApp MapCommand<TPage>(string commandTemplate) where TPage : Page
|
||||||
{
|
{
|
||||||
_commands.Map<TPage>(commandTemplate);
|
_commands.Map<TPage>(commandTemplate, false, null);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Зарегистрировать команду, ведущую на страницу.
|
||||||
|
/// </summary>
|
||||||
|
public BotPagesApp MapCommand<TPage>(string commandTemplate, bool publish, string description) where TPage : Page
|
||||||
|
{
|
||||||
|
_commands.Map<TPage>(commandTemplate, publish, description);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Зарегистрировать команду с кастомным обработчиком.
|
/// Зарегистрировать команду с кастомным обработчиком.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public BotPagesApp MapCommand(string template, Func<PageContext, CancellationToken, Task> handler)
|
public BotPagesApp MapCommand(string template, CommandHandler handler)
|
||||||
{
|
{
|
||||||
_commands.Map(template, handler);
|
_commands.Map(template, handler, false, null);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Зарегистрировать команду с кастомным обработчиком.
|
||||||
|
/// </summary>
|
||||||
|
public BotPagesApp MapCommand(string template, CommandHandler handler, bool publish, string description)
|
||||||
|
{
|
||||||
|
_commands.Map(template, handler, publish, description);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +160,6 @@ public sealed class BotPagesApp
|
|||||||
{
|
{
|
||||||
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null)
|
if (_commands.TryDispatch(ctx, update.Text, ct, out var dispatched) && dispatched is not null)
|
||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Info, $"Command '{update.Text}' dispatched.");
|
|
||||||
await dispatched;
|
await dispatched;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -237,7 +254,7 @@ public sealed class BotPagesApp
|
|||||||
{
|
{
|
||||||
foreach (var adapter in _adapterFactory.Adapters)
|
foreach (var adapter in _adapterFactory.Adapters)
|
||||||
{
|
{
|
||||||
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), cancellationToken);
|
await adapter.Value.StartAdapterAsync(update => HandleUpdateAsync(update, cancellationToken), _commands.Commands, cancellationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,9 @@ public static class PageContextAdapterExtensions
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить текстовое сообщение.
|
/// Отправить текстовое сообщение.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Task<string?> SendTextAsync(this PageContext ctx, string text, MessageFormat format = MessageFormat.Plain,
|
public static Task<string?> SendTextAsync(this PageContext ctx,
|
||||||
|
string text,
|
||||||
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
string? messageId = null,
|
string? messageId = null,
|
||||||
@@ -21,12 +23,19 @@ public static class PageContextAdapterExtensions
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Отправить файл.
|
/// Отправить файл.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, MessageFormat? captionFormat = null, CancellationToken ct = default)
|
public static Task SendFileAsync(this PageContext ctx,
|
||||||
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
FileDescriptor file,
|
||||||
|
string? caption = null,
|
||||||
/// <summary>
|
MessageFormat? captionFormat = null,
|
||||||
/// Отправить файл.
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
/// </summary>
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
public static Task SendFileAsync(this PageContext ctx, FileDescriptor file, string? caption = null, CancellationToken ct = default)
|
CancellationToken ct = default
|
||||||
=> ctx.Adapter.SendFileAsync(ctx.Update.Chat.Id, file, caption, null, ct);
|
)
|
||||||
|
=> ctx.Adapter.SendFileAsync(chatId: ctx.Update.Chat.Id,
|
||||||
|
file: file,
|
||||||
|
caption: caption,
|
||||||
|
captionFormat: captionFormat,
|
||||||
|
inline: inline,
|
||||||
|
reply: reply,
|
||||||
|
ct: ct);
|
||||||
}
|
}
|
||||||
@@ -123,19 +123,25 @@ public sealed class MessageBuilder
|
|||||||
{
|
{
|
||||||
string? messageId = null;
|
string? messageId = null;
|
||||||
|
|
||||||
// Текст
|
|
||||||
if (!string.IsNullOrWhiteSpace(_text))
|
|
||||||
{
|
|
||||||
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;
|
||||||
|
|
||||||
|
// Текст
|
||||||
|
if (!string.IsNullOrWhiteSpace(_text))
|
||||||
|
{
|
||||||
messageId = await _ctx.SendTextAsync(_text, _format, _inline, reply, _editMessageId, ct);
|
messageId = await _ctx.SendTextAsync(_text, _format, _inline, reply, _editMessageId, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Файлы
|
// Файлы
|
||||||
foreach (var (file, caption, captionFormat) in _files)
|
foreach (var (file, caption, captionFormat) in _files)
|
||||||
await _ctx.SendFileAsync(file, caption, captionFormat, ct);
|
await _ctx.SendFileAsync(file: file
|
||||||
|
, caption: caption
|
||||||
|
, captionFormat: captionFormat
|
||||||
|
, reply: reply
|
||||||
|
, inline: _inline
|
||||||
|
, ct: ct
|
||||||
|
);
|
||||||
|
|
||||||
// Альбом
|
// Альбом
|
||||||
if (_album.Count > 0)
|
if (_album.Count > 0)
|
||||||
|
|||||||
34
BotPages.Core/Routing/Command.cs
Normal file
34
BotPages.Core/Routing/Command.cs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
namespace BotPages.Core.Routing;
|
||||||
|
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Команда действий. Например "/start"
|
||||||
|
/// </summary>
|
||||||
|
public class Command
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Название команды.
|
||||||
|
/// </summary>
|
||||||
|
public required string Name { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Шаблон команды.
|
||||||
|
/// </summary>
|
||||||
|
public required Regex Pattern { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обработчик команды.
|
||||||
|
/// </summary>
|
||||||
|
public required CommandHandler Handler { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Описание команды.
|
||||||
|
/// </summary>
|
||||||
|
public string? Description { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Публичный? нужно ли регистрировать в боте.
|
||||||
|
/// </summary>
|
||||||
|
public required bool Publish { get; init; }
|
||||||
|
}
|
||||||
12
BotPages.Core/Routing/CommandHandler.cs
Normal file
12
BotPages.Core/Routing/CommandHandler.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace BotPages.Core.Routing;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обработчик команды: получает контекст страницы, аргументы команды и токен отмены.
|
||||||
|
/// </summary>
|
||||||
|
public delegate Task CommandHandler(PageContext context, IReadOnlyDictionary<string, string>? args, CancellationToken cancellationToken);
|
||||||
@@ -2,30 +2,40 @@
|
|||||||
|
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Реестр команд, доступных из любого места.
|
/// Реестр команд, доступных из любого места.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class CommandsRegistry
|
internal sealed class CommandsRegistry
|
||||||
{
|
{
|
||||||
private readonly List<(Regex pattern, Func<PageContext, CancellationToken, Task> handler)> _commands = new();
|
private readonly List<Command> _commands = new();
|
||||||
|
|
||||||
|
public List<Command> Commands => _commands;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Зарегистрировать команду, ведущую на страницу.
|
/// Зарегистрировать команду, ведущую на страницу.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public CommandsRegistry Map<TPage>(string commandTemplate) where TPage : Page
|
public CommandsRegistry Map<TPage>(string commandTemplate, bool publish = false, string? description = null) where TPage : Page
|
||||||
{
|
{
|
||||||
var pattern = ToRegex(commandTemplate);
|
var pattern = ToRegex(commandTemplate);
|
||||||
_commands.Add((pattern, (ctx, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct)));
|
|
||||||
return this;
|
return Map(commandTemplate, (ctx, args, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct), publish, description);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Зарегистрировать команду с кастомным обработчиком.
|
/// Зарегистрировать команду с кастомным обработчиком.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public CommandsRegistry Map(string commandTemplate, Func<PageContext, CancellationToken, Task> handler)
|
public CommandsRegistry Map(string commandTemplate, CommandHandler handler, bool publish = false, string? description = null)
|
||||||
{
|
{
|
||||||
var pattern = ToRegex(commandTemplate);
|
var pattern = ToRegex(commandTemplate);
|
||||||
_commands.Add((pattern, handler));
|
_commands.Add(new Command()
|
||||||
|
{
|
||||||
|
Name = ToCommandName(commandTemplate),
|
||||||
|
Pattern = pattern,
|
||||||
|
Handler = handler,
|
||||||
|
Publish = publish,
|
||||||
|
Description = string.IsNullOrWhiteSpace(description) ? null : description
|
||||||
|
});
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,11 +44,17 @@ internal sealed class CommandsRegistry
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool TryDispatch(PageContext ctx, string command, CancellationToken ct, out Task? task)
|
public bool TryDispatch(PageContext ctx, string command, CancellationToken ct, out Task? task)
|
||||||
{
|
{
|
||||||
foreach (var (pattern, handler) in _commands)
|
foreach (var cmd in _commands)
|
||||||
{
|
{
|
||||||
if (pattern.IsMatch(command))
|
var match = cmd.Pattern.Match(command);
|
||||||
|
if (match.Success)
|
||||||
{
|
{
|
||||||
task = handler(ctx, ct);
|
// Собираем именованные группы (без числовых)
|
||||||
|
var args = cmd.Pattern.GetGroupNames()
|
||||||
|
.Where(n => !int.TryParse(n, out _))
|
||||||
|
.ToDictionary(n => n, n => match.Groups[n].Value);
|
||||||
|
|
||||||
|
task = cmd.Handler(ctx, args, ct);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,14 +62,27 @@ internal sealed class CommandsRegistry
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Универсальный парсер шаблонов: /cmd {a} {b?} {c}
|
||||||
|
/// </summary>
|
||||||
private static Regex ToRegex(string template)
|
private static Regex ToRegex(string template)
|
||||||
{
|
{
|
||||||
// Простейшее преобразование шаблона: "/open {page} {id?}" -> Regex
|
|
||||||
var escaped = Regex.Escape(template)
|
var escaped = Regex.Escape(template)
|
||||||
.Replace("\\{", "{").Replace("\\}", "}");
|
.Replace("\\{", "{").Replace("\\}", "}");
|
||||||
var pattern = "^" + escaped
|
|
||||||
.Replace("{page}", "(?<page>\\S+)")
|
var pattern = "^" + Regex.Replace(escaped, @"\{(\w+)(\?)?\}", m =>
|
||||||
.Replace("{id?}", "(?<id>\\S+)?") + "$";
|
{
|
||||||
|
var name = m.Groups[1].Value;
|
||||||
|
var optional = m.Groups[2].Success;
|
||||||
|
return optional ? $"(?<{name}>\\S+)?" : $"(?<{name}>\\S+)";
|
||||||
|
}) + "$";
|
||||||
|
|
||||||
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string ToCommandName(string template)
|
||||||
|
{
|
||||||
|
// Простейшее преобразование шаблона: "/open {page} {id?}" -> "/open"
|
||||||
|
return template.Split(" ", StringSplitOptions.RemoveEmptyEntries).First().ToLowerInvariant();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Запустить polling для приема обновлений от Telegram.
|
/// Запустить polling для приема обновлений от Telegram.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, CancellationToken ct)
|
public async Task StartAdapterAsync(Func<UpdateContext, Task> onUpdate, List<BotPages.Core.Routing.Command> commands, CancellationToken ct)
|
||||||
{
|
{
|
||||||
_client = new TelegramBotClient(_token);
|
_client = new TelegramBotClient(_token);
|
||||||
|
|
||||||
@@ -77,6 +77,7 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
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);
|
||||||
|
|
||||||
var me = await _client.GetMe();
|
var me = await _client.GetMe();
|
||||||
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
|
_logger.Log(LogLevel.Info, $"{MessengerType} started: @{me.Username}");
|
||||||
@@ -85,11 +86,12 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task<string?> SendTextAsync(string chatId, string text, MessageFormat format,
|
public async Task<string?> SendTextAsync(string chatId, string text,
|
||||||
IEnumerable<IEnumerable<InlineButton>>? inline,
|
MessageFormat format = MessageFormat.Plain,
|
||||||
IEnumerable<IEnumerable<ReplyButton>>? reply,
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
string? messageId,
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
CancellationToken ct)
|
string? messageId = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
@@ -187,7 +189,14 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public async Task SendFileAsync(string chatId, FileDescriptor file, string? caption, MessageFormat? captionFormat, CancellationToken ct)
|
public async Task SendFileAsync(string chatId,
|
||||||
|
FileDescriptor file,
|
||||||
|
string? caption = null,
|
||||||
|
MessageFormat? captionFormat = null,
|
||||||
|
IEnumerable<IEnumerable<InlineButton>>? inline = null,
|
||||||
|
IEnumerable<IEnumerable<ReplyButton>>? reply = null,
|
||||||
|
CancellationToken ct = default
|
||||||
|
)
|
||||||
{
|
{
|
||||||
if (_client is null)
|
if (_client is null)
|
||||||
{
|
{
|
||||||
@@ -249,20 +258,46 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ReplyMarkup? markup = null;
|
||||||
|
|
||||||
|
if (inline is not null && inline.Any())
|
||||||
|
{
|
||||||
|
markup = new InlineKeyboardMarkup(
|
||||||
|
inline.Select(row => row.Select(b => new InlineKeyboardButton(b.Label, b.Value)).ToArray())
|
||||||
|
.ToArray()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else if (reply is not null)
|
||||||
|
{
|
||||||
|
if (reply.Any())
|
||||||
|
{
|
||||||
|
markup = new ReplyKeyboardMarkup(
|
||||||
|
reply.Select(row => row.Select(b => new KeyboardButton(b.Label)).ToArray()).ToArray()
|
||||||
|
)
|
||||||
|
{
|
||||||
|
ResizeKeyboard = true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
markup = new ReplyKeyboardRemove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// В зависимости от FileKind выбираем подходящий метод
|
// В зависимости от FileKind выбираем подходящий метод
|
||||||
switch (file.Kind)
|
switch (file.Kind)
|
||||||
{
|
{
|
||||||
case FileKind.Photo:
|
case FileKind.Photo:
|
||||||
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
await _client.SendPhoto(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
case FileKind.Video:
|
case FileKind.Video:
|
||||||
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, cancellationToken: ct);
|
await _client.SendVideo(long.Parse(chatId), inputFile, caption: caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
case FileKind.Audio:
|
case FileKind.Audio:
|
||||||
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
await _client.SendAudio(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, cancellationToken: ct);
|
await _client.SendDocument(long.Parse(chatId), inputFile, caption ?? "", parseMode, replyMarkup: markup, cancellationToken: ct);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
{
|
{
|
||||||
_logger.Log(LogLevel.Warn, "Albums not supported. Degraded to sequential sends.");
|
_logger.Log(LogLevel.Warn, "Albums not supported. Degraded to sequential sends.");
|
||||||
foreach (var (file, caption, captionFormat) in _items)
|
foreach (var (file, caption, captionFormat) in _items)
|
||||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +95,7 @@ public sealed class TelegramAlbumBuilder : IAlbumBuilder
|
|||||||
{
|
{
|
||||||
// Telegram не поддерживает document в альбомах — деградация
|
// Telegram не поддерживает document в альбомах — деградация
|
||||||
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
|
_logger.Log(LogLevel.Warn, $"Document '{file.Kind}' in album not supported. Sending document separately.");
|
||||||
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct);
|
await _adapter.SendFileAsync(_ctx.Update.Chat.Id, file, caption, captionFormat, ct: ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,20 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||||
|
<PackageId>BotPages</PackageId>
|
||||||
|
<Version>1.0.0</Version>
|
||||||
|
<Authors>FrigaT</Authors>
|
||||||
|
<Company>FrigaT</Company>
|
||||||
|
<Product>BotPages</Product>
|
||||||
|
<Description>Платформонезависимый framework для создания диалоговых ботов с системой страниц.</Description>
|
||||||
|
<Copyright>Copyright © 2025 FrigaT</Copyright>
|
||||||
|
<RepositoryUrl>https://git.frigat.duckdns.org/FrigaT/BotPages</RepositoryUrl>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
<PackageProjectUrl>https://git.frigat.duckdns.org/FrigaT/BotPages</PackageProjectUrl>
|
||||||
|
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
|
|
||||||
@@ -7,20 +8,20 @@ namespace Demo.Pages;
|
|||||||
/// Страница ввода деталей заявки.
|
/// Страница ввода деталей заявки.
|
||||||
/// Страница с параметрами и получением состояния.
|
/// Страница с параметрами и получением состояния.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
public sealed class DetailsPage : StatefullPage<string>
|
||||||
{
|
{
|
||||||
[Statefull("Request")]
|
[Statefull("Request")]
|
||||||
private Models.Request Request;
|
private Models.Request Request;
|
||||||
|
|
||||||
public override Task OnEnter(PageContext ctx, DetailsArgs args, CancellationToken ct)
|
public override Task OnEnter(PageContext ctx, string args, CancellationToken ct)
|
||||||
{
|
{
|
||||||
Request = new()
|
Request = new()
|
||||||
{
|
{
|
||||||
Title = args.Title,
|
Title = args,
|
||||||
};
|
};
|
||||||
|
|
||||||
return new MessageBuilder(ctx)
|
return new MessageBuilder(ctx)
|
||||||
.Text($"Заголовок: {args.Title}\nДобавьте детали или нажмите Далее.")
|
.Text($"Заголовок: {args}\nДобавьте детали или нажмите Далее.")
|
||||||
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
||||||
.Reply("Отмена")
|
.Reply("Отмена")
|
||||||
.SendAsync(ct);
|
.SendAsync(ct);
|
||||||
@@ -52,12 +53,15 @@ public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
|||||||
await SaveState(ctx, ct);
|
await SaveState(ctx, ct);
|
||||||
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
internal static string Command => "/create_request {title}";
|
||||||
/// Аргументы для страницы DetailsPage.
|
internal static string CommandDescription => "создание заявки /create_request {title";
|
||||||
/// </summary>
|
internal static CommandHandler CommandHandler = async (ctx, args, ct) =>
|
||||||
public sealed class DetailsArgs
|
{
|
||||||
{
|
string? title = "";
|
||||||
public string Title { get; set; } = "";
|
args?.TryGetValue("title", out title);
|
||||||
|
|
||||||
|
// Навигация на страницу по имени
|
||||||
|
await ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, title ?? "", ct);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Abstractions;
|
using BotPages.Core.Abstractions;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
|
|
||||||
|
[Route("FileSend")]
|
||||||
public sealed class FileSendPage : SingletonPage
|
public sealed class FileSendPage : SingletonPage
|
||||||
{
|
{
|
||||||
public override Task OnEnter(PageContext ctx, CancellationToken ct)
|
public override Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ public sealed class FilesPage : SingletonPage
|
|||||||
{
|
{
|
||||||
foreach (var file in files)
|
foreach (var file in files)
|
||||||
{
|
{
|
||||||
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct);
|
await ctx.SendFileAsync(file, $"Файл '{file.Name}' получен и отправлен обратно.", ct: ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Обращение через Storage
|
//Обращение через Storage
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Abstractions;
|
using BotPages.Core.Abstractions;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -23,7 +24,7 @@ public sealed class TitlePage : SingletonPage
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return ctx.Navigation.GoToAsync<DetailsPage, DetailsArgs>(ctx, new DetailsArgs { Title = text }, ct);
|
return ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, text, ct);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Abstractions;
|
using BotPages.Core.Abstractions;
|
||||||
using BotPages.Core.Messaging;
|
using BotPages.Core.Messaging;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
|
|
||||||
namespace Demo.Pages;
|
namespace Demo.Pages;
|
||||||
|
|
||||||
@@ -8,6 +9,7 @@ namespace Demo.Pages;
|
|||||||
/// Стартовая страница демо‑бота.
|
/// Стартовая страница демо‑бота.
|
||||||
/// Обычная страница с кнопками
|
/// Обычная страница с кнопками
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[Route("Welcome")]
|
||||||
public sealed class WelcomePage : SingletonPage
|
public sealed class WelcomePage : SingletonPage
|
||||||
{
|
{
|
||||||
public override async Task OnEnter(PageContext ctx, CancellationToken ct)
|
public override async Task OnEnter(PageContext ctx, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using BotPages.Core;
|
using BotPages.Core;
|
||||||
using BotPages.Core.Logging;
|
using BotPages.Core.Logging;
|
||||||
using BotPages.Core.Middleware;
|
using BotPages.Core.Middleware;
|
||||||
|
using BotPages.Core.Routing;
|
||||||
using BotPages.Core.Storage;
|
using BotPages.Core.Storage;
|
||||||
using BotPages.Telegram;
|
using BotPages.Telegram;
|
||||||
using Demo.Pages;
|
using Demo.Pages;
|
||||||
@@ -18,9 +19,27 @@ namespace Demo
|
|||||||
var state = new InMemoryStateStorage();
|
var state = new InMemoryStateStorage();
|
||||||
using var cts = new CancellationTokenSource();
|
using var cts = new CancellationTokenSource();
|
||||||
|
|
||||||
|
// Можно использовать команды для открытия страниц с роутингом
|
||||||
|
// /open Welcome
|
||||||
|
// /open FileSend
|
||||||
|
CommandHandler openHandler = async (ctx, args, ct) =>
|
||||||
|
{
|
||||||
|
if (args is null || !args.TryGetValue("page", out var pageName))
|
||||||
|
{
|
||||||
|
await ctx.SendTextAsync("Не указана страница для открытия.", ct: ct);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Навигация на страницу по имени
|
||||||
|
await ctx.Navigation.GoToAsync(pageName, ctx, ct);
|
||||||
|
};
|
||||||
|
|
||||||
var app = new BotPagesApp(state, logger)
|
var app = new BotPagesApp(state, logger)
|
||||||
.AddDefaultPage<WelcomePage>()
|
.AddDefaultPage<WelcomePage>()
|
||||||
.MapCommand<WelcomePage>("/start")
|
.MapCommand<WelcomePage>("/start", true, "Главная")
|
||||||
|
.MapCommand("/open {page}", openHandler, true, "открыть станицу /open {page}")
|
||||||
|
.MapCommand(DetailsPage.Command, DetailsPage.CommandHandler, true, DetailsPage.CommandDescription)
|
||||||
|
.AutoMapRoute()
|
||||||
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
.AddMiddleware(new ErrorHandlingMiddleware(logger))
|
||||||
.AddMiddleware(new LoggingMiddleware(logger))
|
.AddMiddleware(new LoggingMiddleware(logger))
|
||||||
.AddTelegramAdapter(token, "Telegram")
|
.AddTelegramAdapter(token, "Telegram")
|
||||||
|
|||||||
Reference in New Issue
Block a user