Simplify subscribe command (#11)

Reviewed-on: #11
Co-authored-by: Sergey Nazarov <insight.appdev@gmail.com>
Co-committed-by: Sergey Nazarov <insight.appdev@gmail.com>
This commit is contained in:
Sergey Nazarov 2024-05-03 08:19:22 +00:00 committed by nazarovsa
parent 03b6f52488
commit 7bf91a073c
8 changed files with 70 additions and 15 deletions

View File

@ -39,4 +39,9 @@ public class NocrCallbackData : CallbackData<NocrState>
{ {
return new NocrCallbackData(NocrState.Feedback); return new NocrCallbackData(NocrState.Feedback);
} }
public static NocrCallbackData AddSubscription()
{
return new NocrCallbackData(NocrState.AddSubscription);
}
} }

View File

@ -9,6 +9,7 @@ public enum NocrState
// States // States
Start, Start,
AddSubscription,
ViewSubscription, ViewSubscription,
Feedback Feedback,
} }

View File

@ -58,6 +58,11 @@ public abstract class StartHandlerBase
{ {
var markup = new VerticalKeyboardMarkup(); var markup = new VerticalKeyboardMarkup();
markup.Add(new InlineKeyboardButton(Localizer.Get(nameof(StartHandlerBase), "AddSubscriptionButton"))
{
CallbackData = NocrCallbackData.AddSubscription().ToString()
});
markup.Add(new InlineKeyboardButton(Localizer.Get(nameof(StartHandlerBase), "SubscriptionsButton")) markup.Add(new InlineKeyboardButton(Localizer.Get(nameof(StartHandlerBase), "SubscriptionsButton"))
{ {
CallbackData = NocrCallbackData.ViewSubscription().ToString() CallbackData = NocrCallbackData.ViewSubscription().ToString()

View File

@ -0,0 +1,47 @@
using Insight.Localizer;
using Insight.TelegramBot;
using Insight.TelegramBot.Handling.Handlers;
using Insight.TelegramBot.Handling.Matchers.CallbackQueryMatchers;
using Insight.TelegramBot.Models;
using Microsoft.Extensions.Logging;
using Nocr.TelegramClient.AppServices.Bots;
using Telegram.Bot.Types;
using Telegram.Bot.Types.ReplyMarkups;
namespace Nocr.TelegramClient.AppServices.Handlers.CallbackQueries.Feedback;
public class AddSubscriptionMatcher : StateCallbackQueryMatcher<NocrState>
{
public AddSubscriptionMatcher()
{
ExpectingState = NocrState.AddSubscription;
}
}
public class AddSubscriptionHandler : IMatchingUpdateHandler<AddSubscriptionMatcher>
{
private readonly ILogger<AddSubscriptionHandler> _logger;
private readonly ILocalizer _localizer;
private readonly IBot _bot;
public AddSubscriptionHandler(ILogger<AddSubscriptionHandler> logger, ILocalizer localizer, IBot bot)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_localizer = localizer ?? throw new ArgumentNullException(nameof(localizer));
_bot = bot ?? throw new ArgumentNullException(nameof(bot));
}
public Task Handle(Update update, CancellationToken cancellationToken = default)
{
var message = new TextMessage(update.CallbackQuery.Message.Chat.Id)
{
Text = _localizer.Get(nameof(AddSubscriptionHandler), "Text"),
ReplyMarkup = new InlineKeyboardMarkup(new InlineKeyboardButton(_localizer.Get("buttons", "back"))
{
CallbackData = NocrCallbackData.Start().ToString()
})
};
return _bot.EditOrSendTextMessage(update.CallbackQuery.Message.MessageId, message, _logger, cancellationToken);
}
}

View File

@ -22,7 +22,7 @@ public class SubscribeMessageHandler : ViewSubscriptionHandlerBase, IMatchingUpd
/// For instance, "/subscribe @baraholka 1 обувь ботинки сапоги" will create match for a current user with type "All" and pattern "обувь ботинки сапоги". /// For instance, "/subscribe @baraholka 1 обувь ботинки сапоги" will create match for a current user with type "All" and pattern "обувь ботинки сапоги".
/// </summary> /// </summary>
private static Regex _commandRegex = private static Regex _commandRegex =
new Regex(@"/subscribe (.*\B@(?=\w{5,32}\b)[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)*.*) (\d{1}) (.*)", new Regex(@"^/subscribe (.*\B@(?=\w{5,32}\b)[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)*.*) (.{3,})$",
RegexOptions.Compiled); RegexOptions.Compiled);
public SubscribeMessageHandler( public SubscribeMessageHandler(
@ -38,7 +38,7 @@ public class SubscribeMessageHandler : ViewSubscriptionHandlerBase, IMatchingUpd
public async Task Handle(Update update, CancellationToken cancellationToken = default) public async Task Handle(Update update, CancellationToken cancellationToken = default)
{ {
var receiverId = update.Message.From.Id; var receiverId = update.Message.Chat.Id;
var match = _commandRegex.Match(update.Message.Text); var match = _commandRegex.Match(update.Message.Text);
if (!match.Success) if (!match.Success)
@ -51,16 +51,9 @@ public class SubscribeMessageHandler : ViewSubscriptionHandlerBase, IMatchingUpd
} }
var username = match.Groups[1].Value.TrimStart('@'); var username = match.Groups[1].Value.TrimStart('@');
if (!Enum.TryParse<TextSubscriptionRule>(match.Groups[2].Value, true, out var rule)) var template = match.Groups[2].Value;
{ // note(nazarovsa): Temporary for simplify usage
MessageQueue.Enqueue(new TextMessage(receiverId) var rule = TextSubscriptionRule.Full;
{
Text = Localizer.Get(nameof(SubscribeMessageHandler), "WrongSubscriptionType")
});
return;
}
var template = match.Groups[3].Value;
var user = await UsersService.GetOrCreate(receiverId, update.Message.From.Username, cancellationToken); var user = await UsersService.GetOrCreate(receiverId, update.Message.From.Username, cancellationToken);
var subscriptionId = await SubscriptionsController.Create(new CreateTextSubscriptionRequest var subscriptionId = await SubscriptionsController.Create(new CreateTextSubscriptionRequest

View File

@ -1,6 +1,7 @@
{ {
"Text": "Привет! Я, Nocr 🤖!", "Text": "Привет! Я, Nocr 🤖!",
"AddSubscriptionButton": "Создать подписку ",
"SubscriptionsButton": "Подписки 📩", "SubscriptionsButton": "Подписки 📩",
"FeedbackButton": "Оставить отзыв 🙋‍" "FeedbackButton": "Оставить отзыв 🙋‍"
} }

View File

@ -0,0 +1,3 @@
{
"Text": "Чтобы добавить подписку пришлите команду в формате `/subscribe @chat_username ключевое_слово`. Ключевое слово должно быть длиннее 2 символов. \n\nНапример, `/subscribe @MyGreatChannel macbook`."
}

View File

@ -25,10 +25,10 @@
}, },
"AdministrationOptions": { "AdministrationOptions": {
"FeedbackReceiverIds": [ "FeedbackReceiverIds": [
-4202454237 -1002085899956
], ],
"UpdateReceiverIds": [ "UpdateReceiverIds": [
-4202454237 -1002085899956
] ]
} }
} }