Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d60bef7070 | |||
| 7556b3d638 | |||
| 67de9e197a |
@@ -17,8 +17,6 @@ internal sealed class CommandsRegistry
|
||||
/// </summary>
|
||||
public CommandsRegistry Map<TPage>(string commandTemplate, bool publish = false, string? description = null) where TPage : Page
|
||||
{
|
||||
var pattern = ToRegex(commandTemplate);
|
||||
|
||||
return Map(commandTemplate, (ctx, args, ct) => ctx.Navigation.GoToAsync<TPage>(ctx, ct), publish, description);
|
||||
}
|
||||
|
||||
@@ -49,12 +47,10 @@ internal sealed class CommandsRegistry
|
||||
var match = cmd.Pattern.Match(command);
|
||||
if (match.Success)
|
||||
{
|
||||
// Собираем аргументы
|
||||
// Собираем именованные группы (без числовых)
|
||||
var args = cmd.Pattern.GetGroupNames()
|
||||
.Where(n => n != "0")
|
||||
.Select(n => new { n, v = match.Groups[n].Value })
|
||||
.Where(x => !string.IsNullOrEmpty(x.v))
|
||||
.ToDictionary(x => x.n, x => x.v);
|
||||
.Where(n => !int.TryParse(n, out _))
|
||||
.ToDictionary(n => n, n => match.Groups[n].Value);
|
||||
|
||||
task = cmd.Handler(ctx, args, ct);
|
||||
return true;
|
||||
@@ -64,14 +60,31 @@ internal sealed class CommandsRegistry
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Универсальный парсер шаблонов: /cmd {a} {b?} {c}
|
||||
/// </summary>
|
||||
private static Regex ToRegex(string template)
|
||||
{
|
||||
// Простейшее преобразование шаблона: "/open {page} {id?}" -> Regex
|
||||
var escaped = Regex.Escape(template)
|
||||
.Replace("\\{", "{").Replace("\\}", "}");
|
||||
var pattern = "^" + escaped
|
||||
.Replace("{page}", "(?<page>\\S+)")
|
||||
.Replace("{id?}", "(?<id>\\S+)?") + "$";
|
||||
// Заменяем все {name} и {name?} на регулярные группы
|
||||
var pattern = "^" + Regex.Replace(template, @"\s*\{(\w+)(\?)?\}", m =>
|
||||
{
|
||||
var name = m.Groups[1].Value;
|
||||
var optional = m.Groups[2].Success;
|
||||
|
||||
var argPattern = $"(?:\"(?<{name}>[^\"]+)\"|(?<{name}>\\S+))";
|
||||
|
||||
if (optional)
|
||||
{
|
||||
// необязательный параметр: пробел + значение целиком необязательны
|
||||
return $"(?:\\s+{argPattern})?";
|
||||
}
|
||||
else
|
||||
{
|
||||
// обязательный параметр: пробел обязателен
|
||||
return $"\\s+{argPattern}";
|
||||
}
|
||||
}) + "\\s*$"; // допускаем пробелы/переносы в конце
|
||||
|
||||
return new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,10 @@ public sealed class TelegramAdapter : IMessangerAdapterSetup
|
||||
var mapped = TelegramUpdateMapper.Map(MessengerType, update, _client);
|
||||
if (mapped is not null)
|
||||
await onUpdate(mapped);
|
||||
if (update.CallbackQuery is not null)
|
||||
{
|
||||
await _.AnswerCallbackQuery(update.CallbackQuery.Id);
|
||||
}
|
||||
},
|
||||
|
||||
errorHandler: async (_, ex, ct2) =>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
|
||||
@@ -7,20 +8,20 @@ namespace Demo.Pages;
|
||||
/// Страница ввода деталей заявки.
|
||||
/// Страница с параметрами и получением состояния.
|
||||
/// </summary>
|
||||
public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
||||
public sealed class DetailsPage : StatefullPage<string>
|
||||
{
|
||||
[Statefull("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()
|
||||
{
|
||||
Title = args.Title,
|
||||
Title = args,
|
||||
};
|
||||
|
||||
return new MessageBuilder(ctx)
|
||||
.Text($"Заголовок: {args.Title}\nДобавьте детали или нажмите Далее.")
|
||||
.Text($"Заголовок: {args}\nДобавьте детали или нажмите Далее.")
|
||||
.Inline(new InlineButton("Далее", "next"), new InlineButton("Назад", "back"))
|
||||
.Reply("Отмена")
|
||||
.SendAsync(ct);
|
||||
@@ -52,12 +53,15 @@ public sealed class DetailsPage : StatefullPage<DetailsArgs>
|
||||
await SaveState(ctx, ct);
|
||||
await ctx.Navigation.GoToAsync<FilesPage>(ctx, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Аргументы для страницы DetailsPage.
|
||||
/// </summary>
|
||||
public sealed class DetailsArgs
|
||||
{
|
||||
public string Title { get; set; } = "";
|
||||
internal static string Command => "/create_request {title?}";
|
||||
internal static string CommandDescription => "создание заявки /create_request {title}";
|
||||
internal static CommandHandler CommandHandler = async (ctx, args, ct) =>
|
||||
{
|
||||
string? title = "";
|
||||
args?.TryGetValue("title", out title);
|
||||
|
||||
// Навигация на страницу по имени
|
||||
await ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, title ?? "", ct);
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using BotPages.Core;
|
||||
using BotPages.Core.Abstractions;
|
||||
using BotPages.Core.Messaging;
|
||||
using BotPages.Core.Routing;
|
||||
|
||||
namespace Demo.Pages;
|
||||
/// <summary>
|
||||
@@ -23,7 +24,7 @@ public sealed class TitlePage : SingletonPage
|
||||
}
|
||||
else
|
||||
{
|
||||
return ctx.Navigation.GoToAsync<DetailsPage, DetailsArgs>(ctx, new DetailsArgs { Title = text }, ct);
|
||||
return ctx.Navigation.GoToAsync<DetailsPage, string>(ctx, text, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ namespace Demo
|
||||
.AddDefaultPage<WelcomePage>()
|
||||
.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 LoggingMiddleware(logger))
|
||||
|
||||
Reference in New Issue
Block a user