diff --git a/Examples/AspNetExample/BotController/BotHandlerOnlyStatic.cs b/Examples/AspNetExample/BotController/BotHandlerOnlyStatic.cs index a6ed5d3..af71683 100644 --- a/Examples/AspNetExample/BotController/BotHandlerOnlyStatic.cs +++ b/Examples/AspNetExample/BotController/BotHandlerOnlyStatic.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Attributes; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace AspNetExample.BotController { @@ -8,9 +7,9 @@ namespace AspNetExample.BotController public class BotHandlerOnlyStatic { [ReplyMenuHandler("TestStatic")] - public async static Task StaticTestMethod(ITelegramBotClient botClient, Update update) + public async static Task StaticTestMethod(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(StaticTestMethod)); + await PRTelegramBot.Helpers.Message.Send(context, nameof(StaticTestMethod)); } } } diff --git a/Examples/AspNetExample/BotController/BotHandlerWithDependency.cs b/Examples/AspNetExample/BotController/BotHandlerWithDependency.cs index 92875db..557cbc4 100644 --- a/Examples/AspNetExample/BotController/BotHandlerWithDependency.cs +++ b/Examples/AspNetExample/BotController/BotHandlerWithDependency.cs @@ -1,14 +1,11 @@ using AspNetExample.Services; using PRTelegramBot.Attributes; -using PRTelegramBot.Configs; +using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; -using Telegram.Bot; -using Telegram.Bot.Types; -using PRTelegramBot.Extensions; using TestDI.Models; namespace AspNetExample.BotController @@ -32,19 +29,19 @@ public BotHandlerWithDependency(ServiceScoped serviceScoped, ServiceTransient se } [ReplyMenuHandler("Test")] - public async Task TestMethodWithDependency(ITelegramBotClient botClient, Update update) + public async Task TestMethodWithDependency(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, $"{nameof(TestMethodWithDependency)} {_logger != null}"); + await PRTelegramBot.Helpers.Message.Send(context, $"{nameof(TestMethodWithDependency)} {_logger != null}"); } [SlashHandler("/test")] - public async Task Slash(ITelegramBotClient botClient, Update update) + public async Task Slash(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(Slash)); + await PRTelegramBot.Helpers.Message.Send(context, nameof(Slash)); } [ReplyMenuHandler("inline")] - public async Task InlineTest(ITelegramBotClient botClient, Update update) + public async Task InlineTest(IBotContext context) { var options = new OptionMessage(); var menuItemns = MenuGenerator.InlineButtons(1, new List { @@ -52,11 +49,11 @@ public async Task InlineTest(ITelegramBotClient botClient, Update update) new InlineCallback("TestStatic", PRTelegramBotCommand.NextPage) }); options.MenuInlineKeyboardMarkup = MenuGenerator.InlineKeyboard(menuItemns); - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(InlineTest), options); + await PRTelegramBot.Helpers.Message.Send(context, nameof(InlineTest), options); } [ReplyMenuHandler("inlinestatic")] - public async Task StaticInlineTest(ITelegramBotClient botClient, Update update) + public async Task StaticInlineTest(IBotContext context) { var options = new OptionMessage(); var menuItemns = MenuGenerator.InlineButtons(1, new List { @@ -64,19 +61,19 @@ public async Task StaticInlineTest(ITelegramBotClient botClient, Update update) new InlineCallback("TestStatic", PRTelegramBotCommand.NextPage) }); options.MenuInlineKeyboardMarkup = MenuGenerator.InlineKeyboard(menuItemns); - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(StaticInlineTest), options); + await PRTelegramBot.Helpers.Message.Send(context, nameof(StaticInlineTest), options); } [InlineCallbackHandler(PRTelegramBotCommand.CurrentPage)] - public async Task InlineHandler(ITelegramBotClient botClient, Update update) + public async Task InlineHandler(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(InlineHandler)); + await PRTelegramBot.Helpers.Message.Send(context, nameof(InlineHandler)); } [InlineCallbackHandler(PRTelegramBotCommand.NextPage)] - public async static Task InlineHandlerStatic(ITelegramBotClient botClient, Update update) + public async static Task InlineHandlerStatic(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(InlineHandlerStatic)); + await PRTelegramBot.Helpers.Message.Send(context, nameof(InlineHandlerStatic)); } /// @@ -84,42 +81,42 @@ public async static Task InlineHandlerStatic(ITelegramBotClient botClient, Updat /// Метод регистрирует следующий шаг пользователя /// [ReplyMenuHandler("stepstart")] - public async Task StepStart(ITelegramBotClient botClient, Update update) + public async Task StepStart(IBotContext context) { string msg = "Тестирование функции пошагового выполнения\nНапишите ваше имя"; //Регистрация обработчика для последовательной обработки шагов и сохранение данных - update.RegisterStepHandler(new StepTelegram(StepOne, new StepCache())); - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + context.Update.RegisterStepHandler(new StepTelegram(StepOne, new StepCache())); + await PRTelegramBot.Helpers.Message.Send(context, msg); } /// /// При написание любого текста сообщения или нажатие на любую кнопку из reply для пользователя будет выполнен этот метод. /// Метод регистрирует следующий шаг с максимальным времени выполнения /// - public async Task StepOne(ITelegramBotClient botClient, Update update) + public async Task StepOne(IBotContext context) { - string msg = $"Шаг 1 - Ваше имя {update.Message.Text}" + + string msg = $"Шаг 1 - Ваше имя {context.Update.Message.Text}" + $"\nВведите дату рождения"; //Получаем текущий обработчик - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Записываем имя пользователя в кэш - handler!.GetCache().Name = update.Message.Text; + handler!.GetCache().Name = context.Update.Message.Text; //Регистрация следующего шага с максимальным ожиданием выполнения этого шага 5 минут от момента регистрации handler.RegisterNextStep(StepTwo); - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + await PRTelegramBot.Helpers.Message.Send(context, msg); } /// /// Напишите в чат любой текст и будет выполнена эта команда если у пользователя был записан следующий шаг /// - public async Task StepTwo(ITelegramBotClient botClient, Update update) + public async Task StepTwo(IBotContext context) { - string msg = $"Шаг 2 - дата рождения {update.Message.Text}" + + string msg = $"Шаг 2 - дата рождения {context.Update.Message.Text}" + $"\nНапиши любой текст, чтобы увидеть результат"; //Получаем текущий обработчик - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Записываем дату рождения - handler!.GetCache().BirthDay = update.Message.Text; + handler!.GetCache().BirthDay = context.Update.Message.Text; //Регистрация следующего шага с максимальным ожиданием выполнения этого шага 5 минут от момента регистрации handler.RegisterNextStep(StepThree, DateTime.Now.AddMinutes(1)); //Настройки для сообщения @@ -127,24 +124,24 @@ public async Task StepTwo(ITelegramBotClient botClient, Update update) //Добавление пустого reply меню с кнопкой "Главное меню" //Функция является приоритетной, если пользователь нажмет эту кнопку будет выполнена функция главного меню, а не следующего шага. //option.MenuReplyKeyboardMarkup = MenuGenerator.ReplyKeyboard(1, new List(), true, botClient.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "RP_MAIN_MENU")); - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg, option); + await PRTelegramBot.Helpers.Message.Send(context, msg, option); } /// /// Напишите в чат любой текст и будет выполнена эта команда если у пользователя был записан следующий шаг /// - public async Task StepThree(ITelegramBotClient botClient, Update update) + public async Task StepThree(IBotContext context) { //Получение текущего обработчика - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Получение текущего кэша var cache = handler!.GetCache(); ; string msg = $"Шаг 3 - Результат: Имя:{cache.Name} дата рождения:{cache.BirthDay}" + $"\nПоследовательность шагов очищена."; //Последний шаг handler.LastStepExecuted = true; - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + await PRTelegramBot.Helpers.Message.Send(context, msg); } /// @@ -152,13 +149,13 @@ public async Task StepThree(ITelegramBotClient botClient, Update update) /// Потому что в ReplyMenuHandler значение первого аргумента установлено в true, что значит приоритетная команда /// [ReplyMenuHandler("ignorestep")] - public static async Task IngoreStep(ITelegramBotClient botClient, Update update) + public static async Task IngoreStep(IBotContext context) { - string msg = update.HasStepHandler() + string msg = context.Update.HasStepHandler() ? "Следующий шаг проигнорирован" : "Следующий шаг отсутствовал"; - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + await PRTelegramBot.Helpers.Message.Send(context, msg); } } } diff --git a/Examples/AspNetExample/BotController/BotHandlerWithoutDependency.cs b/Examples/AspNetExample/BotController/BotHandlerWithoutDependency.cs index 60425f0..033cec6 100644 --- a/Examples/AspNetExample/BotController/BotHandlerWithoutDependency.cs +++ b/Examples/AspNetExample/BotController/BotHandlerWithoutDependency.cs @@ -1,7 +1,6 @@ using PRTelegramBot.Attributes; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; -using Telegram.Bot; -using Telegram.Bot.Types; namespace AspNetExample.BotController { @@ -14,15 +13,15 @@ public BotHandlerWithoutDependency() } [ReplyMenuHandler("Testnodi")] - public async Task TestMethodWithoutDependency(ITelegramBotClient botClient, Update update) + public async Task TestMethodWithoutDependency(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, $"{nameof(TestMethodWithoutDependency)}"); + await PRTelegramBot.Helpers.Message.Send(context, $"{nameof(TestMethodWithoutDependency)}"); } [SlashHandler(CommandComparison.Equals, "/Testnodi")] - public async Task SlashNoDi(ITelegramBotClient botClient, Update update) + public async Task SlashNoDi(IBotContext context) { - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(SlashNoDi)); + await PRTelegramBot.Helpers.Message.Send(context, nameof(SlashNoDi)); } } } diff --git a/Examples/AspNetExample/BotController/BotInlineHandlerWithDependency.cs b/Examples/AspNetExample/BotController/BotInlineHandlerWithDependency.cs index b82d780..2364573 100644 --- a/Examples/AspNetExample/BotController/BotInlineHandlerWithDependency.cs +++ b/Examples/AspNetExample/BotController/BotInlineHandlerWithDependency.cs @@ -1,12 +1,10 @@ using AspNetExample.Services; using PRTelegramBot.Attributes; -using PRTelegramBot.Core; using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; -using Telegram.Bot; using Telegram.Bot.Types; using TestDI.Models; @@ -29,21 +27,21 @@ public BotInlineHandlerWithDependency(ServiceScoped serviceScoped, ServiceTransi _logger = logger; } - public async Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + public async Task Handle(IBotContext context, CallbackQuery updateType) { - await PRTelegramBot.Helpers.Message.Send(bot.botClient, update, $"{nameof(Handle)} {_logger != null}"); + await PRTelegramBot.Helpers.Message.Send(context, $"{nameof(Handle)} {_logger != null}"); return UpdateResult.Handled; } [ReplyMenuHandler("InlineClass")] - public async Task InlineTest(ITelegramBotClient botClient, Update update) + public async Task InlineTest(IBotContext context) { var options = new OptionMessage(); var menuItemns = MenuGenerator.InlineButtons(1, new List { new InlineCallback("Test", ClassTHeader.DefaultTestClass) }); options.MenuInlineKeyboardMarkup = MenuGenerator.InlineKeyboard(menuItemns); - await PRTelegramBot.Helpers.Message.Send(botClient, update, nameof(InlineTest), options); + await PRTelegramBot.Helpers.Message.Send(context, nameof(InlineTest), options); } } } diff --git a/Examples/AspNetExample/Program.cs b/Examples/AspNetExample/Program.cs index 4516789..c67f32e 100644 --- a/Examples/AspNetExample/Program.cs +++ b/Examples/AspNetExample/Program.cs @@ -74,7 +74,7 @@ async Task PrBotInstance_OnLogCommon(CommonLogEventArgs e) prBotInstance.Events.OnCommonLog += PrBotInstance_OnLogCommon; prBotInstance.Events.OnErrorLog += PrBotInstance_OnLogError; -await prBotInstance.Start(); +await prBotInstance.StartAsync(); app.Run(); diff --git a/Examples/AspNetWebHookExample/Controllers/BotController.cs b/Examples/AspNetWebHookExample/Controllers/BotController.cs index 63d4f4c..0669cd1 100644 --- a/Examples/AspNetWebHookExample/Controllers/BotController.cs +++ b/Examples/AspNetWebHookExample/Controllers/BotController.cs @@ -1,6 +1,5 @@ using AspNetWebHook.Filter; using Microsoft.AspNetCore.Mvc; -using PRTelegramBot.Configs; using PRTelegramBot.Core; using PRTelegramBot.Models.Enums; using Telegram.Bot.Types; @@ -24,7 +23,7 @@ public async Task Post([FromBody] Update update) var secretToken = bot.Options.WebHookOptions.SecretToken; if (string.Equals(secretTokenHeader, secretToken, StringComparison.Ordinal)) { - await bot.Handler.HandleUpdateAsync(bot.botClient, update, bot.Options.CancellationToken.Token); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, bot.Options.CancellationTokenSource.Token); return Ok(); } } diff --git a/Examples/AspNetWebHookExample/Filter/ValidateTelegramBotAttribute.cs b/Examples/AspNetWebHookExample/Filter/ValidateTelegramBotAttribute.cs index 0dd294c..37debf8 100644 --- a/Examples/AspNetWebHookExample/Filter/ValidateTelegramBotAttribute.cs +++ b/Examples/AspNetWebHookExample/Filter/ValidateTelegramBotAttribute.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; -using PRTelegramBot.Configs; using PRTelegramBot.Core; using PRTelegramBot.Models.Enums; diff --git a/Examples/AspNetWebHookExample/Services/BotHostedService.cs b/Examples/AspNetWebHookExample/Services/BotHostedService.cs index a8eb202..8b0bf2e 100644 --- a/Examples/AspNetWebHookExample/Services/BotHostedService.cs +++ b/Examples/AspNetWebHookExample/Services/BotHostedService.cs @@ -1,5 +1,7 @@ using PRTelegramBot.Core; +using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; namespace AspNetWebHook.Services { @@ -25,13 +27,14 @@ private async Task StartBots() { bot.Options.ServiceProvider = serviceProvider; bot.ReloadHandlers(); - await bot.Start(); + await bot.StartAsync(); if (bot.DataRetrieval == DataRetrievalMethod.WebHook) { - var webHookResult = await((PRBotWebHook)bot).GetWebHookInfo(); + var webHookResult = await((PRBotWebHook)bot) + .GetWebHookInfoAsync(bot.Options.CancellationTokenSource.Token); if (!string.IsNullOrEmpty(webHookResult.LastErrorMessage)) - bot.Events.OnErrorLogInvoke(new Exception(webHookResult.LastErrorMessage)); + bot.Events.OnErrorLogInvoke(new ErrorLogEventArgs(new BotContext(bot), new Exception(webHookResult.LastErrorMessage))); } } } @@ -41,7 +44,7 @@ public async Task StopAsync(CancellationToken cancellationToken) var bots = BotCollection.Instance.GetBots(); foreach (var bot in bots) { - await bot.Stop(); + await bot.StopAsync(); } } } diff --git a/Examples/ConsoleExample/Checkers/AdminExampleChecher.cs b/Examples/ConsoleExample/Checkers/AdminExampleChecker.cs similarity index 60% rename from Examples/ConsoleExample/Checkers/AdminExampleChecher.cs rename to Examples/ConsoleExample/Checkers/AdminExampleChecker.cs index 9167e00..984d83a 100644 --- a/Examples/ConsoleExample/Checkers/AdminExampleChecher.cs +++ b/Examples/ConsoleExample/Checkers/AdminExampleChecker.cs @@ -1,25 +1,23 @@ using ConsoleExample.Attributes; -using PRTelegramBot.Core; using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using System.Reflection; -using Telegram.Bot.Types; namespace ConsoleExample.Checkers { - internal class AdminExampleChecher : IInternalCheck + internal class AdminExampleChecker : IInternalCheck { - public async Task Check(PRBotBase bot, Update update, CommandHandler handler) + public async Task Check(IBotContext context, CommandHandler handler) { var method = handler.Method; var adminAttribute = method.GetCustomAttribute(); if(adminAttribute != null) { - var userIsAdmin = await bot.IsAdmin(update.GetChatId()); + var userIsAdmin = await context.IsAdmin(context.Update.GetChatId()); if(!userIsAdmin) - await PRTelegramBot.Helpers.Message.Send(bot.botClient, update.GetChatId(), "Вы не админ!"); + await PRTelegramBot.Helpers.Message.Send(context, "Вы не админ!"); return userIsAdmin ? InternalCheckResult.Passed : InternalCheckResult.Custom; } diff --git a/Examples/ConsoleExample/Checkers/ReplyExampleChecker.cs b/Examples/ConsoleExample/Checkers/ReplyExampleChecker.cs index 7ed4a3c..b934d03 100644 --- a/Examples/ConsoleExample/Checkers/ReplyExampleChecker.cs +++ b/Examples/ConsoleExample/Checkers/ReplyExampleChecker.cs @@ -1,14 +1,12 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; -using Telegram.Bot.Types; namespace ConsoleExample.Checkers { internal class ReplyExampleChecker : IInternalCheck { - public async Task Check(PRBotBase bot, Update update, CommandHandler handler) + public async Task Check(IBotContext context, CommandHandler handler) { // Что-то проверяем перед выполнением reply команд. // InternalCheckResult.Passed - продолжить выполнение команды, любые другие результаты остановят выполнение команды. diff --git a/Examples/ConsoleExample/Configs/telegram.json b/Examples/ConsoleExample/Configs/telegram.json index d98ee73..5158702 100644 --- a/Examples/ConsoleExample/Configs/telegram.json +++ b/Examples/ConsoleExample/Configs/telegram.json @@ -2,7 +2,7 @@ { "TelegramConfig": { // Токен для телеграм бота - "Token": "", + "Token": string.Empty, //Идентификаторы администраторов бота, //Пример Admins": [5125555, 23542352, 32452352, 34534534], "Admins": [], diff --git a/Examples/ConsoleExample/Examples/Commands/ExampleInlineCommands.cs b/Examples/ConsoleExample/Examples/Commands/ExampleInlineCommands.cs index 0da7fc5..0eaf019 100644 --- a/Examples/ConsoleExample/Examples/Commands/ExampleInlineCommands.cs +++ b/Examples/ConsoleExample/Examples/Commands/ExampleInlineCommands.cs @@ -11,7 +11,6 @@ using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; using Telegram.Bot; -using Telegram.Bot.Types; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples.Commands @@ -25,12 +24,12 @@ internal class ExampleInlineCommands /// Настройка конфигурационных файла при создание экземпляра PRBot /// [ReplyMenuHandler("InlineMenu")] - public static async Task InlineMenu(ITelegramBotClient botClient, Update update) + public static async Task InlineMenu(IBotContext context) { /* * В program.cs создается экземпляр бота: * - * var telegram = new PRBotBuilder("") + * var telegram = new PRBotBuilder(string.Empty) .AddConfigPath(ExampleConstants.BUTTONS_FILE_KEY, ".\\Configs\\buttons.json") * .Build(); * @@ -41,7 +40,7 @@ public static async Task InlineMenu(ITelegramBotClient botClient, Update update) */ /* - * botClient.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE") + * context.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE") * BotConfigJsonProvider - провайдер который работает с json файлами. * string - возращаемый тип. * ExampleConstants.BUTTONS_FILE_KEY - ключ конфига. @@ -50,10 +49,10 @@ public static async Task InlineMenu(ITelegramBotClient botClient, Update update) */ /* Создание новой кнопки с callback данными - * botClient.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE") - Название кнопки из json + * context`.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE") - Название кнопки из json * CustomTHeaderTwo.ExampleOne - Заголовок команды */ - var exampleItemOne = new InlineCallback(botClient.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE"), CustomTHeaderTwo.ExampleOne); + var exampleItemOne = new InlineCallback(context.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "IN_EXAMPLE_ONE"), CustomTHeaderTwo.ExampleOne); /* Создание новой кнопки с callback данными * InlineKeys.IN_EXAMPLE_TWO - Название кнопки из константы * CustomTHeaderTwo.ExampleTwo - Заголовок команды @@ -97,7 +96,7 @@ public static async Task InlineMenu(ITelegramBotClient botClient, Update update) option.MenuInlineKeyboardMarkup = testMenu; string msg = "Пример работы меню"; //Отправка сообщение с меню - await Helpers.Message.Send(botClient, update, msg, option); + await Helpers.Message.Send(context, msg, option); } /// @@ -105,16 +104,16 @@ public static async Task InlineMenu(ITelegramBotClient botClient, Update update) /// Обрабатывает одну точку входа /// [InlineCallbackHandler(CustomTHeaderTwo.ExampleOne)] - public static async Task Inline(ITelegramBotClient botClient, Update update) + public static async Task Inline(IBotContext context) { try { //Попытка преобразовать callback данные к требуемому типу - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); + var command = InlineCallback.GetCommandByCallbackOrNull(context.Update.CallbackQuery.Data); if (command != null) { string msg = "Выполнена команда callback"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } } catch (Exception ex) @@ -128,26 +127,26 @@ public static async Task Inline(ITelegramBotClient botClient, Update update) /// Данный метод может обработать несколько точек входа /// [InlineCallbackHandler(CustomTHeaderTwo.ExampleTwo, CustomTHeaderTwo.ExampleThree)] - public static async Task InlineTwo(ITelegramBotClient botClient, Update update) + public static async Task InlineTwo(IBotContext context) { try { //Попытка преобразовать callback данные к требуемому типу - var command = InlineCallback>.GetCommandByCallbackOrNull(update.CallbackQuery.Data); + var command = InlineCallback>.GetCommandByCallbackOrNull(context); if (command != null) { string msg = $"Идентификатор который вы передали {command.Data.EntityId}"; if (command.Data.GetActionWithLastMessage() == ActionWithLastMessage.Edit) { - await Helpers.Message.Edit(botClient, update, msg); + await Helpers.Message.Edit(context, msg); } else { if (command.Data.GetActionWithLastMessage() == ActionWithLastMessage.Delete) { - await botClient.DeleteMessage(update.GetChatIdClass(), update.CallbackQuery.Message.MessageId); + await context.BotClient.DeleteMessage(context.Update.GetChatIdClass(), context.Update.CallbackQuery.Message.MessageId); } - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } } } diff --git a/Examples/ConsoleExample/Examples/Commands/ExampleInlineConfirmation.cs b/Examples/ConsoleExample/Examples/Commands/ExampleInlineConfirmation.cs index 9c2e12c..cd228dd 100644 --- a/Examples/ConsoleExample/Examples/Commands/ExampleInlineConfirmation.cs +++ b/Examples/ConsoleExample/Examples/Commands/ExampleInlineConfirmation.cs @@ -7,8 +7,6 @@ using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Models.TCommands; using PRTelegramBot.Utils; -using Telegram.Bot; -using Telegram.Bot.Types; namespace ConsoleExample.Examples.Commands { @@ -20,7 +18,7 @@ internal class ExampleInlineConfirmation /// Так же при проверки будет проигнорирован регистр команды. /// [ReplyMenuHandler("InlineConfirm")] - public static async Task InlineConfirm(ITelegramBotClient botClient, Update update) + public static async Task InlineConfirm(IBotContext context) { //Кнопка для которой нужно создать подтверждение. var exampleInlineCallback = new InlineCallback>("Кнопка с подтверждением", CustomTHeaderTwo.ExampleThree, new EntityTCommand(3, ActionWithLastMessage.Delete)); @@ -36,14 +34,14 @@ public static async Task InlineConfirm(ITelegramBotClient botClient, Update upda option.MenuInlineKeyboardMarkup = testMenu; string msg = "InlineCallback с подтверждением"; //Отправка сообщение с меню - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg, option); + await PRTelegramBot.Helpers.Message.Send(context, msg, option); } /// /// Пример обработки inline класса. /// [ReplyMenuHandler("InlineClass")] - public static async Task InlineClass(ITelegramBotClient botClient, Update update) + public static async Task InlineClass(IBotContext context) { var exampleInlineCallback = new InlineCallback("Test1", ClassTHeader.DefaultTestClass, new StringTCommand("Test1")); var exampleInlineCallbackTwo = new InlineCallback("Test2", ClassTHeader.DefaultTestClass, new StringTCommand("Test2")); @@ -59,7 +57,7 @@ public static async Task InlineClass(ITelegramBotClient botClient, Update update string msg = "InlineClass"; //Отправка сообщение с меню - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg, option); + await PRTelegramBot.Helpers.Message.Send(context, msg, option); } /// @@ -69,7 +67,7 @@ public static async Task InlineClass(ITelegramBotClient botClient, Update update /// [ReplyMenuHandler("InlineConfirmWithBack")] [InlineCallbackHandler(CustomTHeaderTwo.ExampleBack)] - public static async Task InlineConfirmWithBack(ITelegramBotClient botClient, Update update) + public static async Task InlineConfirmWithBack(IBotContext context) { //Кнопка для которой нужно создать подтверждение. var exampleInlineCallback = new InlineCallback>("Кнопка с подтвержением", CustomTHeaderTwo.ExampleThree, new EntityTCommand(3, ActionWithLastMessage.Delete)); @@ -88,10 +86,10 @@ public static async Task InlineConfirmWithBack(ITelegramBotClient botClient, Upd option.MenuInlineKeyboardMarkup = testMenu; string msg = "InlineCallback с подтверждением и обработкой кнопки назад или кастомной"; //Отправка сообщение с меню - if (update.Type == Telegram.Bot.Types.Enums.UpdateType.CallbackQuery) - await PRTelegramBot.Helpers.Message.Edit(botClient, update, msg, option); + if (context.Update.Type == Telegram.Bot.Types.Enums.UpdateType.CallbackQuery) + await PRTelegramBot.Helpers.Message.Edit(context, msg, option); else - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg, option); + await PRTelegramBot.Helpers.Message.Send(context, msg, option); } } } diff --git a/Examples/ConsoleExample/Examples/Commands/ExampleReplyCommands.cs b/Examples/ConsoleExample/Examples/Commands/ExampleReplyCommands.cs index 4647ce1..359906e 100644 --- a/Examples/ConsoleExample/Examples/Commands/ExampleReplyCommands.cs +++ b/Examples/ConsoleExample/Examples/Commands/ExampleReplyCommands.cs @@ -2,13 +2,13 @@ using ConsoleExample.Models; using PRTelegramBot.Attributes; using PRTelegramBot.Configs; +using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Utils; -using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; -using PRTelegramBot.Extensions; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples.Commands @@ -23,10 +23,10 @@ internal class ExampleReplyCommands /// Так же при проверки будет проигнорирован регистр команды. /// [ReplyMenuHandler(CommandComparison.Contains, StringComparison.OrdinalIgnoreCase, "Команда содержит текст")] - public static async Task ReplyExampleOne(ITelegramBotClient botClient, Update update) + public static async Task ReplyExampleOne(IBotContext context) { string msg = nameof(ReplyExampleOne); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -34,10 +34,10 @@ public static async Task ReplyExampleOne(ITelegramBotClient botClient, Update up /// Команда отработает если 'Точное совпадение команды' будет точное совпадения текста сообщения за исключением регистра. /// [ReplyMenuHandler("Точное совпадение команды")] - public static async Task ReplyExampleTwo(ITelegramBotClient botClient, Update update) + public static async Task ReplyExampleTwo(IBotContext context) { string msg = nameof(ReplyExampleTwo); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -46,10 +46,10 @@ public static async Task ReplyExampleTwo(ITelegramBotClient botClient, Update up /// Пример с использованием разных reply команд для работы с 1 функцией. /// [ReplyMenuHandler("Пример 1", "Пример 2")] - public static async Task ExampleReplyMany(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyMany(IBotContext context) { string msg = nameof(ExampleReplyMany); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -58,7 +58,7 @@ public static async Task ExampleReplyMany(ITelegramBotClient botClient, Update u /// В результате сгенерируется меню. /// [ReplyMenuHandler("Reply Меню")] - public static async Task ExampleReplyMenu(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyMenu(IBotContext context) { string msg = "Меню"; //Создаем настройки сообщения @@ -85,7 +85,7 @@ public static async Task ExampleReplyMenu(ITelegramBotClient botClient, Update u var menu = MenuGenerator.ReplyKeyboard(1, menuList, true, "Главное меню"); //Добавляем в настройки меню option.MenuReplyKeyboardMarkup = menu; - await Helpers.Message.Send(botClient, update, msg, option); + await Helpers.Message.Send(context, msg, option); } /// @@ -95,12 +95,12 @@ public static async Task ExampleReplyMenu(ITelegramBotClient botClient, Update u /// Настройка конфигурационных файла при создание экземпляра PRBot /// [ReplyMenuHandler("Пример динамического текста сообщения")] - public static async Task ExampleDynamicReply(ITelegramBotClient botClient, Update update) + public static async Task ExampleDynamicReply(IBotContext context) { /* * В program.cs создается экземпляр бота: * - * var telegram = new PRBotBuilder("") + * var telegram = new PRBotBuilder(string.Empty) * .AddConfigPath(ExampleConstants.MESSAGES_FILE_KEY, ".\\Configs\\messages.json") * .Build(); * @@ -120,8 +120,8 @@ public static async Task ExampleDynamicReply(ITelegramBotClient botClient, Updat */ // Получаем текст сообщения по ключу из json файла. - string msg = botClient.GetConfigValue(ExampleConstants.MESSAGES_FILE_KEY, "MSG_EXAMPLE_TEXT"); - await Helpers.Message.Send(botClient, update, msg); + string msg = context.GetConfigValue(ExampleConstants.MESSAGES_FILE_KEY, "MSG_EXAMPLE_TEXT"); + await Helpers.Message.Send(context, msg); } /// @@ -130,7 +130,7 @@ public static async Task ExampleDynamicReply(ITelegramBotClient botClient, Updat /// Пример работы меню со скобками. /// [ReplyMenuHandler("Скобки")] - public static async Task ExampleBracket(ITelegramBotClient botClient, Update update) + public static async Task ExampleBracket(IBotContext context) { string msg = $"Значени {count}"; //Создаем настройки сообщения @@ -144,7 +144,7 @@ public static async Task ExampleBracket(ITelegramBotClient botClient, Update upd var menu = MenuGenerator.ReplyKeyboard(1, menuList, true, "Главное меню"); //Добавляем в настройки меню option.MenuReplyKeyboardMarkup = menu; - await Helpers.Message.Send(botClient, update, msg, option); + await Helpers.Message.Send(context, msg, option); count++; } @@ -155,10 +155,10 @@ public static async Task ExampleBracket(ITelegramBotClient botClient, Update upd /// [Access((int)(UserPrivilege.Guest | UserPrivilege.Registered))] [ReplyMenuHandler("Проверка доступа")] - public static async Task ExampleAccess(ITelegramBotClient botClient, Update update) + public static async Task ExampleAccess(IBotContext context) { string msg = nameof(ExampleAccess); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -168,7 +168,7 @@ public static async Task ExampleAccess(ITelegramBotClient botClient, Update upda /// "DYNAMIC_COMMANT_EXAMPLE": "Динамическая команда" /// [ReplyMenuDynamicHandler(nameof(ExampleConstants.DYNAMIC_COMMANT_EXAMPLE))] - public static async Task ExampleReplyDynamicCommand(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyDynamicCommand(IBotContext context) { /* * Создание провайдера работы с json файлом commands.json @@ -177,7 +177,7 @@ public static async Task ExampleReplyDynamicCommand(ITelegramBotClient botClient * Выгрузка всех команд в формате ключ:значение * var dynamicCommands = botJsonProvider.GetKeysAndValues(); * - * var telegram = new PRBotBuilder("") + * var telegram = new PRBotBuilder(string.Empty) * .AddReplyDynamicCommands(dynamicCommands) * .Build(); * @@ -187,7 +187,7 @@ public static async Task ExampleReplyDynamicCommand(ITelegramBotClient botClient */ string msg = nameof(ExampleReplyDynamicCommand); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -196,10 +196,10 @@ public static async Task ExampleReplyDynamicCommand(ITelegramBotClient botClient /// [ReplyMenuHandler("Приватная команда")] [RequiredTypeChat(Telegram.Bot.Types.Enums.ChatType.Private)] - public static async Task ExampleReplyRequeretPrivate(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyRequeretPrivate(IBotContext context) { string msg = nameof(ExampleReplyRequeretPrivate); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -208,10 +208,10 @@ public static async Task ExampleReplyRequeretPrivate(ITelegramBotClient botClien /// [ReplyMenuHandler("Сообщение только из текста")] [RequireTypeMessage(Telegram.Bot.Types.Enums.MessageType.Text)] - public static async Task ExampleReplyRequiredText(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyRequiredText(IBotContext context) { string msg = nameof(ExampleReplyRequiredText); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -220,10 +220,10 @@ public static async Task ExampleReplyRequiredText(ITelegramBotClient botClient, /// Пример работы с текстом из json файла. /// [ReplyMenuHandler(1, "Пример команды для бота id 1")] - public static async Task ExampleReplyBotIdOne(ITelegramBotClient botClient, Update update) + public static async Task ExampleReplyBotIdOne(IBotContext context) { string msg = nameof(ExampleReplyBotIdOne); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -231,10 +231,25 @@ public static async Task ExampleReplyBotIdOne(ITelegramBotClient botClient, Upda /// Команда отработает при написание в чат "Команда для всех ботов". /// [ReplyMenuHandler(-1, "Команда для всех ботов")] - public static async Task ReplyExampleAllBots(ITelegramBotClient botClient, Update update) + public static async Task ReplyExampleAllBots(IBotContext context) { string msg = nameof(ReplyExampleAllBots); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); + } + + /// + /// Reply команда которая задерживает обработку update. + /// + [ReplyMenuHandler("Block10")] + public static async Task ReplyBlockUpdate(IBotContext context) + { + string msg = nameof(ReplyBlockUpdate); + await Helpers.Message.Send(context, msg); + + await Task.Delay(10000); + + await Helpers.Message.Send(context, "Конец ожидания"); } + } } diff --git a/Examples/ConsoleExample/Examples/Commands/ExampleSlashCommands.cs b/Examples/ConsoleExample/Examples/Commands/ExampleSlashCommands.cs index 464ea9e..1979448 100644 --- a/Examples/ConsoleExample/Examples/Commands/ExampleSlashCommands.cs +++ b/Examples/ConsoleExample/Examples/Commands/ExampleSlashCommands.cs @@ -1,7 +1,6 @@ using PRTelegramBot.Attributes; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; -using Telegram.Bot; -using Telegram.Bot.Types; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples.Commands @@ -13,14 +12,14 @@ internal class ExampleSlashCommands /// Команда отработает при написание в чат "/example". /// [SlashHandler("/example")] - public static async Task ExampleSlashCommand(ITelegramBotClient botClient, Update update) + public static async Task ExampleSlashCommand(IBotContext context) { string msg = $"Команда /example"; msg += "\n /get_1 - команда 1" + "\n /get_2 - команда 2" + "\n /get_3 - команда 3" + "\n /get_4 - команда 4"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -29,26 +28,26 @@ public static async Task ExampleSlashCommand(ITelegramBotClient botClient, Updat /// Команда отработает при написание в чат "/get_1", значение 1 можно обработать. /// [SlashHandler("/get")] - public static async Task ExampleSlashCommandGet(ITelegramBotClient botClient, Update update) + public static async Task ExampleSlashCommandGet(IBotContext context) { - if (update.Message.Text.Contains("_")) + if (context.Update.Message.Text.Contains("_")) { - var spl = update.Message.Text.Split("_"); + var spl = context.Update.Message.Text.Split("_"); if (spl.Length > 1) { string msg = $"Команда /get со значением {spl[1]}"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } else { string msg = $"Команда /get"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } } else { string msg = $"Команда /get"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } } @@ -58,10 +57,10 @@ public static async Task ExampleSlashCommandGet(ITelegramBotClient botClient, Up /// /equals_1 не сработает. /// [SlashHandler(CommandComparison.Equals, "/equals")] - public static async Task ExampleSlashEqualsCommand(ITelegramBotClient botClient, Update update) + public static async Task ExampleSlashEqualsCommand(IBotContext context) { string msg = nameof(ExampleSlashEqualsCommand); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -70,10 +69,10 @@ public static async Task ExampleSlashEqualsCommand(ITelegramBotClient botClient, /// Не сработает/equals_1, /equalsreG, /Equalsreg. /// [SlashHandler(CommandComparison.Equals, StringComparison.Ordinal, "/equalsreg")] - public static async Task ExampleSlashEqualsRegisterCommand(ITelegramBotClient botClient, Update update) + public static async Task ExampleSlashEqualsRegisterCommand(IBotContext context) { string msg = nameof(ExampleSlashEqualsRegisterCommand); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } } } diff --git a/Examples/ConsoleExample/Examples/Commands/ExampleStepCommand.cs b/Examples/ConsoleExample/Examples/Commands/ExampleStepCommand.cs index 8b7f4b9..23606a5 100644 --- a/Examples/ConsoleExample/Examples/Commands/ExampleStepCommand.cs +++ b/Examples/ConsoleExample/Examples/Commands/ExampleStepCommand.cs @@ -3,11 +3,10 @@ using PRTelegramBot.Attributes; using PRTelegramBot.Configs; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; -using Telegram.Bot; -using Telegram.Bot.Types; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples.Commands @@ -22,67 +21,67 @@ public class ExampleStepCommand /// Метод регистрирует следующий шаг пользователя /// [ReplyMenuHandler("stepstart")] - public static async Task StepStart(ITelegramBotClient botClient, Update update) + public static async Task StepStart(IBotContext context) { string msg = "Тестирование функции пошагового выполнения\nНапишите ваше имя"; //Регистрация обработчика для последовательной обработки шагов и сохранение данных - update.RegisterStepHandler(new StepTelegram(StepOne, new StepCache())); - await Helpers.Message.Send(botClient, update, msg); + context.Update.RegisterStepHandler(new StepTelegram(StepOne, new StepCache())); + await Helpers.Message.Send(context, msg); } /// /// При написание любого текста сообщения или нажатие на любую кнопку из reply для пользователя будет выполнен этот метод. /// Метод регистрирует следующий шаг с максимальным времени выполнения /// - public static async Task StepOne(ITelegramBotClient botClient, Update update) + public static async Task StepOne(IBotContext context) { - string msg = $"Шаг 1 - Ваше имя {update.Message.Text}" + + string msg = $"Шаг 1 - Ваше имя {context.Update.Message.Text}" + $"\nВведите дату рождения"; //Получаем текущий обработчик - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Записываем имя пользователя в кэш - handler!.GetCache().Name = update.Message.Text; + handler!.GetCache().Name = context.Update.Message.Text; //Регистрация следующего шага с максимальным ожиданием выполнения этого шага 5 минут от момента регистрации handler.RegisterNextStep(StepTwo); - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// /// Напишите в чат любой текст и будет выполнена эта команда если у пользователя был записан следующий шаг /// - public static async Task StepTwo(ITelegramBotClient botClient, Update update) + public static async Task StepTwo(IBotContext context) { - string msg = $"Шаг 2 - дата рождения {update.Message.Text}" + + string msg = $"Шаг 2 - дата рождения {context.Update.Message.Text}" + $"\nНапиши любой текст, чтобы увидеть результат"; //Получаем текущий обработчик - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Записываем дату рождения - handler!.GetCache().BirthDay = update.Message.Text; + handler!.GetCache().BirthDay = context.Update.Message.Text; //Регистрация следующего шага с максимальным ожиданием выполнения этого шага 5 минут от момента регистрации handler.RegisterNextStep(StepThree, DateTime.Now.AddMinutes(1)); //Настройки для сообщения var option = new OptionMessage(); //Добавление пустого reply меню с кнопкой "Главное меню" //Функция является приоритетной, если пользователь нажмет эту кнопку будет выполнена функция главного меню, а не следующего шага. - option.MenuReplyKeyboardMarkup = MenuGenerator.ReplyKeyboard(1, new List(), true, botClient.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "RP_MAIN_MENU")); - await Helpers.Message.Send(botClient, update, msg, option); + option.MenuReplyKeyboardMarkup = MenuGenerator.ReplyKeyboard(1, new List(), true, context.GetConfigValue(ExampleConstants.BUTTONS_FILE_KEY, "RP_MAIN_MENU")); + await Helpers.Message.Send(context, msg, option); } /// /// Напишите в чат любой текст и будет выполнена эта команда если у пользователя был записан следующий шаг /// - public static async Task StepThree(ITelegramBotClient botClient, Update update) + public static async Task StepThree(IBotContext context) { //Получение текущего обработчика - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Получение текущего кэша var cache = handler!.GetCache(); ; string msg = $"Шаг 3 - Результат: Имя:{cache.Name} дата рождения:{cache.BirthDay}" + $"\nПоследовательность шагов очищена."; //Последний шаг handler.LastStepExecuted = true; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -90,28 +89,28 @@ public static async Task StepThree(ITelegramBotClient botClient, Update update) /// Потому что в ReplyMenuHandler значение первого аргумента установлено в true, что значит приоритетная команда /// [ReplyMenuHandler("ignorestep")] - public static async Task IngoreStep(ITelegramBotClient botClient, Update update) + public static async Task IngoreStep(IBotContext context) { - string msg = update.HasStepHandler() + string msg = context.Update.HasStepHandler() ? "Следующий шаг проигнорирован" : "Следующий шаг отсутствовал"; - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } [InlineCallbackHandler(CustomTHeader.InlineWithStep)] - public static async Task InlineStepp(ITelegramBotClient botClient, Update update) + public static async Task InlineStepp(IBotContext context) { try { //Попытка преобразовать callback данные к требуемому типу - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); + var command = InlineCallback.GetCommandByCallbackOrNull(context.Update.CallbackQuery.Data); if (command != null) { string msg = "Регистрация следующего шага, напишите что-нибудь"; - await Helpers.Message.Send(botClient, update, msg); - update.RegisterStepHandler(new StepTelegram(InlineStep, new StepCache())); + await Helpers.Message.Send(context, msg); + context.Update.RegisterStepHandler(new StepTelegram(InlineStep, new StepCache())); } } catch (Exception ex) @@ -120,17 +119,17 @@ public static async Task InlineStepp(ITelegramBotClient botClient, Update update } } - public static async Task InlineStep(ITelegramBotClient botClient, Update update) + public static async Task InlineStep(IBotContext context) { - string msg = $"Вы ввели данные {update.Message.Text}"; + string msg = $"Вы ввели данные {context.Update.Message.Text}"; //Получаем текущий обработчик - var handler = update.GetStepHandler(); + var handler = context.Update.GetStepHandler(); //Записываем имя пользователя в кэш - handler!.GetCache().Name = update.Message.Text; + handler!.GetCache().Name = context.Update.Message.Text; //Регистрация следующего шага с максимальным ожиданием выполнения этого шага 5 минут от момента регистрации - update.ClearStepUserHandler(); - await Helpers.Message.Send(botClient, update, msg); - await ExampleCalendar.PickCalendar(botClient, update); + context.Update.ClearStepUserHandler(); + await Helpers.Message.Send(context, msg); + await ExampleCalendar.PickCalendar(context); } } } diff --git a/Examples/ConsoleExample/Examples/Events/ExampleEvents.cs b/Examples/ConsoleExample/Examples/Events/ExampleEvents.cs index 3598e86..1ec9883 100644 --- a/Examples/ConsoleExample/Examples/Events/ExampleEvents.cs +++ b/Examples/ConsoleExample/Examples/Events/ExampleEvents.cs @@ -10,19 +10,19 @@ public static class ExampleEvents public static async Task OnWrongTypeChat(BotEventArgs e) { string msg = "Неверный тип чата"; - await Helpers.Message.Send(e.BotClient, e.Update, msg); + await Helpers.Message.Send(e.Context, msg); } public static async Task OnMissingCommand(BotEventArgs args) { string msg = "Не найдена команда"; - await Helpers.Message.Send(args.BotClient, args.Update, msg); + await Helpers.Message.Send(args.Context, msg); } public static async Task OnErrorCommand(BotEventArgs args) { string msg = "Произошла ошибка при обработке команды"; - await Helpers.Message.Send(args.BotClient, args.Update, msg); + await Helpers.Message.Send(args.Context, msg); } /// @@ -36,7 +36,7 @@ public static async Task OnCheckPrivilege(PrivilegeEventArgs e) if (!e.Mask.HasValue) { // Нет маски доступа, выполняем метод. - await e.ExecuteMethod(e.BotClient, e.Update); + await e.ExecuteMethod(e.Context); return; } @@ -45,18 +45,18 @@ public static async Task OnCheckPrivilege(PrivilegeEventArgs e) // Получаем флаги доступа пользователя. // Здесь вы на свое усмотрение реализываете логику получение флагов, например можно из базы данных получить. - var userFlags = e.Update.LoadExampleFlagPrivilege(); + var userFlags = e.Context.Update.LoadExampleFlagPrivilege(); if (requiredAccess.HasFlag(userFlags)) { // Доступ есть, выполняем метод. - await e.ExecuteMethod(e.BotClient, e.Update); + await e.ExecuteMethod(e.Context); return; } // Доступа нет. string errorMsg = "У вас нет доступа к данной функции"; - await Helpers.Message.Send(e.BotClient, e.Update, errorMsg); + await Helpers.Message.Send(e.Context, errorMsg); return; } @@ -64,12 +64,12 @@ public static async Task OnCheckPrivilege(PrivilegeEventArgs e) public static async Task OnUserStartWithArgs(StartEventArgs args) { string msg = "Пользователь отправил старт с аргументом"; - await Helpers.Message.Send(args.BotClient, args.Update, msg); + await Helpers.Message.Send(args.Context, msg); } public static async Task OnWrongTypeMessage(BotEventArgs e) { string msg = "Неверный тип сообщения"; - await Helpers.Message.Send(e.BotClient, e.Update, msg); + await Helpers.Message.Send(e.Context, msg); } } } diff --git a/Examples/ConsoleExample/Examples/Events/ExampleLogEvents.cs b/Examples/ConsoleExample/Examples/Events/ExampleLogEvents.cs index de907a3..9b86e18 100644 --- a/Examples/ConsoleExample/Examples/Events/ExampleLogEvents.cs +++ b/Examples/ConsoleExample/Examples/Events/ExampleLogEvents.cs @@ -4,18 +4,20 @@ namespace ConsoleExample.Examples.Events { internal static class ExampleLogEvents { - public static async Task OnLogError(ErrorLogEventArgs e) + public static Task OnLogError(ErrorLogEventArgs e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{DateTime.Now}: {e.Exception}"); Console.ResetColor(); + return Task.CompletedTask; } - public static async Task OnLogCommon(CommonLogEventArgs e) + public static Task OnLogCommon(CommonLogEventArgs e) { Console.ForegroundColor = e.Color; Console.WriteLine($"{DateTime.Now}: {e.Message}"); Console.ResetColor(); + return Task.CompletedTask; } } } diff --git a/Examples/ConsoleExample/Examples/Events/ExampleMessageEvents.cs b/Examples/ConsoleExample/Examples/Events/ExampleMessageEvents.cs index 93753b3..d81ba30 100644 --- a/Examples/ConsoleExample/Examples/Events/ExampleMessageEvents.cs +++ b/Examples/ConsoleExample/Examples/Events/ExampleMessageEvents.cs @@ -6,25 +6,25 @@ public static class ExampleMessageEvents { public static async Task OnDiceHandle(BotEventArgs e) { - var dice = e.Update.Message.Dice; + var dice = e.Context.Update.Message.Dice; //Обработка данных } public static async Task OnVideoNoteHandle(BotEventArgs e) { - var videonote = e.Update.Message.VideoNote; + var videonote = e.Context.Update.Message.VideoNote; //Обработка данных } public static async Task OnGameHandle(BotEventArgs e) { - var game = e.Update.Message.Game; + var game = e.Context.Update.Message.Game; //Обработка данных } public static async Task OnVenueHandle(BotEventArgs e) { - var venue = e.Update.Message.Venue; + var venue = e.Context.Update.Message.Venue; //Обработка данных } @@ -35,37 +35,37 @@ public static async Task OnUnknownHandle(BotEventArgs e) public static async Task OnVoiceHandle(BotEventArgs e) { - var voice = e.Update.Message.Voice; + var voice = e.Context.Update.Message.Voice; //Обработка данных } public static async Task OnStickerHandle(BotEventArgs e) { - var sticker = e.Update.Message.Sticker; + var sticker = e.Context.Update.Message.Sticker; //Обработка данных } public static async Task OnPhotoHandle(BotEventArgs e) { - var photo = e.Update.Message.Photo; + var photo = e.Context.Update.Message.Photo; //Обработка данных } public static async Task OnVideoHandle(BotEventArgs e) { - var video = e.Update.Message.Video; + var video = e.Context.Update.Message.Video; //Обработка данных } public static async Task OnAudioHandle(BotEventArgs e) { - var audio = e.Update.Message.Audio; + var audio = e.Context.Update.Message.Audio; //Обработка данных } public static async Task OnDocumentHandle(BotEventArgs e) { - var document = e.Update.Message.Document; + var document = e.Context.Update.Message.Document; //Обработка данных } @@ -76,25 +76,25 @@ public static async Task OnAccessDenied(BotEventArgs e) public static async Task OnWebAppsHandle(BotEventArgs e) { - var webApp = e.Update.Message.WebAppData; + var webApp = e.Context.Update.Message.WebAppData; //Обработка данных } public static async Task OnPollHandle(BotEventArgs e) { - var poll = e.Update.Message.Poll; + var poll = e.Context.Update.Message.Poll; //Обработка данных } public static async Task OnContactHandle(BotEventArgs e) { - var contact = e.Update.Message.Contact; + var contact = e.Context.Update.Message.Contact; //Обработка данных } public static async Task OnLocationHandle(BotEventArgs e) { - var location = e.Update.Message.Location; + var location = e.Context.Update.Message.Location; //Обработка данных } } diff --git a/Examples/ConsoleExample/Examples/Events/ExampleUpdateEvents.cs b/Examples/ConsoleExample/Examples/Events/ExampleUpdateEvents.cs index bf1afbd..f8fc4d6 100644 --- a/Examples/ConsoleExample/Examples/Events/ExampleUpdateEvents.cs +++ b/Examples/ConsoleExample/Examples/Events/ExampleUpdateEvents.cs @@ -9,14 +9,14 @@ public static class ExampleUpdateEvents public static async Task OnUpdateMyChatMember(BotEventArgs args) { //Обработка информации из myChatHandle - var myChatHandle = args.Update.MyChatMember; + var myChatHandle = args.Context.Update.MyChatMember; try { if (myChatHandle.NewChatMember.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Member) { - if (myChatHandle.NewChatMember.User.Id == args.BotClient.BotId) + if (myChatHandle.NewChatMember.User.Id == args.Context.BotClient.BotId) { - await Helpers.Message.Send(args.BotClient, myChatHandle.Chat.Id, "Hello world"); + await Helpers.Message.Send(args.Context, "Hello world"); } else { @@ -26,7 +26,7 @@ public static async Task OnUpdateMyChatMember(BotEventArgs args) } catch (Exception ex) { - args.Bot.Events.OnErrorLogInvoke(ex); + args.Context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(args.Context, ex)); } } diff --git a/Examples/ConsoleExample/Examples/ExampleAdminCheck.cs b/Examples/ConsoleExample/Examples/ExampleAdminCheck.cs index 0a180d2..fb46d71 100644 --- a/Examples/ConsoleExample/Examples/ExampleAdminCheck.cs +++ b/Examples/ConsoleExample/Examples/ExampleAdminCheck.cs @@ -1,8 +1,7 @@ using ConsoleExample.Attributes; using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace ConsoleExample.Examples { @@ -14,11 +13,11 @@ public class ExampleAdminCheck /// Проверка текущего пользователя на привилегии администратора. /// [ReplyMenuHandler("Админ")] - public static async Task AdminExample(ITelegramBotClient botClient, Update update) + public static async Task AdminExample(IBotContext context) { - bool isAdminUpdate = await botClient.IsAdmin(update); - bool isAdminById = await botClient.IsAdmin(update.GetChatId()) ; - await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Вы администратор бота: {isAdminById} {isAdminUpdate}"); + bool isAdminUpdate = await context.IsAdmin(); + bool isAdminById = await context.IsAdmin(context.Update.GetChatId()) ; + await PRTelegramBot.Helpers.Message.Send(context, $"Вы администратор бота: {isAdminById} {isAdminUpdate}"); } @@ -29,11 +28,11 @@ public static async Task AdminExample(ITelegramBotClient botClient, Update updat /// [AdminOnlyExample] [ReplyMenuHandler("Только админы")] - public static async Task AdminOnlyExample(ITelegramBotClient botClient, Update update) + public static async Task AdminOnlyExample(IBotContext context) { - bool isAdminUpdate = await botClient.IsAdmin(update); - bool isAdminById = await botClient.IsAdmin(update.GetChatId()); - await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Вы администратор бота: {isAdminById} {isAdminUpdate}"); + bool isAdminUpdate = await context.IsAdmin(); + bool isAdminById = await context.IsAdmin(context.Update.GetChatId()); + await PRTelegramBot.Helpers.Message.Send(context, $"Вы администратор бота: {isAdminById} {isAdminUpdate}"); } } } diff --git a/Examples/ConsoleExample/Examples/ExampleCalendar.cs b/Examples/ConsoleExample/Examples/ExampleCalendar.cs index 30bb092..d3beaa0 100644 --- a/Examples/ConsoleExample/Examples/ExampleCalendar.cs +++ b/Examples/ConsoleExample/Examples/ExampleCalendar.cs @@ -1,12 +1,11 @@ using ConsoleExample.Models.CommandHeaders; using PRTelegramBot.Attributes; -using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.CallbackCommands; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; using System.Globalization; -using Telegram.Bot; -using Telegram.Bot.Types; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples @@ -18,11 +17,11 @@ public class ExampleCalendar /// Вызов команды календаря /// [ReplyMenuHandler("Calendar")] - public static async Task PickCalendar(ITelegramBotClient botClient, Update update) + public static async Task PickCalendar(IBotContext context) { try { - await CalendarUtils.Create(botClient, update, CustomTHeader.CalendarCallback, "Выберите дату:"); + await CalendarUtils.Create(context, CustomTHeader.CalendarCallback, "Выберите дату:"); } catch (Exception ex) { @@ -35,11 +34,11 @@ public static async Task PickCalendar(ITelegramBotClient botClient, Update updat /// Вызов команды календаря на английском языке /// [ReplyMenuHandler("EngCalendar")] - public static async Task EngPickCalendar(ITelegramBotClient botClient, Update update) + public static async Task EngPickCalendar(IBotContext context) { try { - await CalendarUtils.Create(botClient, update, CultureInfo.GetCultureInfo("en-US", false), CustomTHeader.CalendarCallback, "Choose date:"); + await CalendarUtils.Create(context, CultureInfo.GetCultureInfo("en-US", false), CustomTHeader.CalendarCallback, "Choose date:"); } catch (Exception ex) { @@ -51,20 +50,20 @@ public static async Task EngPickCalendar(ITelegramBotClient botClient, Update up /// Обработка выбраной даты /// [InlineCallbackHandler(CustomTHeader.CalendarCallback)] - public static async Task PickDate(ITelegramBotClient botClient, Update update) + public static async Task PickDate(IBotContext context) { - var bot = botClient.GetBotDataOrNull(); + var bot = context.Current; try { - using (var inlineHandler = new InlineCallback(botClient, update)) + using (var inlineHandler = new InlineCallback(context)) { var command = inlineHandler.GetCommandByCallbackOrNull(); - await Helpers.Message.Send(botClient, update, command.Data.Date.ToString()); + await Helpers.Message.Send(context, command.Data.Date.ToString()); } } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); } } } diff --git a/Examples/ConsoleExample/Examples/ExamplePage.cs b/Examples/ConsoleExample/Examples/ExamplePage.cs index 1826bb2..a776553 100644 --- a/Examples/ConsoleExample/Examples/ExamplePage.cs +++ b/Examples/ConsoleExample/Examples/ExamplePage.cs @@ -1,12 +1,12 @@ using ConsoleExample.Models.CommandHeaders; using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.CallbackCommands; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; -using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; using Helpers = PRTelegramBot.Helpers; @@ -39,7 +39,7 @@ public class ExamplePage /// Напишите в чате "pages" /// [ReplyMenuHandler("pages")] - public static async Task ExamplePages(ITelegramBotClient botClient, Update update) + public static async Task ExamplePages(IBotContext context) { //Беру текст для первого сообщения string msg = pageData[0]; @@ -49,14 +49,14 @@ public static async Task ExamplePages(ITelegramBotClient botClient, Update updat var generateMenu = MenuGenerator.GetPageMenu(data.CurrentPage, data.PageCount, CustomTHeaderTwo.CustomPageHeader); var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = generateMenu; - var message = await Helpers.Message.Send(botClient, update, msg, option); + var message = await Helpers.Message.Send(context, msg, option); } /// /// Напишите в чате "pagestwo" /// [ReplyMenuHandler("pagestwo")] - public static async Task ExamplePagesTwo(ITelegramBotClient botClient, Update update) + public static async Task ExamplePagesTwo(IBotContext context) { //Беру текст для первого сообщения string msg = pageDataTwo[0]; @@ -67,7 +67,7 @@ public static async Task ExamplePagesTwo(ITelegramBotClient botClient, Update up var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = generateMenu; - var message = await Helpers.Message.Send(botClient, update, msg, option); + var message = await Helpers.Message.Send(context, msg, option); } /// @@ -75,14 +75,14 @@ public static async Task ExamplePagesTwo(ITelegramBotClient botClient, Update up /// Обрабатывает одну точку входа /// [InlineCallbackHandler(PRTelegramBotCommand.NextPage, PRTelegramBotCommand.PreviousPage, PRTelegramBotCommand.CurrentPage)] - public static async Task InlinenPage(ITelegramBotClient botClient, Update update) + public static async Task InlinenPage(IBotContext context) { try { //Попытка преобразовать callback данные к требуемому типу - if (update.CallbackQuery?.Data != null) + if (context.Update.CallbackQuery?.Data != null) { - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); + var command = InlineCallback.GetCommandByCallbackOrNull(context); if (command != null) { //Получаю заголовок из данных @@ -99,7 +99,7 @@ public static async Task InlinenPage(ITelegramBotClient botClient, Update update var pageResult = data.Results; var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = generateMenu; - string msg = ""; + string msg = string.Empty; if (pageResult.Count > 0) { msg = pageResult.FirstOrDefault(); @@ -109,7 +109,7 @@ public static async Task InlinenPage(ITelegramBotClient botClient, Update update msg = "Нечего не найдено"; } //Редактирую текущую страницу - await Helpers.Message.Edit(botClient, update, msg, option); + await Helpers.Message.Edit(context, msg, option); } //обрабатываю данные по заголовку else if (header == CustomTHeaderTwo.CustomPageHeader2) @@ -122,7 +122,7 @@ public static async Task InlinenPage(ITelegramBotClient botClient, Update update var pageResult = data.Results; var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = generateMenu; - string msg = ""; + string msg = string.Empty; if (pageResult.Count > 0) { msg = pageResult.FirstOrDefault(); @@ -132,7 +132,7 @@ public static async Task InlinenPage(ITelegramBotClient botClient, Update update msg = "Нечего не найдено"; } //Редактирую текущую страницу - await Helpers.Message.Edit(botClient, update, msg, option); + await Helpers.Message.Edit(context, msg, option); } } } @@ -145,7 +145,7 @@ public static async Task InlinenPage(ITelegramBotClient botClient, Update update } [InlineCallbackHandler(CustomTHeader.CustomButton)] - public static async Task FavoriteMessage(ITelegramBotClient botClient, Update update) + public static async Task FavoriteMessage(IBotContext context) { string msg = "Меню"; //Создаем настройки сообщения @@ -172,7 +172,7 @@ public static async Task FavoriteMessage(ITelegramBotClient botClient, Update up var menu = MenuGenerator.ReplyKeyboard(1, menuList, true, "Главное меню"); //Добавляем в настройки меню option.MenuReplyKeyboardMarkup = menu; - await Helpers.Message.Send(botClient, update, msg, option); + await Helpers.Message.Send(context, msg, option); } } } diff --git a/Examples/ConsoleExample/Examples/ExamplePay.cs b/Examples/ConsoleExample/Examples/ExamplePay.cs index ef11b41..c391388 100644 --- a/Examples/ConsoleExample/Examples/ExamplePay.cs +++ b/Examples/ConsoleExample/Examples/ExamplePay.cs @@ -1,11 +1,4 @@ -using PRTelegramBot.Attributes; -using PRTelegramBot.Extensions; -using Telegram.Bot; -using Telegram.Bot.Requests; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Payments; - -namespace ConsoleExample.Examples +namespace ConsoleExample.Examples { internal class ExamplePay { @@ -14,7 +7,7 @@ internal class ExamplePay ///// Метод регистрирует следующий шаг пользователя ///// //[ReplyMenuHandler("Pay")] - //public static async Task Pay(ITelegramBotClient botClient, Update update) + //public static async Task Pay(ITelegramBotClient context.BotClient, context.Update update) //{ // var chatId = new ChatId(update.GetChatId()); // List prices = new(); diff --git a/Examples/ConsoleExample/Examples/ExampleUserCache.cs b/Examples/ConsoleExample/Examples/ExampleUserCache.cs index 02fdebc..2b43e7e 100644 --- a/Examples/ConsoleExample/Examples/ExampleUserCache.cs +++ b/Examples/ConsoleExample/Examples/ExampleUserCache.cs @@ -1,8 +1,7 @@ using ConsoleExample.Models; using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; using Helpers = PRTelegramBot.Helpers; namespace ConsoleExample.Examples @@ -17,12 +16,12 @@ public class ExampleUserCache /// Функция записывает данные в кэш /// [ReplyMenuHandler("cache")] - public static async Task GetCache(ITelegramBotClient botClient, Update update) + public static async Task GetCache(IBotContext context) { - string msg = $"Запись в кэш пользователя данных: {update.GetChatId()}"; + string msg = $"Запись в кэш пользователя данных: {context.GetChatId()}"; //Записываем данные в кеш пользователя - update.GetCacheData().Id = update.GetChatId(); - await Helpers.Message.Send(botClient, update, msg); + context.GetCacheData().Id = context.GetChatId(); + await Helpers.Message.Send(context, msg); } /// @@ -30,11 +29,11 @@ public static async Task GetCache(ITelegramBotClient botClient, Update update) /// Функция получает данные из кэша /// [ReplyMenuHandler("resultcache")] - public static async Task CheckCache(ITelegramBotClient botClient, Update update) + public static async Task CheckCache(IBotContext context) { //Получаем данные с кеша - var cache = update.GetCacheData(); - string msg = ""; + var cache = context.GetCacheData(); + string msg = string.Empty; if(cache.Id != null) { msg = $"Данные в кэше пользователя: {cache.Id}"; @@ -43,7 +42,7 @@ public static async Task CheckCache(ITelegramBotClient botClient, Update update) { msg = $"Данные в кэше пользователя отсутствуют."; } - await Helpers.Message.Send(botClient, update, msg); + await Helpers.Message.Send(context, msg); } /// @@ -51,12 +50,12 @@ public static async Task CheckCache(ITelegramBotClient botClient, Update update) /// Функция очищает данные в кэше пользователя /// [ReplyMenuHandler("clearcache")] - public static async Task ClearCache(ITelegramBotClient botClient, Update update) + public static async Task ClearCache(IBotContext context) { string msg = "Очистка данных"; //Очищаем кеш для пользователя - update.GetCacheData().ClearData(); - await Helpers.Message.Send(botClient, update, msg); + context.GetCacheData().ClearData(); + await Helpers.Message.Send(context, msg); } } } diff --git a/Examples/ConsoleExample/Examples/ExampleUtils.cs b/Examples/ConsoleExample/Examples/ExampleUtils.cs index e83254e..20724ec 100644 --- a/Examples/ConsoleExample/Examples/ExampleUtils.cs +++ b/Examples/ConsoleExample/Examples/ExampleUtils.cs @@ -1,8 +1,7 @@ using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Utils; -using Telegram.Bot; -using Telegram.Bot.Types; namespace ConsoleExample.Examples { @@ -14,13 +13,13 @@ internal class ExampleUtils /// Сначало будет отправлено сообщение 'Обработка данных...', после двух секунд старое сообщение будет удалено и сразу появится новое. /// [ReplyMenuHandler("Awaiter message")] - public static async Task AwaiterExample (ITelegramBotClient botClient, Update update) + public static async Task AwaiterExample (IBotContext context) { - using(var messageAwaiter = new MessageAwaiter(botClient, update.GetChatId(), "Обработка данных...")) + using(var messageAwaiter = new MessageAwaiter(context, "Обработка данных...")) { // Симуляция тяжелой операции. await Task.Delay(2000); - await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Генерация данных завершена."); + await PRTelegramBot.Helpers.Message.Send(context, $"Генерация данных завершена."); } } @@ -30,10 +29,10 @@ public static async Task AwaiterExample (ITelegramBotClient botClient, Update up /// Сообщение будет удалено по истечению 10 секунд. /// [ReplyMenuHandler("AutoDelete")] - public static async Task AutoDelete(ITelegramBotClient botClient, Update update) + public static async Task AutoDelete(IBotContext context) { - var message = await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Автоматическое удаление сообщения через 10 секунд"); - message.AutoDeleteMessage(10, botClient, update); + var message = await PRTelegramBot.Helpers.Message.Send(context, $"Автоматическое удаление сообщения через 10 секунд"); + message.AutoDeleteMessage(10, context); } /// @@ -42,10 +41,10 @@ public static async Task AutoDelete(ITelegramBotClient botClient, Update update) /// Сообщение будет отредактировано по истечению 10 секунд. /// [ReplyMenuHandler("AutoEdit")] - public static async Task AutoEdit(ITelegramBotClient botClient, Update update) + public static async Task AutoEdit(IBotContext context) { - var message = await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Автоматическое редактирование сообщения через 10 секунд"); - message.AutoEditMessage("Текст изменился.", 10, botClient, update); + var message = await PRTelegramBot.Helpers.Message.Send(context, $"Автоматическое редактирование сообщения через 10 секунд"); + message.AutoEditMessage("Текст изменился.", 10, context); } /// @@ -54,7 +53,7 @@ public static async Task AutoEdit(ITelegramBotClient botClient, Update update) /// Сообщение постепенно будет редактироваться. /// [ReplyMenuHandler("AutoEditCycle")] - public static async Task AutoEditCycle(ITelegramBotClient botClient, Update update) + public static async Task AutoEditCycle(IBotContext context) { var messages = new List() { @@ -70,8 +69,8 @@ public static async Task AutoEditCycle(ITelegramBotClient botClient, Update upda "1", "Все готово.", }; - var message = await PRTelegramBot.Helpers.Message.Send(botClient, update, $"Автоматическое редактирование сообщения через 10 секунд"); - message.AutoEditMessageСycle(messages, 1, botClient, update); + var message = await PRTelegramBot.Helpers.Message.Send(context, $"Автоматическое редактирование сообщения через 10 секунд"); + message.AutoEditMessageСycle(messages, 1, context); } } } diff --git a/Examples/ConsoleExample/Examples/ExampleWhiteList.cs b/Examples/ConsoleExample/Examples/ExampleWhiteList.cs index c7af276..9179950 100644 --- a/Examples/ConsoleExample/Examples/ExampleWhiteList.cs +++ b/Examples/ConsoleExample/Examples/ExampleWhiteList.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Attributes; -using Telegram.Bot.Types; -using Telegram.Bot; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; namespace ConsoleExample.Examples @@ -12,10 +11,10 @@ internal class ExampleWhiteList /// Если включен белый список и в нем есть пользователи, отработает только для них. /// [ReplyMenuHandler("OnlyWhiteList")] - public static async Task OnlyWhiteList(ITelegramBotClient botClient, Update update) + public static async Task OnlyWhiteList(IBotContext context) { string msg = nameof(OnlyWhiteList); - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + await PRTelegramBot.Helpers.Message.Send(context, msg); } /// @@ -24,10 +23,10 @@ public static async Task OnlyWhiteList(ITelegramBotClient botClient, Update upda /// [WhiteListAnonymous] [ReplyMenuHandler("AllUsers")] - public static async Task AllUsers(ITelegramBotClient botClient, Update update) + public static async Task AllUsers(IBotContext context) { string msg = nameof(AllUsers); - await PRTelegramBot.Helpers.Message.Send(botClient, update, msg); + await PRTelegramBot.Helpers.Message.Send(context, msg); } } } diff --git a/Examples/ConsoleExample/Examples/InlineClassHandlers/InlineDefaultClassHandler.cs b/Examples/ConsoleExample/Examples/InlineClassHandlers/InlineDefaultClassHandler.cs index a3f33d9..2f95aca 100644 --- a/Examples/ConsoleExample/Examples/InlineClassHandlers/InlineDefaultClassHandler.cs +++ b/Examples/ConsoleExample/Examples/InlineClassHandlers/InlineDefaultClassHandler.cs @@ -1,6 +1,4 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Extensions; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Models.TCommands; @@ -21,12 +19,12 @@ public class InlineDefaultClassHandler : ICallbackQueryCommandHandler #region ICallbackQueryCommandHandler - public async Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + public async Task Handle(IBotContext context, CallbackQuery updateType) { var command = InlineCallback.GetCommandByCallbackOrNull(updateType.Data); if (command != null) { - await PRTelegramBot.Helpers.Message.Send(bot.botClient, update.GetChatId(), $"{TEST_ADD_MESSAGE} {command.Data.StrData}"); + await PRTelegramBot.Helpers.Message.Send(context, $"{TEST_ADD_MESSAGE} {command.Data.StrData}"); return UpdateResult.Handled; } diff --git a/Examples/ConsoleExample/Middlewares/OneMiddleWare.cs b/Examples/ConsoleExample/Middlewares/OneMiddleWare.cs index dab871e..846d418 100644 --- a/Examples/ConsoleExample/Middlewares/OneMiddleWare.cs +++ b/Examples/ConsoleExample/Middlewares/OneMiddleWare.cs @@ -1,21 +1,20 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace ConsoleExample.Middlewares { public class OneMiddleware : MiddlewareBase { - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { Console.WriteLine("Выполнение первого обработчика перед update"); - await base.InvokeOnPreUpdateAsync(botClient, update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { Console.WriteLine("Выполнение первого обработчика после update"); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } } } diff --git a/Examples/ConsoleExample/Middlewares/ThreeMiddleware.cs b/Examples/ConsoleExample/Middlewares/ThreeMiddleware.cs index e6eaaa5..a3a6cdc 100644 --- a/Examples/ConsoleExample/Middlewares/ThreeMiddleware.cs +++ b/Examples/ConsoleExample/Middlewares/ThreeMiddleware.cs @@ -1,21 +1,20 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace ConsoleExample.Middlewares { public class ThreeMiddleware : MiddlewareBase { - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { Console.WriteLine("Выполнение третьего обработчика перед update"); - await base.InvokeOnPreUpdateAsync(botClient, update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { Console.WriteLine("Выполнение третьего обработчика после update"); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } } } diff --git a/Examples/ConsoleExample/Middlewares/TwoMiddleWare.cs b/Examples/ConsoleExample/Middlewares/TwoMiddleWare.cs index a1445f3..11ba82a 100644 --- a/Examples/ConsoleExample/Middlewares/TwoMiddleWare.cs +++ b/Examples/ConsoleExample/Middlewares/TwoMiddleWare.cs @@ -1,21 +1,20 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace ConsoleExample.Middlewares { public class TwoMiddleware : MiddlewareBase { - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { Console.WriteLine("Выполнение второго обработчика перед update"); - await base.InvokeOnPreUpdateAsync(botClient,update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { Console.WriteLine("Выполнение второго обработчика после update"); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } } } diff --git a/Examples/ConsoleExample/Models/UserCache.cs b/Examples/ConsoleExample/Models/UserCache.cs index d967aa4..81c8cc9 100644 --- a/Examples/ConsoleExample/Models/UserCache.cs +++ b/Examples/ConsoleExample/Models/UserCache.cs @@ -15,7 +15,7 @@ public class UserCache : ITelegramCache public bool ClearData() { - Data = ""; + Data = string.Empty; return true; } } diff --git a/Examples/ConsoleExample/Program.cs b/Examples/ConsoleExample/Program.cs index 2668fed..bdd6ef1 100644 --- a/Examples/ConsoleExample/Program.cs +++ b/Examples/ConsoleExample/Program.cs @@ -3,6 +3,7 @@ using ConsoleExample.Models.CommandHeaders; using ConsoleExample.Services; using PRTelegramBot.Core; +using PRTelegramBot.Models.EventsArgs; /**************************************************************************************** * ###################################################################################### @@ -35,12 +36,12 @@ Initializer.InitCommands(telegram); // Запуск работы бота. -await telegram.Start(); +await telegram.StartAsync(); telegram.Events.OnErrorLog += Events_OnErrorLog; -async Task Events_OnErrorLog(PRTelegramBot.Models.EventsArgs.ErrorLogEventArgs arg) +async Task Events_OnErrorLog(ErrorLogEventArgs arg) { Console.WriteLine(arg.Exception.Message); } diff --git a/Examples/ConsoleExample/Services/Initializer.cs b/Examples/ConsoleExample/Services/Initializer.cs index ce891e4..29a6855 100644 --- a/Examples/ConsoleExample/Services/Initializer.cs +++ b/Examples/ConsoleExample/Services/Initializer.cs @@ -128,14 +128,14 @@ public static void InitUpdateEvents(PRBotBase bot) /// Бот. public static void InitCommands(PRBotBase bot) { - bot.Register.AddInlineCommand(AddCustomTHeader.TestAddCommand, async (botClient, update) => + bot.Register.AddInlineCommand(AddCustomTHeader.TestAddCommand, async (context) => { - await PRTelegramBot.Helpers.Message.Send(botClient, update, "Тест метода TestAddCommand"); + await PRTelegramBot.Helpers.Message.Send(context, "Тест метода TestAddCommand"); }); - bot.Register.AddInlineCommand(AddCustomTHeader.TestAddCommandTwo, async (botClient, update) => + bot.Register.AddInlineCommand(AddCustomTHeader.TestAddCommandTwo, async (context) => { - await PRTelegramBot.Helpers.Message.Send(botClient, update, "Тест метода TestAddCommandTwo"); + await PRTelegramBot.Helpers.Message.Send(context, "Тест метода TestAddCommandTwo"); }); } @@ -156,7 +156,7 @@ public static Dictionary GetDynamicCommands() public static List GetCommandChekers() { var checkerReplyCommand = new InternalChecker(CommandType.Reply, new ReplyExampleChecker()); - var adminChecker = new InternalChecker(new List() { CommandType.Reply, CommandType.NextStep, CommandType.Inline, CommandType.ReplyDynamic, CommandType.Slash }, new AdminExampleChecher()); + var adminChecker = new InternalChecker(new List() { CommandType.Reply, CommandType.NextStep, CommandType.Inline, CommandType.ReplyDynamic, CommandType.Slash }, new AdminExampleChecker()); return new List() { checkerReplyCommand, adminChecker }; } diff --git a/PRTelegramBot.Tests/Common/Commands.cs b/PRTelegramBot.Tests/Common/Commands.cs index 198ec30..2bd8fe4 100644 --- a/PRTelegramBot.Tests/Common/Commands.cs +++ b/PRTelegramBot.Tests/Common/Commands.cs @@ -1,8 +1,7 @@ using PRTelegramBot.Attributes; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using static PRTelegramBot.Tests.CoreTests.FindMethodsTests; -using Telegram.Bot.Types; -using Telegram.Bot; namespace PRTelegramBot.Tests.Common { @@ -14,19 +13,19 @@ public class Commands [ReplyMenuHandler(CommandComparison.Contains, StringComparison.Ordinal, nameof(TestCommonMethod), "TestTwoArgs")] [InlineCallbackHandler(TestTHeader.One, TestTHeader.Two)] [ReplyMenuDynamicHandler(CommandComparison.Contains, StringComparison.Ordinal, nameof(KEY_DYNAMIC_REPLY_FOUR))] - public static async Task TestCommonMethod(ITelegramBotClient botClient, Update update) { } + public static async Task TestCommonMethod(IBotContext context) { } [SlashHandler(2, nameof(TestCommonMethodTwo))] [ReplyMenuHandler(2, nameof(TestCommonMethodTwo))] [InlineCallbackHandler(2, TestTHeader.Three)] [ReplyMenuDynamicHandler(2, nameof(KEY_DYNAMIC_REPLY_FOUR))] - public static async Task TestCommonMethodTwo(ITelegramBotClient botClient, Update update) { } + public static async Task TestCommonMethodTwo(IBotContext context) { } [SlashHandler(-1, nameof(TestCommonMethodForAllBot))] [ReplyMenuHandler(-1, nameof(TestCommonMethodForAllBot))] [InlineCallbackHandler(-1, TestTHeader.Eight)] [ReplyMenuDynamicHandler(-1, nameof(KEY_DYNAMIC_REPLY_FIVE))] - public static async Task TestCommonMethodForAllBot(ITelegramBotClient botClient, Update update) { } + public static async Task TestCommonMethodForAllBot(IBotContext context) { } #endregion @@ -35,56 +34,56 @@ public static async Task TestCommonMethodForAllBot(ITelegramBotClient botClient, [Access(1)] [ReplyMenuHandler(nameof(TestAccessMethod))] - public static async Task TestAccessMethod(ITelegramBotClient botClient, Update update) { } + public static async Task TestAccessMethod(IBotContext context) { } [ReplyMenuHandler(1, nameof(TestReplyWithCustomId))] - public static async Task TestReplyWithCustomId(ITelegramBotClient botClient, Update update) { } + public static async Task TestReplyWithCustomId(IBotContext context) { } [ReplyMenuHandler([2, 1], nameof(TestReplyWithCustomIdTwo))] - public static async Task TestReplyWithCustomIdTwo(ITelegramBotClient botClient, Update update) { } + public static async Task TestReplyWithCustomIdTwo(IBotContext context) { } [RequireTypeMessage(Telegram.Bot.Types.Enums.MessageType.Photo)] [ReplyMenuHandler(nameof(TestTypeMessage))] - public static async Task TestTypeMessage(ITelegramBotClient botClient, Update update) { } + public static async Task TestTypeMessage(IBotContext context) { } #endregion #region Reply dynamic methods [ReplyMenuDynamicHandler(nameof(KEY_DYNAMIC_REPLY_ONE))] - public static async Task TestDynamicReplyOne(ITelegramBotClient botClient, Update update) { } + public static async Task TestDynamicReplyOne(IBotContext context) { } [ReplyMenuDynamicHandler(1, nameof(KEY_DYNAMIC_REPLY_TWO))] - public static async Task TestDynamicReplyWithCustomId(ITelegramBotClient botClient, Update update) { } + public static async Task TestDynamicReplyWithCustomId(IBotContext context) { } [ReplyMenuDynamicHandler([2,1], KEY_DYNAMIC_REPLY_THREE)] - public static async Task TestDynamicReplyWithCustomIdTwo(ITelegramBotClient botClient, Update update) { } + public static async Task TestDynamicReplyWithCustomIdTwo(IBotContext context) { } #endregion #region Inline methods [InlineCallbackHandler(TestTHeader.Four, TestTHeader.Five)] - public static async Task InlineFive(ITelegramBotClient botClient, Update update) { } + public static async Task InlineFive(IBotContext context) { } [InlineCallbackHandler(1, TestTHeader.Six)] - public static async Task InlineSix(ITelegramBotClient botClient, Update update) { } + public static async Task InlineSix(IBotContext context) { } [InlineCallbackHandler([2, 1], TestTHeader.Seven)] - public static async Task InlineSeven(ITelegramBotClient botClient, Update update) { } + public static async Task InlineSeven(IBotContext context) { } #endregion #region Slash methods [SlashHandler(nameof(TestSlashMethod))] - public static async Task TestSlashMethod(ITelegramBotClient botClient, Update update) { } + public static async Task TestSlashMethod(IBotContext context) { } [SlashHandler(1, nameof(TestSlashMethodTwo))] - public static async Task TestSlashMethodTwo(ITelegramBotClient botClient, Update update) { } + public static async Task TestSlashMethodTwo(IBotContext context) { } [SlashHandler([2, 1], nameof(TestSlashMethodThree))] - public static async Task TestSlashMethodThree(ITelegramBotClient botClient, Update update) { } + public static async Task TestSlashMethodThree(IBotContext context) { } #endregion } diff --git a/PRTelegramBot.Tests/CoreTests/CacheTests.cs b/PRTelegramBot.Tests/CoreTests/CacheTests.cs index 1ccacbf..e43709a 100644 --- a/PRTelegramBot.Tests/CoreTests/CacheTests.cs +++ b/PRTelegramBot.Tests/CoreTests/CacheTests.cs @@ -1,8 +1,4 @@ -using Moq; -using PRTelegramBot.Extensions; -using Telegram.Bot.Types; - -namespace PRTelegramBot.Tests.CoreTests +namespace PRTelegramBot.Tests.CoreTests { internal class CacheTests { diff --git a/PRTelegramBot.Tests/CoreTests/FindMethodsTests.cs b/PRTelegramBot.Tests/CoreTests/FindMethodsTests.cs index c03c10f..03fe4fe 100644 --- a/PRTelegramBot.Tests/CoreTests/FindMethodsTests.cs +++ b/PRTelegramBot.Tests/CoreTests/FindMethodsTests.cs @@ -4,8 +4,6 @@ using PRTelegramBot.Tests.Common; using PRTelegramBot.Utils; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Tests.CoreTests { @@ -17,8 +15,8 @@ public void Cleanup() BotCollection.Instance.ClearBots(); } - public const string KEY_DYNAMIC_REPLY_ONE = ""; - public const string KEY_DYNAMIC_REPLY_TWO = ""; + public const string KEY_DYNAMIC_REPLY_ONE = ""; + public const string KEY_DYNAMIC_REPLY_TWO = ""; public const string KEY_DYNAMIC_REPLY_THREE = "dynamic three"; public const string KEY_DYNAMIC_REPLY_FOUR = "dynamic four"; public const string KEY_DYNAMIC_REPLY_FIVE = "dynamic five"; diff --git a/PRTelegramBot.Tests/CoreTests/HandlerTests.cs b/PRTelegramBot.Tests/CoreTests/HandlerTests.cs new file mode 100644 index 0000000..6b6a492 --- /dev/null +++ b/PRTelegramBot.Tests/CoreTests/HandlerTests.cs @@ -0,0 +1,54 @@ +using PRTelegramBot.Core; +using PRTelegramBot.Models.EventsArgs; +using PRTelegramBot.Tests.Common; + +namespace PRTelegramBot.Tests.CoreTests +{ + internal class HandlerTests + { + private PRBotBase bot { get; set; } + + [OneTimeSetUp] + public void SetUP() + { + bot = new PRBotBuilder("5555:Token").Build(); + bot.ReloadHandlers(); + } + + [OneTimeTearDown] + public void TearDown() + { + BotCollection.Instance.ClearBots(); + } + + [Test] + public async Task HandleUpdateAsyncShouldTriggerErrorLogWhenHandlerThrows() + { + var update = UpdateSetUp.CreateUpdateTypeShippingQuery(); + bool errorEventCalled = false; + Exception capturedException = null; + + bot.Events.OnErrorLog += (args) => + { + errorEventCalled = true; + capturedException = args.Exception; + return Task.CompletedTask; + }; + + Task ThrowingHandler(BotEventArgs e) + { + throw new InvalidOperationException("Test exception"); + } + + bot.Events.UpdateEvents.OnShippingQueryHandle += ThrowingHandler; + + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, CancellationToken.None); + + Assert.IsTrue(errorEventCalled, "Error event was not triggered."); + Assert.IsNotNull(capturedException, "Exception was not captured."); + Assert.IsInstanceOf(capturedException); + + bot.Events.UpdateEvents.OnShippingQueryHandle -= ThrowingHandler; + } + } +} diff --git a/PRTelegramBot.Tests/CoreTests/MiddlewareTests.cs b/PRTelegramBot.Tests/CoreTests/MiddlewareTests.cs index 8336bd0..d886f95 100644 --- a/PRTelegramBot.Tests/CoreTests/MiddlewareTests.cs +++ b/PRTelegramBot.Tests/CoreTests/MiddlewareTests.cs @@ -1,7 +1,7 @@ using Moq; using PRTelegramBot.Core.Middlewares; +using PRTelegramBot.Interfaces; using PRTelegramBot.Tests.TestModels.TestMiddleware; -using Telegram.Bot; using Telegram.Bot.Types; namespace PRTelegramBot.Tests.CoreTests @@ -13,7 +13,7 @@ public async Task MiddlewareExecutesBeforeAndAfterMainLogic() { var exceptedMessageMainLogin = "Main Logic"; var update = new Update { Id = 1 }; - var botClientMock = new Mock(); + var botContextMock = new Mock(); var log = new List(); var middlewareOne = new TestOneMiddleware(log); @@ -23,7 +23,7 @@ public async Task MiddlewareExecutesBeforeAndAfterMainLogic() var builder = new MiddlewareBuilder(); var middlewareChain = builder.Build(new List() { middlewareOne, middlewareTwo, middlewareThree }); - await middlewareChain.InvokeOnPreUpdateAsync(botClientMock.Object, update, async () => + await middlewareChain.InvokeOnPreUpdateAsync(botContextMock.Object, async () => { log.Add(exceptedMessageMainLogin); }); diff --git a/PRTelegramBot.Tests/CoreTests/PRBotBuilderTests.cs b/PRTelegramBot.Tests/CoreTests/PRBotBuilderTests.cs index 514e8dd..63bef03 100644 --- a/PRTelegramBot.Tests/CoreTests/PRBotBuilderTests.cs +++ b/PRTelegramBot.Tests/CoreTests/PRBotBuilderTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using PRTelegramBot.Configs; using PRTelegramBot.Core; using PRTelegramBot.Core.Factories; using PRTelegramBot.Core.Factory; diff --git a/PRTelegramBot.Tests/CoreTests/TelegramOptionsTests.cs b/PRTelegramBot.Tests/CoreTests/TelegramOptionsTests.cs index a2a5ab3..5648372 100644 --- a/PRTelegramBot.Tests/CoreTests/TelegramOptionsTests.cs +++ b/PRTelegramBot.Tests/CoreTests/TelegramOptionsTests.cs @@ -90,7 +90,7 @@ public void AddInlineClassHandlerWhenTypeImplementedInterfaceNotShouldBeExceptio [Test] public void AddInlineClassHandlerWhenTypeNotImplementedInterfaceShouldBeException() { - var exception = Assert.Throws(() => + var exception = Assert.Throws(() => { var bot = new PRBotBuilder(CommonUtils.TEST_TOKEN) .AddInlineClassHandler(TestTHeader.Class, typeof(TestClass)) diff --git a/PRTelegramBot.Tests/EventsTests/EventTests.cs b/PRTelegramBot.Tests/EventsTests/EventTests.cs index 6cb6aa2..6277ec6 100644 --- a/PRTelegramBot.Tests/EventsTests/EventTests.cs +++ b/PRTelegramBot.Tests/EventsTests/EventTests.cs @@ -1,4 +1,5 @@ using PRTelegramBot.Core; +using PRTelegramBot.Models; using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Tests.Common; @@ -41,7 +42,7 @@ Task EventHandler(StartEventArgs e) } bot.Events.OnUserStartWithArgs += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.OnUserStartWithArgs)} event was not called."); bot.Events.OnUserStartWithArgs -= EventHandler; } @@ -59,7 +60,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.OnMissingCommand += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.OnMissingCommand)} event was not called."); bot.Events.OnMissingCommand -= EventHandler; } @@ -77,7 +78,7 @@ Task EventHandler(PrivilegeEventArgs e) } bot.Events.OnCheckPrivilege += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.OnCheckPrivilege)} event was not called."); bot.Events.OnCheckPrivilege -= EventHandler; } @@ -93,7 +94,7 @@ Task EventHandler(BotEventArgs e) return Task.CompletedTask; } bot.Events.OnWrongTypeMessage += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.OnWrongTypeMessage)} event was not called."); bot.Events.OnWrongTypeMessage -= EventHandler; } @@ -111,7 +112,7 @@ Task EventHandler(BotEventArgs e) return Task.CompletedTask; } bot.Events.OnAccessDenied += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.OnAccessDenied)} event was not called."); bot.Events.OnAccessDenied -= EventHandler; await bot.Options.WhiteListManager.RemoveUser(testUserId); @@ -130,7 +131,7 @@ Task EventHandler(BotEventArgs e) return Task.CompletedTask; } bot.Events.OnAccessDenied += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsFalse(eventCalled, $"The {nameof(bot.Events.OnAccessDenied)} event was not called."); bot.Events.OnAccessDenied -= EventHandler; await bot.Options.WhiteListManager.RemoveUser(userId); @@ -141,7 +142,7 @@ public async Task OnErrorLog() { var tcs = new TaskCompletionSource(); bot.Events.OnErrorLog += EventHandler; - bot.Events.OnErrorLogInvoke(new Exception("Error")); + bot.Events.OnErrorLogInvoke(new ErrorLogEventArgs(new BotContext(bot), new Exception("EX"))); Task EventHandler(BotEventArgs e) { tcs.SetResult(true); diff --git a/PRTelegramBot.Tests/EventsTests/MessageEventsTest.cs b/PRTelegramBot.Tests/EventsTests/MessageEventsTest.cs index a3c3bb1..618556d 100644 --- a/PRTelegramBot.Tests/EventsTests/MessageEventsTest.cs +++ b/PRTelegramBot.Tests/EventsTests/MessageEventsTest.cs @@ -34,7 +34,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnContactHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnContactHandle)} event was not called."); bot.Events.MessageEvents.OnContactHandle -= EventHandler; } @@ -52,7 +52,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnPollHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnPollHandle)} event was not called."); bot.Events.MessageEvents.OnPollHandle -= EventHandler; } @@ -70,7 +70,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnLocationHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnLocationHandle)} event was not called."); bot.Events.MessageEvents.OnLocationHandle -= EventHandler; } @@ -88,7 +88,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnWebAppsHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnWebAppsHandle)} event was not called."); bot.Events.MessageEvents.OnWebAppsHandle -= EventHandler; } @@ -106,7 +106,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnDocumentHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnDocumentHandle)} event was not called."); bot.Events.MessageEvents.OnDocumentHandle -= EventHandler; } @@ -124,7 +124,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnAudioHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnAudioHandle)} event was not called."); bot.Events.MessageEvents.OnAudioHandle -= EventHandler; } @@ -142,7 +142,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoHandle)} event was not called."); bot.Events.MessageEvents.OnVideoHandle -= EventHandler; } @@ -160,7 +160,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnPhotoHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnPhotoHandle)} event was not called."); bot.Events.MessageEvents.OnPhotoHandle -= EventHandler; } @@ -178,7 +178,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnStickerHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnStickerHandle)} event was not called."); bot.Events.MessageEvents.OnStickerHandle -= EventHandler; } @@ -196,7 +196,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVoiceHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVoiceHandle)} event was not called."); bot.Events.MessageEvents.OnVoiceHandle -= EventHandler; } @@ -214,7 +214,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnTextHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnTextHandle)} event was not called."); bot.Events.MessageEvents.OnTextHandle -= EventHandler; } @@ -232,7 +232,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVenueHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVenueHandle)} event was not called."); bot.Events.MessageEvents.OnVenueHandle -= EventHandler; } @@ -250,7 +250,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGameHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGameHandle)} event was not called."); bot.Events.MessageEvents.OnGameHandle -= EventHandler; } @@ -268,7 +268,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoNoteHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoNoteHandle)} event was not called."); bot.Events.MessageEvents.OnVideoNoteHandle -= EventHandler; } @@ -286,7 +286,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnDiceHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnDiceHandle)} event was not called."); bot.Events.MessageEvents.OnDiceHandle -= EventHandler; } @@ -304,7 +304,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnAnimationHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnAnimationHandle)} event was not called."); bot.Events.MessageEvents.OnAnimationHandle -= EventHandler; } @@ -322,7 +322,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnStoryHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnStoryHandle)} event was not called."); bot.Events.MessageEvents.OnStoryHandle -= EventHandler; } @@ -340,7 +340,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnPassportDataHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnPassportDataHandle)} event was not called."); bot.Events.MessageEvents.OnPassportDataHandle -= EventHandler; } @@ -358,7 +358,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGiveawayCreatedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGiveawayCreatedHandle)} event was not called."); bot.Events.MessageEvents.OnGiveawayCreatedHandle -= EventHandler; } @@ -376,7 +376,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatMemberLeftHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatMemberLeftHandle)} event was not called."); bot.Events.MessageEvents.OnChatMemberLeftHandle -= EventHandler; } @@ -394,7 +394,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatTitleChangedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatTitleChangedHandle)} event was not called."); bot.Events.MessageEvents.OnChatTitleChangedHandle -= EventHandler; } @@ -412,7 +412,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatPhotoChangedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatPhotoChangedHandle)} event was not called."); bot.Events.MessageEvents.OnChatPhotoChangedHandle -= EventHandler; } @@ -430,7 +430,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatPhotoDeletedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatPhotoDeletedHandle)} event was not called."); bot.Events.MessageEvents.OnChatPhotoDeletedHandle -= EventHandler; } @@ -448,7 +448,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGroupCreatedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGroupCreatedHandle)} event was not called."); bot.Events.MessageEvents.OnGroupCreatedHandle -= EventHandler; } @@ -466,7 +466,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnSupergroupCreatedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnSupergroupCreatedHandle)} event was not called."); bot.Events.MessageEvents.OnSupergroupCreatedHandle -= EventHandler; } @@ -484,7 +484,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChannelCreatedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChannelCreatedHandle)} event was not called."); bot.Events.MessageEvents.OnChannelCreatedHandle -= EventHandler; } @@ -502,7 +502,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnMessageAutoDeleteTimerChangedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnMessageAutoDeleteTimerChangedHandle)} event was not called."); bot.Events.MessageEvents.OnMessageAutoDeleteTimerChangedHandle -= EventHandler; } @@ -520,7 +520,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnMigratedFromGroupHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnMigratedFromGroupHandle)} event was not called."); bot.Events.MessageEvents.OnMigratedFromGroupHandle -= EventHandler; } @@ -538,7 +538,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnMigratedToSupergroupHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnMigratedToSupergroupHandle)} event was not called."); bot.Events.MessageEvents.OnMigratedToSupergroupHandle -= EventHandler; } @@ -556,7 +556,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnMessagePinnedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnMessagePinnedHandle)} event was not called."); bot.Events.MessageEvents.OnMessagePinnedHandle -= EventHandler; } @@ -574,7 +574,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnWebsiteConnectedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnWebsiteConnectedHandle)} event was not called."); bot.Events.MessageEvents.OnWebsiteConnectedHandle -= EventHandler; } @@ -592,7 +592,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnInvoiceHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnInvoiceHandle)} event was not called."); bot.Events.MessageEvents.OnInvoiceHandle -= EventHandler; } @@ -610,7 +610,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnSuccessfulPaymentHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnSuccessfulPaymentHandle)} event was not called."); bot.Events.MessageEvents.OnSuccessfulPaymentHandle -= EventHandler; } @@ -628,7 +628,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnUserSharedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnUserSharedHandle)} event was not called."); bot.Events.MessageEvents.OnUserSharedHandle -= EventHandler; } @@ -646,7 +646,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatSharedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatSharedHandle)} event was not called."); bot.Events.MessageEvents.OnChatSharedHandle -= EventHandler; } @@ -664,7 +664,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnWriteAccessAllowedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnWriteAccessAllowedHandle)} event was not called."); bot.Events.MessageEvents.OnWriteAccessAllowedHandle -= EventHandler; } @@ -682,7 +682,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnPassportDataHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnPassportDataHandle)} event was not called."); bot.Events.MessageEvents.OnPassportDataHandle -= EventHandler; } @@ -700,7 +700,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnProximityAlertTriggeredHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnProximityAlertTriggeredHandle)} event was not called."); bot.Events.MessageEvents.OnProximityAlertTriggeredHandle -= EventHandler; } @@ -718,7 +718,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnBoostAddedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnBoostAddedHandle)} event was not called."); bot.Events.MessageEvents.OnBoostAddedHandle -= EventHandler; } @@ -736,7 +736,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnChatBackgroundSetHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnChatBackgroundSetHandle)} event was not called."); bot.Events.MessageEvents.OnChatBackgroundSetHandle -= EventHandler; } @@ -754,7 +754,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnForumTopicCreatedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnForumTopicCreatedHandle)} event was not called."); bot.Events.MessageEvents.OnForumTopicCreatedHandle -= EventHandler; } @@ -772,7 +772,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnForumTopicEditedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnForumTopicEditedHandle)} event was not called."); bot.Events.MessageEvents.OnForumTopicEditedHandle -= EventHandler; } @@ -790,7 +790,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnForumTopicClosedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnForumTopicClosedHandle)} event was not called."); bot.Events.MessageEvents.OnForumTopicClosedHandle -= EventHandler; } @@ -808,7 +808,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnForumTopicReopenedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnForumTopicReopenedHandle)} event was not called."); bot.Events.MessageEvents.OnForumTopicReopenedHandle -= EventHandler; } @@ -826,7 +826,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGeneralForumTopicHiddenHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGeneralForumTopicHiddenHandle)} event was not called."); bot.Events.MessageEvents.OnGeneralForumTopicHiddenHandle -= EventHandler; } @@ -844,7 +844,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGeneralForumTopicUnhiddenHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGeneralForumTopicUnhiddenHandle)} event was not called."); bot.Events.MessageEvents.OnGeneralForumTopicUnhiddenHandle -= EventHandler; } @@ -862,7 +862,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGiveawayHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGiveawayHandle)} event was not called."); bot.Events.MessageEvents.OnGiveawayHandle -= EventHandler; } @@ -881,7 +881,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGiveawayWinnersHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGiveawayWinnersHandle)} event was not called."); bot.Events.MessageEvents.OnGiveawayWinnersHandle -= EventHandler; } @@ -899,7 +899,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnGiveawayCompletedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnGiveawayCompletedHandle)} event was not called."); bot.Events.MessageEvents.OnGiveawayCompletedHandle -= EventHandler; } @@ -917,7 +917,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoChatScheduledHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoChatScheduledHandle)} event was not called."); bot.Events.MessageEvents.OnVideoChatScheduledHandle -= EventHandler; } @@ -935,7 +935,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoChatStartedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoChatStartedHandle)} event was not called."); bot.Events.MessageEvents.OnVideoChatStartedHandle -= EventHandler; } @@ -953,7 +953,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoChatEndedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoChatEndedHandle)} event was not called."); bot.Events.MessageEvents.OnVideoChatEndedHandle -= EventHandler; } @@ -971,7 +971,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.MessageEvents.OnVideoChatParticipantsInvitedHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.MessageEvents.OnVideoChatParticipantsInvitedHandle)} event was not called."); bot.Events.MessageEvents.OnVideoChatParticipantsInvitedHandle -= EventHandler; } diff --git a/PRTelegramBot.Tests/EventsTests/UpdateEventsTests.cs b/PRTelegramBot.Tests/EventsTests/UpdateEventsTests.cs index b755913..44bdee7 100644 --- a/PRTelegramBot.Tests/EventsTests/UpdateEventsTests.cs +++ b/PRTelegramBot.Tests/EventsTests/UpdateEventsTests.cs @@ -35,7 +35,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnEditedMessageHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnEditedMessageHandle)} event was not called."); bot.Events.UpdateEvents.OnEditedMessageHandle -= EventHandler; } @@ -53,7 +53,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnChannelPostHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnChannelPostHandle)} event was not called."); bot.Events.UpdateEvents.OnChannelPostHandle -= EventHandler; } @@ -71,7 +71,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnEditedChannelPostHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnEditedChannelPostHandle)} event was not called."); bot.Events.UpdateEvents.OnEditedChannelPostHandle -= EventHandler; } @@ -89,7 +89,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnBusinessConnectionHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnBusinessConnectionHandle)} event was not called."); bot.Events.UpdateEvents.OnBusinessConnectionHandle -= EventHandler; } @@ -107,7 +107,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnEditedBusinessMessageHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnEditedBusinessMessageHandle)} event was not called."); bot.Events.UpdateEvents.OnEditedBusinessMessageHandle -= EventHandler; } @@ -125,7 +125,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnDeletedBusinessMessagesHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnDeletedBusinessMessagesHandle)} event was not called."); bot.Events.UpdateEvents.OnDeletedBusinessMessagesHandle -= EventHandler; } @@ -143,7 +143,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnMessageReactionHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnMessageReactionHandle)} event was not called."); bot.Events.UpdateEvents.OnMessageReactionHandle -= EventHandler; } @@ -161,7 +161,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnMessageReactionCountHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnMessageReactionCountHandle)} event was not called."); bot.Events.UpdateEvents.OnMessageReactionCountHandle -= EventHandler; } @@ -179,7 +179,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnInlineQueryHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnInlineQueryHandle)} event was not called."); bot.Events.UpdateEvents.OnInlineQueryHandle -= EventHandler; } @@ -197,7 +197,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnChosenInlineResultHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnChosenInlineResultHandle)} event was not called."); bot.Events.UpdateEvents.OnChosenInlineResultHandle -= EventHandler; } @@ -215,7 +215,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnShippingQueryHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnShippingQueryHandle)} event was not called."); bot.Events.UpdateEvents.OnShippingQueryHandle -= EventHandler; } @@ -233,7 +233,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnPreCheckoutQueryHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnPreCheckoutQueryHandle)} event was not called."); bot.Events.UpdateEvents.OnPreCheckoutQueryHandle -= EventHandler; } @@ -251,7 +251,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnPollHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnPollHandle)} event was not called."); bot.Events.UpdateEvents.OnPollHandle -= EventHandler; } @@ -269,7 +269,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnPollAnswerHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnPollAnswerHandle)} event was not called."); bot.Events.UpdateEvents.OnPollAnswerHandle -= EventHandler; } @@ -287,7 +287,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnMyChatMemberHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnMyChatMemberHandle)} event was not called."); bot.Events.UpdateEvents.OnMyChatMemberHandle -= EventHandler; } @@ -305,7 +305,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnChatMemberHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnChatMemberHandle)} event was not called."); bot.Events.UpdateEvents.OnChatMemberHandle -= EventHandler; } @@ -323,7 +323,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnChatJoinRequestHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnChatJoinRequestHandle)} event was not called."); bot.Events.UpdateEvents.OnChatJoinRequestHandle -= EventHandler; } @@ -341,7 +341,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnChatBoostHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnChatBoostHandle)} event was not called."); bot.Events.UpdateEvents.OnChatBoostHandle -= EventHandler; } @@ -359,7 +359,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnRemovedChatBoostHandle += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnRemovedChatBoostHandle)} event was not called."); bot.Events.UpdateEvents.OnRemovedChatBoostHandle -= EventHandler; } @@ -377,7 +377,7 @@ Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnPostUpdate += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnPostUpdate)} event was not called."); bot.Events.UpdateEvents.OnPostUpdate -= EventHandler; } @@ -395,7 +395,7 @@ async Task EventHandler(BotEventArgs e) } bot.Events.UpdateEvents.OnPreUpdate += EventHandler; - await bot.Handler.HandleUpdateAsync(bot.botClient, update, new CancellationToken()); + await bot.Handler.HandleUpdateAsync(bot.BotClient, update, new CancellationToken()); Assert.IsTrue(eventCalled, $"The {nameof(bot.Events.UpdateEvents.OnPreUpdate)} event was not called."); bot.Events.UpdateEvents.OnPreUpdate -= EventHandler; } diff --git a/PRTelegramBot.Tests/TestModels/TestHandlers/CallbackQueryTestHandler.cs b/PRTelegramBot.Tests/TestModels/TestHandlers/CallbackQueryTestHandler.cs index 812f99f..6a62873 100644 --- a/PRTelegramBot.Tests/TestModels/TestHandlers/CallbackQueryTestHandler.cs +++ b/PRTelegramBot.Tests/TestModels/TestHandlers/CallbackQueryTestHandler.cs @@ -1,5 +1,4 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using Telegram.Bot.Types; @@ -7,7 +6,7 @@ namespace PRTelegramBot.Tests.TestModels.TestHandlers { public class CallbackQueryTestHandler : ICallbackQueryCommandHandler { - public async Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + public async Task Handle(IBotContext context, CallbackQuery updateType) { ///* Если данные пришли которые вам нужны и вы их обработали возращаем результат Handled. // * Это будет означать, то что действие выполнено и остальные обработчики будут пропущены. */ diff --git a/PRTelegramBot.Tests/TestModels/TestHandlers/MessageTestHandler.cs b/PRTelegramBot.Tests/TestModels/TestHandlers/MessageTestHandler.cs index ff3fea2..58331ed 100644 --- a/PRTelegramBot.Tests/TestModels/TestHandlers/MessageTestHandler.cs +++ b/PRTelegramBot.Tests/TestModels/TestHandlers/MessageTestHandler.cs @@ -1,5 +1,4 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using Telegram.Bot.Types; @@ -7,7 +6,7 @@ namespace PRTelegramBot.Tests.TestModels.TestHandlers { internal class MessageTestHandler : IMessageCommandHandler { - public async Task Handle(PRBotBase bot, Update update, Message updateType) + public async Task Handle(IBotContext context, Message updateType) { ///* Если данные пришли которые вам нужны и вы их обработали возращаем результат Handled. // * Это будет означать, то что действие выполнено и остальные обработчики будут пропущены. */ diff --git a/PRTelegramBot.Tests/TestModels/TestHandlers/TestInlineClassHandler.cs b/PRTelegramBot.Tests/TestModels/TestHandlers/TestInlineClassHandler.cs index 6c175ee..cad77b2 100644 --- a/PRTelegramBot.Tests/TestModels/TestHandlers/TestInlineClassHandler.cs +++ b/PRTelegramBot.Tests/TestModels/TestHandlers/TestInlineClassHandler.cs @@ -1,5 +1,4 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using Telegram.Bot.Types; @@ -7,7 +6,7 @@ namespace PRTelegramBot.Tests.TestModels.TestHandlers { internal class TestInlineClassHandler : ICallbackQueryCommandHandler { - public Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + public Task Handle(IBotContext context, CallbackQuery updateType) { throw new NotImplementedException(); } diff --git a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestOneMiddleware.cs b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestOneMiddleware.cs index 0100c9f..e6b0fbb 100644 --- a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestOneMiddleware.cs +++ b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestOneMiddleware.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Tests.TestModels.TestMiddleware { @@ -10,16 +9,16 @@ public class TestOneMiddleware : MiddlewareBase public const string PrevMessage = "OnePrev"; private List log; - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { log.Add(NextMessage); - await base.InvokeOnPreUpdateAsync(botClient, update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { log.Add(PrevMessage); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } public TestOneMiddleware(List log) diff --git a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestThreeMiddleware.cs b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestThreeMiddleware.cs index 63af1ea..a118a6c 100644 --- a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestThreeMiddleware.cs +++ b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestThreeMiddleware.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Tests.TestModels.TestMiddleware { @@ -10,16 +9,16 @@ public class TestThreeMiddleware : MiddlewareBase public const string PrevMessage = "ThreePrev"; private List log; - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { log.Add(NextMessage); - await base.InvokeOnPreUpdateAsync(botClient, update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { log.Add(PrevMessage); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } public TestThreeMiddleware(List log) diff --git a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestTwoMiddleware.cs b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestTwoMiddleware.cs index 4d74a84..9f330cf 100644 --- a/PRTelegramBot.Tests/TestModels/TestMiddleware/TestTwoMiddleware.cs +++ b/PRTelegramBot.Tests/TestModels/TestMiddleware/TestTwoMiddleware.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Core.Middlewares; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Tests.TestModels.TestMiddleware { @@ -10,16 +9,16 @@ public class TestTwoMiddleware : MiddlewareBase public const string PrevMessage = "TwoPrev"; private List log; - public override async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public override async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { log.Add(NextMessage); - await base.InvokeOnPreUpdateAsync(botClient, update, next); + await base.InvokeOnPreUpdateAsync(context, next); } - public override Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + public override Task InvokeOnPostUpdateAsync(IBotContext context) { log.Add(PrevMessage); - return base.InvokeOnPostUpdateAsync(botClient, update); + return base.InvokeOnPostUpdateAsync(context); } public TestTwoMiddleware(List log) diff --git a/PRTelegramBot.Tests/UtilsTests/MenuGeneratorTests.cs b/PRTelegramBot.Tests/UtilsTests/MenuGeneratorTests.cs index 3eb760d..23ac7d8 100644 --- a/PRTelegramBot.Tests/UtilsTests/MenuGeneratorTests.cs +++ b/PRTelegramBot.Tests/UtilsTests/MenuGeneratorTests.cs @@ -1,9 +1,4 @@ using PRTelegramBot.Utils; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace PRTelegramBot.Tests.UtilsTests { @@ -13,9 +8,9 @@ internal class MenuGeneratorTests private const string MENU_ITEM = "Menu item"; [Test] - [TestCase(1,"", 1, 1)] - [TestCase(1,"", 2, 2)] - [TestCase(1,"", 6, 6)] + [TestCase(1, "", 1, 1)] + [TestCase(1, "", 2, 2)] + [TestCase(1, "", 6, 6)] [TestCase(2, "", 1, 1)] [TestCase(2, "", 1, 1)] [TestCase(1, MAIN_MENU, 1, 2)] diff --git a/PRTelegramBot/Actions/InlineCalendar.cs b/PRTelegramBot/Actions/InlineCalendar.cs index c77f850..8b8d1af 100644 --- a/PRTelegramBot/Actions/InlineCalendar.cs +++ b/PRTelegramBot/Actions/InlineCalendar.cs @@ -1,14 +1,13 @@ using PRTelegramBot.Attributes; -using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.CallbackCommands; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; using PRTelegramBot.Utils.Controls.CalendarControl.Common; using System.Globalization; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Actions { @@ -23,23 +22,22 @@ public class InlineCalendar /// Действие выбор года или месяца. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.YearMonthPicker)] - public static async Task PickYearMonth(ITelegramBotClient botClient, Update update) + public static async Task PickYearMonth(IBotContext context) { try { - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); - if (command != null) + var command = InlineCallback.GetCommandByCallbackOrNull(context); + if (command is not null) { var monthYearMarkup = Markup.PickMonthYear(command.Data.Date, CultureInfo.GetCultureInfo(command.Data.Culture, false), command.Data.HeaderCallbackCommand); var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = monthYearMarkup; - await Helpers.Message.EditInline(botClient, update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, option); + await Helpers.Message.EditInline(context, context.Update.CallbackQuery.Message.Chat.Id, context.Update.CallbackQuery.Message.MessageId, option); } } catch (Exception ex) { - var bot = botClient.GetBotDataOrNull(); - bot.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(context.Current, ex)); } } @@ -47,25 +45,24 @@ public static async Task PickYearMonth(ITelegramBotClient botClient, Update upda /// Действие выбор месяца. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.PickMonth)] - public static async Task PickMonth(ITelegramBotClient botClient, Update update) + public static async Task PickMonth(IBotContext context) { try { - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); - if (command != null) + var command = InlineCallback.GetCommandByCallbackOrNull(context); + if (command is not null) { var monthPickerMarkup = Markup.PickMonth(command.Data.Date, CultureInfo.GetCultureInfo(command.Data.Culture, false), command.Data.HeaderCallbackCommand); var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = monthPickerMarkup; - await Helpers.Message.EditInline(botClient, update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, option); + await Helpers.Message.EditInline(context, context.Update.CallbackQuery.Message.Chat.Id, context.Update.CallbackQuery.Message.MessageId, option); } } catch (Exception ex) { - var bot = botClient.GetBotDataOrNull(); - bot.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(context.Current, ex)); } } @@ -73,23 +70,22 @@ public static async Task PickMonth(ITelegramBotClient botClient, Update update) /// Действие выбор года. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.PickYear)] - public static async Task PickYear(ITelegramBotClient botClient, Update update) + public static async Task PickYear(IBotContext context) { try { - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); - if (command != null) + var command = InlineCallback.GetCommandByCallbackOrNull(context); + if (command is not null) { var monthYearMarkup = Markup.PickYear(command.Data.Date, CultureInfo.GetCultureInfo(command.Data.Culture, false), command.Data.HeaderCallbackCommand); var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = monthYearMarkup; - await Helpers.Message.EditInline(botClient, update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, option); + await Helpers.Message.EditInline(context, context.Update.CallbackQuery.Message.Chat.Id, context.Update.CallbackQuery.Message.MessageId, option); } } catch (Exception ex) { - var bot = botClient.GetBotDataOrNull(); - bot.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(context.Current, ex)); } } @@ -97,23 +93,22 @@ public static async Task PickYear(ITelegramBotClient botClient, Update update) /// Действие перелистывание месяца. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.ChangeTo)] - public static async Task ChangeToHandler(ITelegramBotClient botClient, Update update) + public static async Task ChangeToHandler(IBotContext context) { try { - var command = InlineCallback.GetCommandByCallbackOrNull(update.CallbackQuery.Data); - if (command != null) + var command = InlineCallback.GetCommandByCallbackOrNull(context); + if (command is not null) { var calendarMarkup = Markup.Calendar(command.Data.Date, CultureInfo.GetCultureInfo(command.Data.Culture, false), command.Data.HeaderCallbackCommand); var option = new OptionMessage(); option.MenuInlineKeyboardMarkup = calendarMarkup; - await Helpers.Message.EditInline(botClient, update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId, option); + await Helpers.Message.EditInline(context, context.Update.CallbackQuery.Message.Chat.Id, context.Update.CallbackQuery.Message.MessageId, option); } } catch (Exception ex) { - var bot = botClient.GetBotDataOrNull(); - bot.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(context.Current, ex)); } } @@ -121,23 +116,23 @@ public static async Task ChangeToHandler(ITelegramBotClient botClient, Update up /// Действие обработка выбраной даты. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.PickDate)] - public static async Task PickDate(ITelegramBotClient botClient, Update update) + public static async Task PickDate(IBotContext context) { - var bot = botClient.GetBotDataOrNull(); + var bot = context.Current; try { - using (var inlineHandler = new InlineCallback(botClient, update)) + using (var inlineHandler = new InlineCallback(context)) { var command = inlineHandler.GetCommandByCallbackOrNull(); command.Data.ActionWithLastMessage = (int)ActionWithLastMessage.Delete; - var callBackHandler = new InlineCallback("", EnumHeaders.Instance.Get(command.Data.HeaderCallbackCommand), command.Data); - update.CallbackQuery.Data = callBackHandler.GetContent() as string; - await botClient.GetBotDataOrNull().Handler.HandleUpdateAsync(botClient, update, bot.Options.CancellationToken.Token); + var callBackHandler = new InlineCallback(string.Empty, EnumHeaders.Instance.Get(command.Data.HeaderCallbackCommand), command.Data); + context.Update.CallbackQuery.Data = callBackHandler.GetContent() as string; + await bot.Handler.HandleUpdateAsync(context.BotClient, context.Update, bot.Options.CancellationTokenSource.Token); } } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, ex)); } } diff --git a/PRTelegramBot/Actions/InlineConfirmation.cs b/PRTelegramBot/Actions/InlineConfirmation.cs index 79e6b7d..8be38d4 100644 --- a/PRTelegramBot/Actions/InlineConfirmation.cs +++ b/PRTelegramBot/Actions/InlineConfirmation.cs @@ -4,10 +4,10 @@ using PRTelegramBot.Models; using PRTelegramBot.Models.CallbackCommands; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Models.InlineButtons; using PRTelegramBot.Utils; using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Actions { @@ -22,11 +22,11 @@ public static class InlineConfirmation /// Обработка подтверждения действия. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.CallbackWithConfirmation)] - public static async Task ActionWithConfirmation(ITelegramBotClient botClient, Update update) + public static async Task ActionWithConfirmation(IBotContext context) { try { - using (var inlineHandler = new InlineCallback>(botClient, update)) + using (var inlineHandler = new InlineCallback>(context)) { var command = inlineHandler.GetCommandByCallbackOrNull(); if (InlineCallbackWithConfirmation.DataCollection.TryGetValue(command.Data.EntityId, out var inlineCommand)) @@ -39,20 +39,20 @@ public static async Task ActionWithConfirmation(ITelegramBotClient botClient, Up var option = new OptionMessage() { MenuInlineKeyboardMarkup = testMenu }; var actionLastMessage = command.Data.GetActionWithLastMessage(); if (command.Data.GetActionWithLastMessage() == ActionWithLastMessage.Edit) - await Helpers.Message.Edit(botClient, update, inlineCommand.BaseMessage, option); + await Helpers.Message.Edit(context, inlineCommand.BaseMessage, option); else - await Helpers.Message.Send(botClient, update, inlineCommand.BaseMessage, option); + await Helpers.Message.Send(context, inlineCommand.BaseMessage, option); } else { string msg = "Ошибка при выполнение команды, попробуйте еще раз."; - await Helpers.Message.Edit(botClient, update, msg); + await Helpers.Message.Edit(context, msg); } } } catch (Exception ex) { - botClient.GetBotDataOrNull().Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); } } @@ -60,15 +60,15 @@ public static async Task ActionWithConfirmation(ITelegramBotClient botClient, Up /// Базовый обработчик при нажатие на нет. /// [InlineCallbackHandler(-1, PRTelegramBotCommand.CallbackWithConfirmationResultNo)] - public static async Task ActionWithConfirmationResultNo(ITelegramBotClient botClient, Update update) + public static async Task ActionWithConfirmationResultNo(IBotContext context) { try { - await botClient.DeleteMessage(update.GetChatIdClass(), update.CallbackQuery.Message.MessageId); + await context.BotClient.DeleteMessage(context.GetChatIdClass(), context.Update.CallbackQuery.Message.MessageId); } catch (Exception ex) { - botClient.GetBotDataOrNull().Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); } } diff --git a/PRTelegramBot/Attributes/BaseQueryAttribute.cs b/PRTelegramBot/Attributes/BaseQueryAttribute.cs index c04dd5c..48883a3 100644 --- a/PRTelegramBot/Attributes/BaseQueryAttribute.cs +++ b/PRTelegramBot/Attributes/BaseQueryAttribute.cs @@ -22,20 +22,17 @@ public abstract class BaseQueryAttribute #region ICommandStore - public IEnumerable Commands - { - get - { - return commands.ToList(); - } - } + /// + public IEnumerable Commands => commands.ToList(); #endregion #region IBaseQueryAttribute + /// public List BotIds { get; set; } = new(); + /// public CommandComparison CommandComparison { get; protected set; } #endregion @@ -50,6 +47,7 @@ public IEnumerable Commands public BaseQueryAttribute(long[] botIds, CommandComparison commandComparison) { BotIds.AddRange(botIds); + this.CommandComparison = commandComparison; } diff --git a/PRTelegramBot/Attributes/ReplyMenuDynamicHandlerAttribute.cs b/PRTelegramBot/Attributes/ReplyMenuDynamicHandlerAttribute.cs index b72456f..5b6326c 100644 --- a/PRTelegramBot/Attributes/ReplyMenuDynamicHandlerAttribute.cs +++ b/PRTelegramBot/Attributes/ReplyMenuDynamicHandlerAttribute.cs @@ -1,5 +1,6 @@ using PRTelegramBot.Core; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; namespace PRTelegramBot.Attributes { @@ -125,7 +126,8 @@ public ReplyMenuDynamicHandlerAttribute(long[] botIds, CommandComparison command { if (!dynamicCommand.ContainsKey(command)) { - bot.Events.OnErrorLogInvoke(new Exception($"Bot with id {bot.BotId} not contains dynamic command {command}")); + var exception = new ArgumentException($"Bot with id {bot.BotId} not contains dynamic command {command}"); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, exception)); continue; } this.commands.Add(dynamicCommand[command]); diff --git a/PRTelegramBot/Attributes/WhiteListAnonymousAttribute.cs b/PRTelegramBot/Attributes/WhiteListAnonymousAttribute.cs index ea96261..dbb98e8 100644 --- a/PRTelegramBot/Attributes/WhiteListAnonymousAttribute.cs +++ b/PRTelegramBot/Attributes/WhiteListAnonymousAttribute.cs @@ -10,6 +10,7 @@ public class WhiteListAnonymousAttribute { #region IBaseQueryAttribute + /// public List BotIds { get; set; } = new(); #endregion diff --git a/PRTelegramBot/CHANGELOG.md b/PRTelegramBot/CHANGELOG.md index 30ffc1a..60f48e6 100644 --- a/PRTelegramBot/CHANGELOG.md +++ b/PRTelegramBot/CHANGELOG.md @@ -1,8 +1,45 @@ +-- 2025.09.15 - V0.8 +- Рефакторинг кода. Так же спасибо за помощь @Harlok13. +- Добавлен IBotContext который хранит в себе: Всех экземпляры ботов системы. Текущий экземпляр бота. Update. BotClient, CurrentUpdateType, CancelationToken. +- Сигнатура методов, команд ...ITelegramBotClient botClient, Update update... заменена на IBotContext context +- Добавлены методы расширений для IBotContext по аналогии с update. Cache, Steps и другие. +- CacheExtension. +-- Добавлен метод GetOrCreate. +-- Поправлен метод CreateCacheData. Теперь при его вызове будет всегда создаваться новый кэш. +- Поправлены примеры ботов. +- Добавлен новый метод расширения для получения идентификатора пользователя GetUserId() +- Документация будет обновлена позже, после слияния с мастером. + + +# Миграции: +## MiddlewareBase: +- InvokeOnPreUpdateAsync(ITelegramBotClient context.BotClient, context.Update update, Func next) -> InvokeOnPreUpdateAsync(IBotContext context, Func next) +- InvokeOnPostUpdateAsync(ITelegramBotClient context.BotClient, context.Update update, Func next) -> InvokeOnPostUpdateAsync(IBotContext context) + +## IExecuteStep и его реализации: +ExecuteStep(ITelegramBotClient context.BotClient, context.Update update) -> ExecuteStep(IBotContext context) + +## PRBotBuilder +- SetIpAddresWebHook(string ipAddress) -> SetIpAddressWebHook(string ipAddress) +- AddRecevingOptions(ReceiverOptions recevierOptions) -> AddReceivingOptions(ReceiverOptions receiverOptions) + +## PRBotWebHook +- GetWebHookInfo(CancellationToken cancellationToken = default) -> GetWebHookInfoAsync(CancellationToken cancellationToken = default) + +## PRBotBase +- Start -> StartAsync +- Stop -> StopAsync + +Методы в вашем коде нужно привести к сигнатуре от (ITelegramBotClient context.BotClient, context.Update update) к (IBotContext context) и поправить другие места в коде куда передавались или брались старые аргументы аргументы. +Примеры: +update -> context.Update +botClient -> context.BotClient + + -- 2025.09.04 - V0.7.12 - Исправлена проверка размера callback_data. Автор @Harlok13 - Telegram.Bot: обновлен до 22.7.2 - -- 2025.08.31 - V0.7.11 - Еще доработки по Di Scope для nextStep. diff --git a/PRTelegramBot/Configs/BotConfigJsonProvider.cs b/PRTelegramBot/Configs/BotConfigJsonProvider.cs index e5da57a..73b191e 100644 --- a/PRTelegramBot/Configs/BotConfigJsonProvider.cs +++ b/PRTelegramBot/Configs/BotConfigJsonProvider.cs @@ -22,6 +22,7 @@ public sealed class BotConfigJsonProvider : IBotConfigProvider #region IBotConfigProvider + /// public void SetConfigPath(string configPath) { this.configPath = configPath; @@ -29,6 +30,7 @@ public void SetConfigPath(string configPath) .AddJsonFile(configPath).Build(); } + /// public TOptions GetOptions() where TOptions : class { @@ -36,17 +38,20 @@ public TOptions GetOptions() return section.Get(); } + /// public TReturn GetValue(string section) { return configuration.GetSection(section).Get(); } + /// public Dictionary GetKeysAndValues() { string json = File.ReadAllText(configPath); return JsonSerializer.Deserialize>(json); } + /// public Dictionary GetKeysAndValuesByOptions() where T : class { diff --git a/PRTelegramBot/Configs/TelegramOptions.cs b/PRTelegramBot/Configs/TelegramOptions.cs index 7cf10e2..aaa81c5 100644 --- a/PRTelegramBot/Configs/TelegramOptions.cs +++ b/PRTelegramBot/Configs/TelegramOptions.cs @@ -17,12 +17,12 @@ public class TelegramOptions /// /// Клиент телеграма. /// - public TelegramBotClient? Client { get; set; } + public ITelegramBotClient? Client { get; set; } /// /// Токен telegram бота. /// - public string Token { get; set; } + public string Token { get; set; } = null!; /// /// Перед запуском очищает список обновлений, которые накопились когда бот не работал. @@ -30,7 +30,7 @@ public class TelegramOptions public bool ClearUpdatesOnStart { get; set; } /// - /// Уникальных идентификатор для бота, используется, чтобы в одном приложение запускать несколько ботов. + /// Уникальный идентификатор для бота, используется, чтобы в одном приложение запускать несколько ботов. /// public long BotId { get; set; } @@ -45,9 +45,9 @@ public class TelegramOptions public Dictionary ConfigPaths { get; set; } = new(); /// - /// Токен отмены. + /// Источник токена отмены. /// - public CancellationTokenSource CancellationToken { get; set; } = new CancellationTokenSource(); + public CancellationTokenSource CancellationTokenSource { get; set; } = new(); /// /// Настройки telegram бота. @@ -57,12 +57,12 @@ public class TelegramOptions /// /// Сервис провайдер. /// - public IServiceProvider ServiceProvider { get; set; } + public IServiceProvider? ServiceProvider { get; set; } /// /// Обработчик обновлений Telegram. /// - public IPRUpdateHandler UpdateHandler { get; set; } + public IPRUpdateHandler? UpdateHandler { get; set; } /// /// Менеджер управления администраторами. @@ -77,12 +77,12 @@ public class TelegramOptions /// /// Промежуточные обработчики перед update. /// - public List Middlewares { get; set; } = new(); + public List Middlewares { get; set; } = []; /// /// Дополнительные проверки перед обработкой команд. /// - public List CommandCheckers { get; set; } = new(); + public List CommandCheckers { get; set; } = []; /// /// Таймаут для получения update в режиме polling. @@ -90,29 +90,29 @@ public class TelegramOptions public int? Timeout { get; set; } /// - /// Обработчики callbackquery (inline) команд. + /// Обработчики callbackQuery (inline) команд. /// - public List CallbackQueryHandlers { get; set; } = new(); + public List CallbackQueryHandlers { get; set; } = []; /// /// Обработчики для message. /// - public List MessageHandlers { get; set; } = new(); - - /// - /// Параметры для webhook. - /// - public WebHookOptions WebHookOptions = new WebHookOptions(); + public List MessageHandlers { get; set; } = []; /// /// Параметр предотвращает спам об ошибке, если пропала сеть. По умолчанию значение 1 минута, можно поменять. /// public int AntiSpamErrorMinute { get; set; } = 1; + + /// + /// Параметры для webhook. + /// + public readonly WebHookOptions WebHookOptions = new(); /// /// Параметры команд. /// - public CommandOptions CommandOptions = new CommandOptions(); + public readonly CommandOptions CommandOptions = new(); #endregion } diff --git a/PRTelegramBot/Converters/CustomEnumConverter.cs b/PRTelegramBot/Converters/CustomEnumConverter.cs index 7a43cbb..28111ed 100644 --- a/PRTelegramBot/Converters/CustomEnumConverter.cs +++ b/PRTelegramBot/Converters/CustomEnumConverter.cs @@ -11,6 +11,7 @@ public sealed class HeaderConverter : JsonConverter { #region Базовый класс + /// public override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // Обработка десериализации JSON в тип Enum @@ -25,15 +26,17 @@ public override Enum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSer } } + /// public override void Write(Utf8JsonWriter writer, Enum value, JsonSerializerOptions options) { // Обработка сериализации типа Enum в JSON - if (value != null) + if (value is not null) writer.WriteNumberValue(EnumHeaders.Instance.Get(value)); else writer.WriteNullValue(); } + /// public override bool CanConvert(Type typeToConvert) { return true; diff --git a/PRTelegramBot/Converters/DateOnlyConverter.cs b/PRTelegramBot/Converters/DateOnlyConverter.cs index 4589706..36fffe3 100644 --- a/PRTelegramBot/Converters/DateOnlyConverter.cs +++ b/PRTelegramBot/Converters/DateOnlyConverter.cs @@ -17,11 +17,13 @@ public class DateOnlyConverter : JsonConverter #region Базовый класс + /// public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.Parse(reader.GetString()).Date; } + /// public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString(DATE_FORMAT)); diff --git a/PRTelegramBot/Core/BotCollection.cs b/PRTelegramBot/Core/BotCollection.cs index c38f52d..50c8160 100644 --- a/PRTelegramBot/Core/BotCollection.cs +++ b/PRTelegramBot/Core/BotCollection.cs @@ -10,30 +10,22 @@ public sealed class BotCollection /// /// Экземпляр класса. /// - private static BotCollection instance; + private static BotCollection? instance; /// /// Коллекция ботов. /// - private Dictionary BotList = new Dictionary(); + private Dictionary botList = new(); /// /// Количество ботов. /// - public long BotCount => BotList.Count; + public long BotCount => botList.Count; /// /// Singleton экземпляр. /// - public static BotCollection Instance - { - get - { - if (instance == null) - instance = new BotCollection(); - return instance; - } - } + public static BotCollection Instance => instance ??= new BotCollection(); #endregion @@ -44,35 +36,35 @@ public static BotCollection Instance /// /// Идентификатор бота. public static long GetNextId() - => Instance.BotList.LastOrDefault().Key + 1; + => Instance.botList.LastOrDefault().Key + 1; /// /// Добавить бота в коллекцию. /// /// Бот. public void AddBot(PRBotBase bot) - => BotList.Add(bot.BotId, bot); + => botList.Add(bot.BotId, bot); /// /// Удалить бота из коллекции. /// /// Бот. public void RemoveBot(PRBotBase bot) - => BotList.Remove(bot.BotId); + => botList.Remove(bot.BotId); /// /// Очистить всех ботов. /// public void ClearBots() - => BotList.Clear(); + => botList.Clear(); /// /// Получить бота по telegram id. /// /// Идентификатор telegram. /// Экземпляр класса бота или null. - public PRBotBase GetBotByTelegramIdOrNull(long? telegramId) - => BotList.Values.SingleOrDefault(x => x.TelegramId == telegramId); + public PRBotBase? GetBotByTelegramIdOrNull(long? telegramId) + => botList.Values.SingleOrDefault(x => x.TelegramId == telegramId); /// /// Получить экземпляр бота. @@ -80,22 +72,22 @@ public PRBotBase GetBotByTelegramIdOrNull(long? telegramId) /// Идентификатор бота. /// Экземпляр класса бота или null. public PRBotBase GetBotOrNull(long botId) - => BotList.Values.SingleOrDefault(x => x.BotId == botId); + => botList.Values.SingleOrDefault(x => x.BotId == botId); /// /// Получить экземпляр бота. /// /// Выражение для фильтрации. /// Экземпляр класса бота или null. - public PRBotBase GetBotOrNull(Func predicate) - => BotList.Values.SingleOrDefault(predicate); + public PRBotBase? GetBotOrNull(Func predicate) + => botList.Values.SingleOrDefault(predicate); /// /// Получить всех ботов. /// /// Коллекция ботов. public List GetBots() - => BotList.Select(x => x.Value).ToList(); + => botList.Select(x => x.Value).ToList(); /// /// Получить всех ботов. @@ -103,15 +95,15 @@ public List GetBots() /// Выражение для фильтрации. /// Коллекция ботов. public List GetBots(Func predicate) - => BotList.Values.Where(predicate).ToList(); + => botList.Values.Where(predicate).ToList(); /// /// Получить экземпляр бота. /// /// Название/логин бота. /// Экземпляр класса бота или null. - public PRBotBase GetBotOrNull(string botName) - => BotList.Values.SingleOrDefault(x => x.BotName.Contains(botName, StringComparison.OrdinalIgnoreCase)); + public PRBotBase? GetBotOrNull(string botName) + => botList.Values.SingleOrDefault(x => x.BotName.Contains(botName, StringComparison.OrdinalIgnoreCase)); #endregion diff --git a/PRTelegramBot/Core/CommandHandlers/InlineClassInstanceHandler.cs b/PRTelegramBot/Core/CommandHandlers/InlineClassInstanceHandler.cs index 7ff2623..b356029 100644 --- a/PRTelegramBot/Core/CommandHandlers/InlineClassInstanceHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/InlineClassInstanceHandler.cs @@ -9,13 +9,14 @@ internal class InlineClassInstanceHandler : ICallbackQueryCommandHandler { #region ICallbackQueryCommandHandler - public async Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + /// + public async Task Handle(IBotContext context, CallbackQuery updateType) { - foreach (var handler in bot.InlineClassHandlerInstances) + foreach (var handler in context.Current.InlineClassHandlerInstances) { var command = InlineCallback.GetCommandByCallbackOrNull(updateType.Data); - if (command != null && Convert.ToInt32(command.CommandType) == Convert.ToInt32(handler.Key)) - return await handler.Value.Handle(bot, update, updateType); + if (command is not null && Convert.ToInt32(command.CommandType) == Convert.ToInt32(handler.Key)) + return await handler.Value.Handle(context, updateType); } return UpdateResult.Continue; diff --git a/PRTelegramBot/Core/CommandHandlers/InlineCommandHandler.cs b/PRTelegramBot/Core/CommandHandlers/InlineCommandHandler.cs index df16508..52dd976 100644 --- a/PRTelegramBot/Core/CommandHandlers/InlineCommandHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/InlineCommandHandler.cs @@ -1,7 +1,7 @@ using PRTelegramBot.Core.Executors; +using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; -using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Models.InlineButtons; using Telegram.Bot.Types; @@ -9,21 +9,22 @@ namespace PRTelegramBot.Core.CommandHandlers { internal class InlineCommandHandler : ICallbackQueryCommandHandler { - public async Task Handle(PRBotBase bot, Update update, CallbackQuery updateType) + /// + public async Task Handle(IBotContext context, CallbackQuery updateType) { var command = InlineCallback.GetCommandByCallbackOrNull(updateType.Data); - if (command != null) + if (command is not null) { - bot.Events.CommandsEvents.OnPreInlineCommandHandleInvoke(new BotEventArgs(bot, update)); - var executer = new ExecutorCallbackQueryCommand(bot); - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + context.Current.Events.CommandsEvents.OnPreInlineCommandHandleInvoke(context.CreateBotEventArgs()); + var executer = new ExecutorCallbackQueryCommand(context.Current); + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return UpdateResult.Continue; - var resultExecute = await executer.Execute(command.CommandType, update, currentHandler.CallbackQueryCommandsStore.Commands); + var resultExecute = await executer.Execute(command.CommandType, context, currentHandler.CallbackQueryCommandsStore.Commands); if (resultExecute == CommandResult.Executed) { - bot.Events.CommandsEvents.OnPostInlineCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPostInlineCommandHandleInvoke(context.CreateBotEventArgs()); return UpdateResult.Handled; } } diff --git a/PRTelegramBot/Core/CommandHandlers/NextStepCommandHandler.cs b/PRTelegramBot/Core/CommandHandlers/NextStepCommandHandler.cs index cf65e18..cde839f 100644 --- a/PRTelegramBot/Core/CommandHandlers/NextStepCommandHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/NextStepCommandHandler.cs @@ -1,5 +1,6 @@ using PRTelegramBot.Core.Executors; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; @@ -12,45 +13,41 @@ namespace PRTelegramBot.Core.CommandHandlers /// internal sealed class NextStepCommandHandler { - #region Поля и свойства + #region Методы /// - /// Бот. + /// Обработать следующий шаг. /// - private readonly PRBotBase bot; - - #endregion - - #region Методы - - public async Task Handle(PRBotBase bot, Update update) + /// Контекст бота. + /// Результат обработки. + public async Task Handle(IBotContext context) { try { - if (!update.HasStepHandler()) + if (!context.Update.HasStepHandler()) return UpdateResult.Continue; - var step = update.GetStepHandler()?.GetExecuteMethod(); + var step = context.Update.GetStepHandler()?.GetExecuteMethod(); if (step is null) return UpdateResult.NotFound; - if(!update.GetStepHandler()!.CanExecute()) + if(!context.Update.GetStepHandler()!.CanExecute()) { - update.ClearStepUserHandler(); + context.Update.ClearStepUserHandler(); return UpdateResult.Continue; } - bot.Events.CommandsEvents.OnPreNextStepCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPreNextStepCommandHandleInvoke(context.CreateBotEventArgs()); - var executer = new ExecutorNextStepCommand(bot); - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + var executer = new ExecutorNextStepCommand(context.Current); + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return UpdateResult.Continue; - var resultExecute = await executer.ExecuteMethod(bot, update, new CommandHandler(step, bot.Options.ServiceProvider)); + var resultExecute = await executer.ExecuteMethod(context, new CommandHandler(step, context.Current.Options.ServiceProvider)); if (resultExecute == CommandResult.Executed) { - bot.Events.CommandsEvents.OnPostNextStepCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPostNextStepCommandHandleInvoke(context.CreateBotEventArgs()); return UpdateResult.Handled; } @@ -58,7 +55,7 @@ public async Task Handle(PRBotBase bot, Update update) } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex, update); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); return UpdateResult.Error; } } @@ -66,14 +63,14 @@ public async Task Handle(PRBotBase bot, Update update) /// /// Игнорировать базовые команды. /// - /// Обновление. + /// Контекст бота. /// True - игнорировать основные команды, False - не игнорировать. - public bool IgnoreBasicCommand(Update update) + public bool IgnoreBasicCommand(IBotContext context) { - if (!update.HasStepHandler()) + if (!context.Update.HasStepHandler()) return false; - return update?.GetStepHandler()?.IgnoreBasicCommands ?? false; + return context.Update?.GetStepHandler()?.IgnoreBasicCommands ?? false; } /// @@ -108,11 +105,7 @@ public void ClearSteps(Update update) /// /// Конструктор. /// - /// Бот. - public NextStepCommandHandler(PRBotBase bot) - { - this.bot = bot; - } + public NextStepCommandHandler() { } #endregion } diff --git a/PRTelegramBot/Core/CommandHandlers/ReplyCommandHandler.cs b/PRTelegramBot/Core/CommandHandlers/ReplyCommandHandler.cs index 8594457..49bc9ac 100644 --- a/PRTelegramBot/Core/CommandHandlers/ReplyCommandHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/ReplyCommandHandler.cs @@ -1,42 +1,47 @@ using PRTelegramBot.Core.Executors; +using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; -using PRTelegramBot.Models.EventsArgs; using Telegram.Bot.Types; namespace PRTelegramBot.Core.CommandHandlers { internal class ReplyCommandHandler : IMessageCommandHandler { - public async Task Handle(PRBotBase bot, Update update, Message updateType) + #region IMessageCommandHandler + + /// + public async Task Handle(IBotContext context, Message updateType) { string command = updateType.Text; RemoveBracketsIfExists(ref command); - bot.Events.CommandsEvents.OnPreReplyCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPreReplyCommandHandleInvoke(context.CreateBotEventArgs()); - var executer = new ExecutorReplyCommand(bot); - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + var executer = new ExecutorReplyCommand(context.Current); + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return UpdateResult.Continue; - var resultExecute = await executer.Execute(command, update, GetCommands(bot)); + var resultExecute = await executer.Execute(command, context, GetCommands(context)); if (resultExecute != CommandResult.Continue) { - bot.Events.CommandsEvents.OnPostReplyCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPostReplyCommandHandleInvoke(context.CreateBotEventArgs()); return UpdateResult.Handled; } return UpdateResult.Continue; } - protected virtual Dictionary GetCommands(PRBotBase bot) + protected virtual Dictionary GetCommands(IBotContext context) { - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return new(); return currentHandler.ReplyCommandsStore.Commands; - } + } + + #endregion #region Методы diff --git a/PRTelegramBot/Core/CommandHandlers/ReplyDynamicCommandHandler.cs b/PRTelegramBot/Core/CommandHandlers/ReplyDynamicCommandHandler.cs index 23f7575..27e65c5 100644 --- a/PRTelegramBot/Core/CommandHandlers/ReplyDynamicCommandHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/ReplyDynamicCommandHandler.cs @@ -5,13 +5,18 @@ namespace PRTelegramBot.Core.CommandHandlers { internal class ReplyDynamicCommandHandler : ReplyCommandHandler, IMessageCommandHandler { - protected override Dictionary GetCommands(PRBotBase bot) + #region Базовый класс + + /// + protected override Dictionary GetCommands(IBotContext context) { - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return new(); return currentHandler.ReplyDynamicCommandsStore.Commands; } + + #endregion } } diff --git a/PRTelegramBot/Core/CommandHandlers/SlashCommandHandler.cs b/PRTelegramBot/Core/CommandHandlers/SlashCommandHandler.cs index 802f3b9..62edf28 100644 --- a/PRTelegramBot/Core/CommandHandlers/SlashCommandHandler.cs +++ b/PRTelegramBot/Core/CommandHandlers/SlashCommandHandler.cs @@ -1,4 +1,5 @@ using PRTelegramBot.Core.Executors; +using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; @@ -8,42 +9,47 @@ namespace PRTelegramBot.Core.CommandHandlers { internal class SlashCommandHandler : IMessageCommandHandler { - public async Task Handle(PRBotBase bot, Update update, Message updateType) + #region IMessageCommandHandler + + /// + public async Task Handle(IBotContext context, Message updateType) { - string command = update.Message.Text; + string command = context.Update.Message.Text; if (command.StartsWith('/')) { - var resultExecute = StartHasDeepLink(bot, command, update); + var resultExecute = StartHasDeepLink(context, command); if (resultExecute == CommandResult.Executed) return UpdateResult.Handled; - bot.Events.CommandsEvents.OnPreSlashCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPreSlashCommandHandleInvoke(context.CreateBotEventArgs()); - var executer = new ExecutorSlashCommand(bot); - var currentHandler = bot.Handler as Handler; - if (currentHandler == null) + var executer = new ExecutorSlashCommand(context.Current); + var currentHandler = context.Current.Handler as Handler; + if (currentHandler is null) return UpdateResult.Continue; - resultExecute = await executer.Execute(command, update, currentHandler.SlashCommandsStore.Commands); + resultExecute = await executer.Execute(command, context, currentHandler.SlashCommandsStore.Commands); if (resultExecute != CommandResult.Continue) { - bot.Events.CommandsEvents.OnPostSlashCommandHandleInvoke(new BotEventArgs(bot, update)); + context.Current.Events.CommandsEvents.OnPostSlashCommandHandleInvoke(context.CreateBotEventArgs()); return UpdateResult.Handled; } } return UpdateResult.Continue; } + #endregion + #region Методы /// /// Проверка является ли команда start с аргументом. /// + /// Контекст бота. /// Команда. - /// Обновление. /// Результат выполнение команд. - private CommandResult StartHasDeepLink(PRBotBase bot, string command, Update update) + private CommandResult StartHasDeepLink(IBotContext context, string command) { try { @@ -54,12 +60,12 @@ private CommandResult StartHasDeepLink(PRBotBase bot, string command, Update upd if (spl.Length < 2 || string.IsNullOrEmpty(spl[1])) return CommandResult.Continue; - bot.Events.OnUserStartWithArgsInvoke(new StartEventArgs(bot, update, spl[1])); + context.Current.Events.OnUserStartWithArgsInvoke(new StartEventArgs(context, spl[1])); return CommandResult.Executed; } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex, update); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); return CommandResult.Error; } } diff --git a/PRTelegramBot/Core/CommandStores/BaseCommandStore.cs b/PRTelegramBot/Core/CommandStores/BaseCommandStore.cs index 42f0afe..0823f32 100644 --- a/PRTelegramBot/Core/CommandStores/BaseCommandStore.cs +++ b/PRTelegramBot/Core/CommandStores/BaseCommandStore.cs @@ -1,7 +1,6 @@ -using PRTelegramBot.Models; +using PRTelegramBot.Interfaces; +using PRTelegramBot.Models; using PRTelegramBot.Registrars; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.CommandStores { @@ -10,6 +9,7 @@ namespace PRTelegramBot.Core.CommandStores /// /// Тип ключа для команды. public abstract class BaseCommandStore + where TKey : notnull { #region Поля и свойства @@ -54,9 +54,9 @@ public void ClearCommands() /// Добавить новую команду. /// /// Команда. - /// Метод обработки команды.Метод обработки команды. /// True - команда добавлена, False - не удалось добавить команду. - public abstract bool AddCommand(TKey command, Func @delegate); + public abstract bool AddCommand(TKey command, Func @delegate); /// /// Удалить команду. diff --git a/PRTelegramBot/Core/CommandStores/CallbackQueryCommandStore.cs b/PRTelegramBot/Core/CommandStores/CallbackQueryCommandStore.cs index 8a36f35..7004363 100644 --- a/PRTelegramBot/Core/CommandStores/CallbackQueryCommandStore.cs +++ b/PRTelegramBot/Core/CommandStores/CallbackQueryCommandStore.cs @@ -1,14 +1,14 @@ using PRTelegramBot.Attributes; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Utils; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.CommandStores { /// - /// Хранилище callbackquery команд. + /// Хранилище callbackQuery команд. /// public sealed class CallbackQueryCommandStore : BaseCommandStore { @@ -37,7 +37,7 @@ public override void RegisterCommand() /// Команда. /// Метод обработки команды.True - команда добавлена, False - не удалось добавить команду. - public override bool AddCommand(Enum command, Func @delegate) + public override bool AddCommand(Enum command, Func @delegate) { try { @@ -47,7 +47,7 @@ public override bool AddCommand(Enum command, Func /// Добавить новую команду. /// /// Команда. - /// Метод обработки команды.Метод обработки команды. /// True - команда добавлена, False - не удалось добавить команду. - public override bool AddCommand(string command, Func @delegate) + public override bool AddCommand(string command, Func @delegate) { try { @@ -26,7 +26,7 @@ public override bool AddCommand(string command, FuncКоманда. /// Метод обработки команды.True - команда добавлена, False - не удалось добавить команду. - public override bool AddCommand(string command, Func @delegate) + public override bool AddCommand(string command, Func @delegate) { if (!command.StartsWith('/')) command = "/" + command; diff --git a/PRTelegramBot/Core/Events/CommandsEvents.cs b/PRTelegramBot/Core/Events/CommandsEvents.cs index d669877..c76d848 100644 --- a/PRTelegramBot/Core/Events/CommandsEvents.cs +++ b/PRTelegramBot/Core/Events/CommandsEvents.cs @@ -63,24 +63,64 @@ public sealed class CommandsEvents #region Методы + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPreReplyCommandHandleInvoke(BotEventArgs e) => OnPreReplyCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPostReplyCommandHandleInvoke(BotEventArgs e) => OnPostReplyCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPreDynamicReplyCommandHandleInvoke(BotEventArgs e) => OnPreDynamicReplyCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPostDynamicReplyCommandHandleInvoke(BotEventArgs e) => OnPostDynamicReplyCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPreSlashCommandHandleInvoke(BotEventArgs e) => OnPreSlashCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPostSlashCommandHandleInvoke(BotEventArgs e) => OnPostSlashCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPreInlineCommandHandleInvoke(BotEventArgs e) => OnPreInlineCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPostInlineCommandHandleInvoke(BotEventArgs e) => OnPostInlineCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPreNextStepCommandHandleInvoke(BotEventArgs e) => OnPreNextStepCommandHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnPostNextStepCommandHandleInvoke(BotEventArgs e) => OnPostNextStepCommandHandle?.Invoke(e); #endregion diff --git a/PRTelegramBot/Core/Events/MessageEvents.cs b/PRTelegramBot/Core/Events/MessageEvents.cs index ca52fa0..7be9fb7 100644 --- a/PRTelegramBot/Core/Events/MessageEvents.cs +++ b/PRTelegramBot/Core/Events/MessageEvents.cs @@ -283,112 +283,274 @@ public sealed class MessageEvents #region Методы + /// + /// Вызвать событие . + /// internal void OnContactHandleInvoke(BotEventArgs e) => OnContactHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnAudioHandleInvoke(BotEventArgs e) => OnAudioHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnLocationHandleInvoke(BotEventArgs e) => OnLocationHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnDiceHandleInvoke(BotEventArgs e) => OnDiceHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnDocumentHandleInvoke(BotEventArgs e) => OnDocumentHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnWebAppsHandleInvoke(BotEventArgs e) => OnWebAppsHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnPollHandleInvoke(BotEventArgs e) => OnPollHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGameHandleInvoke(BotEventArgs e) => OnGameHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoHandleInvoke(BotEventArgs e) => OnVideoHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnPhotoHandleInvoke(BotEventArgs e) => OnPhotoHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnStickerHandleInvoke(BotEventArgs e) => OnStickerHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVoiceHandleInvoke(BotEventArgs e) => OnVoiceHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVenueHandleInvoke(BotEventArgs e) => OnVenueHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnUnknownHandleInvoke(BotEventArgs e) => OnUnknownHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoNoteHandleInvoke(BotEventArgs e) => OnVideoNoteHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnAnimationHandleInvoke(BotEventArgs e) => OnAnimationHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChannelCreatedHandleInvoke(BotEventArgs e) => OnChannelCreatedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatMemberLeftHandleInvoke(BotEventArgs e) => OnChatMemberLeftHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatMembersAddedHandleInvoke(BotEventArgs e) => OnChatMembersAddedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatPhotoChangedHandleInvoke(BotEventArgs e) => OnChatPhotoChangedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatPhotoDeletedHandleInvoke(BotEventArgs e) => OnChatPhotoDeletedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatSharedHandleInvoke(BotEventArgs e) => OnChatSharedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatTitleChangedHandleInvoke(BotEventArgs e) => OnChatTitleChangedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnForumTopicClosedHandleInvoke(BotEventArgs e) => OnForumTopicClosedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnForumTopicCreatedHandleInvoke(BotEventArgs e) => OnForumTopicCreatedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnForumTopicEditedHandleInvoke(BotEventArgs e) => OnForumTopicEditedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnForumTopicReopenedHandleInvoke(BotEventArgs e) => OnForumTopicReopenedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGeneralForumTopicHiddenHandleInvoke(BotEventArgs e) => OnGeneralForumTopicHiddenHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGeneralForumTopicUnhiddenHandleInvoke(BotEventArgs e) => OnGeneralForumTopicUnhiddenHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGroupCreatedHandleInvoke(BotEventArgs e) => OnGroupCreatedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnInvoiceHandleInvoke(BotEventArgs e) => OnInvoiceHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnMessageAutoDeleteTimerChangedHandleInvoke(BotEventArgs e) => OnMessageAutoDeleteTimerChangedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnMessagePinnedHandleInvoke(BotEventArgs e) => OnMessagePinnedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnMigratedFromGroupHandleInvoke(BotEventArgs e) => OnMigratedFromGroupHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnMigratedToSupergroupHandleInvoke(BotEventArgs e) => OnMigratedToSupergroupHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnSuccessfulPaymentHandleInvoke(BotEventArgs e) => OnSuccessfulPaymentHandle?.Invoke(e); - + + /// + /// Вызвать событие . + /// internal void OnSupergroupCreatedHandleInvoke(BotEventArgs e) => OnSupergroupCreatedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnUserSharedHandleInvoke(BotEventArgs e) => OnUserSharedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoChatEndedHandleInvoke(BotEventArgs e) => OnVideoChatEndedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoChatParticipantsInvitedHandleInvoke(BotEventArgs e) => OnVideoChatParticipantsInvitedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoChatScheduledHandleInvoke(BotEventArgs e) => OnVideoChatScheduledHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnVideoChatStartedHandleInvoke(BotEventArgs e) => OnVideoChatStartedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnWebsiteConnectedHandleInvoke(BotEventArgs e) => OnWebsiteConnectedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnWriteAccessAllowedInvoke(BotEventArgs e) => OnWriteAccessAllowedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnProximityAlertTriggeredHandleInvoke(BotEventArgs e) => OnProximityAlertTriggeredHandle?.Invoke(e); - + + /// + /// Вызвать событие . + /// internal void OnGiveawayHandleInvoke(BotEventArgs e) => OnGiveawayHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGiveawayWinnersHandleInvoke(BotEventArgs e) => OnGiveawayWinnersHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGiveawayCompletedHandleInvoke(BotEventArgs e) => OnGiveawayCompletedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnBoostAddedHandleInvoke(BotEventArgs e) => OnBoostAddedHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnChatBackgroundSetHandleInvoke(BotEventArgs e) => OnChatBackgroundSetHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnTextHandleInvoke(BotEventArgs e) => OnTextHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnStoryHandleInvoke(BotEventArgs e) => OnStoryHandle?.Invoke(e); - internal void OnPassportDataHandleInvoke(BotEventArgs e) => OnPassportDataHandle?.Invoke(e); + /// + /// Вызвать событие . + /// + internal void OnPassportDataHandleInvoke(BotEventArgs e) => OnPassportDataHandle?.Invoke(e); + /// + /// Вызвать событие . + /// internal void OnGiveawayCreatedHandleInvoke(BotEventArgs e) => OnGiveawayCreatedHandle?.Invoke(e); #endregion diff --git a/PRTelegramBot/Core/Events/TEvents.cs b/PRTelegramBot/Core/Events/TEvents.cs index bbf386b..d3852ce 100644 --- a/PRTelegramBot/Core/Events/TEvents.cs +++ b/PRTelegramBot/Core/Events/TEvents.cs @@ -1,5 +1,5 @@ -using PRTelegramBot.Models.EventsArgs; -using Telegram.Bot.Types; +using PRTelegramBot.Models; +using PRTelegramBot.Models.EventsArgs; namespace PRTelegramBot.Core.Events { @@ -83,39 +83,111 @@ public sealed class TEvents #region Методы + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnUserStartWithArgsInvoke(StartEventArgs e) => OnUserStartWithArgs?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnMissingCommandInvoke(BotEventArgs e) => OnMissingCommand?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnErrorCommandInvoke(BotEventArgs e) => OnErrorCommand?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnAccessDeniedInvoke(BotEventArgs e) => OnAccessDenied?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnCheckPrivilegeInvoke(PrivilegeEventArgs e) => OnCheckPrivilege?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnWrongTypeMessageInvoke(BotEventArgs e) => OnWrongTypeMessage?.Invoke(e); + /// + /// Вызвать событие . + /// + /// Аргументы события. internal void OnWrongTypeChatInvoke(BotEventArgs e) => OnWrongTypeChat?.Invoke(e); - internal void OnErrorLogInvoke(ErrorLogEventArgsCreator e) => OnErrorLog?.Invoke(new ErrorLogEventArgs(Bot, e)); - - public void OnErrorLogInvoke(Exception exception, Update update) => OnErrorLogInvoke(new ErrorLogEventArgsCreator(exception, update)); - - public void OnErrorLogInvoke(Exception exception) => OnErrorLogInvoke(new ErrorLogEventArgsCreator(exception)); + /// + /// Вызвать событие . + /// + /// Аргументы события. + public void OnErrorLogInvoke(ErrorLogEventArgs e) => OnErrorLog?.Invoke(e); - public void OnCommonLogInvoke(CommonLogEventArgsCreator e) => OnCommonLog?.Invoke(new CommonLogEventArgs(Bot, e)); + /// + /// Вызвать событие через готовый объект аргументов. + /// + /// Создатель аргументов события. + public void OnCommonLogInvoke(CommonLogEventArgsCreator e) => + OnCommonLog?.Invoke(new CommonLogEventArgs(e.Context, e)); - public void OnCommonLogInvoke(string message) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, "Common")); + /// + /// Вызвать событие с простым сообщением. + /// + /// Текст сообщения. + public void OnCommonLogInvoke(string message) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, "Common")); - public void OnCommonLogInvoke(string message, string type) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type)); + /// + /// Вызвать событие с указанием типа лога. + /// + /// Текст сообщения. + /// Тип лога. + public void OnCommonLogInvoke(string message, string type) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type)); - public void OnCommonLogInvoke(string message, string type, Update update) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, update)); + /// + /// Вызвать событие с контекстом бота. + /// + /// Текст сообщения. + /// Тип лога. + /// Контекст бота. + public void OnCommonLogInvoke(string message, string type, BotContext context) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, context)); - public void OnCommonLogInvoke(string message, string type, ConsoleColor color) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, color)); + /// + /// Вызвать событие с цветом текста. + /// + /// Текст сообщения. + /// Тип лога. + /// Цвет текста в консоли. + public void OnCommonLogInvoke(string message, string type, ConsoleColor color) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, color)); - public void OnCommonLogInvoke(string message, string type, ConsoleColor color, Update update) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, color, update)); + /// + /// Вызвать событие с цветом текста и контекстом бота. + /// + /// Текст сообщения. + /// Тип лога. + /// Цвет текста в консоли. + /// Контекст бота. + public void OnCommonLogInvoke(string message, string type, ConsoleColor color, BotContext context) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type, color, context)); - public void OnCommonLogInvokeInvoke(string message, string type) => OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type)); + /// + /// Дополнительный метод вызова с типом лога. + /// + /// Текст сообщения. + /// Тип лога. + public void OnCommonLogInvokeInvoke(string message, string type) => + OnCommonLogInvoke(new CommonLogEventArgsCreator(message, type)); #endregion diff --git a/PRTelegramBot/Core/Events/UpdateEvents.cs b/PRTelegramBot/Core/Events/UpdateEvents.cs index 9622a4a..7bcc5fa 100644 --- a/PRTelegramBot/Core/Events/UpdateEvents.cs +++ b/PRTelegramBot/Core/Events/UpdateEvents.cs @@ -129,6 +129,10 @@ public sealed class UpdateEvents #region Методы + /// + /// Вызвать событие и получить результат продолжения/остановки обработки. + /// + /// Аргументы события. internal async Task OnPreInvoke(BotEventArgs e) { if (HasEventOnPreUpdate()) @@ -137,50 +141,75 @@ internal async Task OnPreInvoke(BotEventArgs e) return UpdateResult.Continue; } - internal bool HasEventOnPreUpdate() => OnPreUpdate != null; + /// + /// Проверить наличие подписчиков на . + /// + internal bool HasEventOnPreUpdate() => OnPreUpdate is not null; + /// Вызвать событие . internal void OnPostInvoke(BotEventArgs e) => OnPostUpdate?.Invoke(e); + /// Вызвать событие . internal void OnChannelPostHandler(BotEventArgs e) => OnChannelPostHandle?.Invoke(e); + /// Вызвать событие . internal void OnChatJoinRequestHandler(BotEventArgs e) => OnChatJoinRequestHandle?.Invoke(e); + /// Вызвать событие . internal void OnChatMemberHandler(BotEventArgs e) => OnChatMemberHandle?.Invoke(e); + /// Вызвать событие . internal void OnChosenInlineResultHandler(BotEventArgs e) => OnChosenInlineResultHandle?.Invoke(e); + /// Вызвать событие . internal void OnEditedChannelPostHandler(BotEventArgs e) => OnEditedChannelPostHandle?.Invoke(e); + /// Вызвать событие . internal void OnEditedMessageHandler(BotEventArgs e) => OnEditedMessageHandle?.Invoke(e); + /// Вызвать событие . internal void OnInlineQueryHandler(BotEventArgs e) => OnInlineQueryHandle?.Invoke(e); + /// Вызвать событие . internal void OnMyChatMemberHandler(BotEventArgs e) => OnMyChatMemberHandle?.Invoke(e); + /// Вызвать событие . internal void OnPollHandler(BotEventArgs e) => OnPollHandle?.Invoke(e); + /// Вызвать событие . internal void OnPollAnswerHandler(BotEventArgs e) => OnPollAnswerHandle?.Invoke(e); + /// Вызвать событие . internal void OnPreCheckoutQueryHandler(BotEventArgs e) => OnPreCheckoutQueryHandle?.Invoke(e); + /// Вызвать событие . internal void OnShippingQueryHandler(BotEventArgs e) => OnShippingQueryHandle?.Invoke(e); + /// Вызвать событие . internal void OnUnknownHandler(BotEventArgs e) => OnUnknownHandle?.Invoke(e); + /// Вызвать событие . internal void OnBusinessConnectionHandler(BotEventArgs e) => OnBusinessConnectionHandle?.Invoke(e); + /// Вызвать событие . internal void OnEditedBusinessHandler(BotEventArgs e) => OnEditedBusinessMessageHandle?.Invoke(e); + /// Вызвать событие . internal void OnDeletedBusinessConnectionHandler(BotEventArgs e) => OnDeletedBusinessMessagesHandle?.Invoke(e); + /// Вызвать событие . internal void OnMessageReactionHandleHandler(BotEventArgs e) => OnMessageReactionHandle?.Invoke(e); + /// Вызвать событие . internal void OnMessageReactionCountHandleHandler(BotEventArgs e) => OnMessageReactionCountHandle?.Invoke(e); + /// Вызвать событие . internal void OnChatBoostHandler(BotEventArgs e) => OnChatBoostHandle?.Invoke(e); + /// Вызвать событие . internal void OnRemovedChatBoostHandler(BotEventArgs e) => OnRemovedChatBoostHandle?.Invoke(e); + /// Вызвать событие . internal void OnCallbackQueryHandler(BotEventArgs e) => OnCallbackQueryHandle?.Invoke(e); #endregion diff --git a/PRTelegramBot/Core/Executors/ExecutorCallbackQueryCommand.cs b/PRTelegramBot/Core/Executors/ExecutorCallbackQueryCommand.cs index 23723a5..9f7e8f8 100644 --- a/PRTelegramBot/Core/Executors/ExecutorCallbackQueryCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorCallbackQueryCommand.cs @@ -1,10 +1,10 @@ using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; using System.Reflection; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.Executors { @@ -15,45 +15,48 @@ internal sealed class ExecutorCallbackQueryCommand : ExecutorCommandBase { #region Базовый класс + /// public override CommandType CommandType => CommandType.Inline; - protected override async Task InternalCheck(PRBotBase bot, Update update, CommandHandler handler) + /// + protected override async Task InternalCheck(IBotContext context, CommandHandler handler) { var currentCheckers = bot.Options.CommandCheckers.Where(x => x.CommandTypes.Contains(CommandType)); if (currentCheckers.Any()) { foreach (var commandChecker in currentCheckers) { - var result = await commandChecker.Checker.Check(bot, update, handler); + var result = await commandChecker.Checker.Check(context, handler); if (result != InternalCheckResult.Passed) return result; } } var method = handler.Method; - var privilages = method.GetCustomAttribute(); + var privileges = method.GetCustomAttribute(); var whiteListAttribute = method.GetCustomAttribute(); - if (privilages != null) + if (privileges is not null) { - bot.Events.OnCheckPrivilegeInvoke(new PrivilegeEventArgs(bot, update, handler.ExecuteCommand, privilages.Mask)); + bot.Events.OnCheckPrivilegeInvoke(new PrivilegeEventArgs(context, handler.ExecuteCommand, privileges.Mask)); return InternalCheckResult.PrivilegeCheck; } var whiteListManager = bot.Options.WhiteListManager; - var hasUserInWhiteList = await whiteListManager.HasUser(update.GetChatId()); + var hasUserInWhiteList = await whiteListManager.HasUser(context.Update.GetChatId()); if (whiteListManager.Settings == WhiteListSettings.OnlyCommands && whiteListManager.Count > 0) { - if (whiteListAttribute == null && !hasUserInWhiteList) + if (whiteListAttribute is null && !hasUserInWhiteList) { - bot.Events.OnAccessDeniedInvoke(new BotEventArgs(bot, update)); + bot.Events.OnAccessDeniedInvoke(context.CreateBotEventArgs()); return InternalCheckResult.NotInWhiteList; } } return InternalCheckResult.Passed; } + /// protected override bool CanExecute(Enum currentCommand, Enum command, CommandHandler handler) { if (handler.CommandComparison == CommandComparison.Equals) diff --git a/PRTelegramBot/Core/Executors/ExecutorCommandBase.cs b/PRTelegramBot/Core/Executors/ExecutorCommandBase.cs index 9c7a51c..ab0a611 100644 --- a/PRTelegramBot/Core/Executors/ExecutorCommandBase.cs +++ b/PRTelegramBot/Core/Executors/ExecutorCommandBase.cs @@ -1,6 +1,6 @@ -using PRTelegramBot.Models; +using PRTelegramBot.Interfaces; +using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.Executors { @@ -8,7 +8,8 @@ namespace PRTelegramBot.Core.Executors /// Базовый исполнитель команд. /// /// Тип ключа для команд. - internal abstract class ExecutorCommandBase + internal abstract class ExecutorCommandBase + where TKey : notnull { #region Поля и свойства @@ -30,15 +31,15 @@ internal abstract class ExecutorCommandBase /// Выполнить команду. /// /// Команда для выполения. - /// Обновление. + /// Контекст бота. /// Команды. /// Результат выполнения команды. - public async Task Execute(TKey command, Update update, Dictionary commands) + public async Task Execute(TKey command, IBotContext context, Dictionary commands) { foreach (var commandExecute in commands.OrderByDescending(x => x.Value.CommandComparison == CommandComparison.Equals)) { if (CanExecute(command, commandExecute.Key, commandExecute.Value)) - return await ExecuteMethod(bot, update, commandExecute.Value); + return await ExecuteMethod(context, commandExecute.Value); } return CommandResult.Continue; } @@ -46,26 +47,26 @@ public async Task Execute(TKey command, Update update, Dictionary /// /// Выполнить метод. /// - /// Обновление. + /// Контекст бота. /// Обработчик. /// Результат выполнения команды. - public virtual async Task ExecuteMethod(PRBotBase bot, Update update, CommandHandler handler) + public virtual async Task ExecuteMethod(IBotContext context, CommandHandler handler) { - var result = await InternalCheck(bot, update, handler); + var result = await InternalCheck(context, handler); if (result != InternalCheckResult.Passed) return CommandResult.InternalCheck; - await handler.ExecuteCommand(bot.botClient, update); + await handler.ExecuteCommand(context); return CommandResult.Executed; } /// /// Внутрення проверка для /// - /// Обновление. + /// Контекст бота. /// Обработчик. /// Результат выполнения проверки. - protected abstract Task InternalCheck(PRBotBase bot, Update update, CommandHandler handler); + protected abstract Task InternalCheck(IBotContext context, CommandHandler handler); /// /// Можно ли выполнить команду. diff --git a/PRTelegramBot/Core/Executors/ExecutorMessageCommand.cs b/PRTelegramBot/Core/Executors/ExecutorMessageCommand.cs index 93ac34c..f51c0e6 100644 --- a/PRTelegramBot/Core/Executors/ExecutorMessageCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorMessageCommand.cs @@ -1,10 +1,10 @@ using PRTelegramBot.Attributes; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; using System.Reflection; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.Executors { @@ -15,48 +15,49 @@ internal abstract class ExecutorMessageCommand : ExecutorCommandBase { #region Базовый класс - protected override async Task InternalCheck(PRBotBase bot, Update update, CommandHandler handler) + /// + protected override async Task InternalCheck(IBotContext context, CommandHandler handler) { var method = handler.Method; - var privilages = method.GetCustomAttribute(); + var privileges = method.GetCustomAttribute(); var requireDate = method.GetCustomAttribute(); var requireChat = method.GetCustomAttribute(); var whiteListAttribute = method.GetCustomAttribute(); - if (requireChat != null) + if (requireChat is not null) { - var currentType = update?.Message?.Chat?.Type; - if (currentType == null || !requireChat.TypesChat.Contains(currentType.Value)) + var currentType = context.Update?.Message?.Chat?.Type; + if (currentType is null || !requireChat.TypesChat.Contains(currentType.Value)) { - bot.Events.OnWrongTypeChatInvoke(new BotEventArgs(bot, update)); + bot.Events.OnWrongTypeChatInvoke(context.CreateBotEventArgs()); return InternalCheckResult.WrongChatType; } } - if (requireDate != null) + if (requireDate is not null) { - var currentType = update?.Message?.Type; - if (currentType == null || !requireDate.TypeMessages.Contains(currentType.Value)) + var currentType = context.Update?.Message?.Type; + if (currentType is null || !requireDate.TypeMessages.Contains(currentType.Value)) { - bot.Events.OnWrongTypeMessageInvoke(new BotEventArgs(bot, update)); + bot.Events.OnWrongTypeMessageInvoke(context.CreateBotEventArgs()); return InternalCheckResult.WrongMessageType; } } - if (privilages != null) + if (privileges is not null) { - bot.Events.OnCheckPrivilegeInvoke(new PrivilegeEventArgs(bot, update, handler.ExecuteCommand, privilages.Mask)); + bot.Events.OnCheckPrivilegeInvoke(new PrivilegeEventArgs(context, handler.ExecuteCommand, privileges.Mask)); return InternalCheckResult.PrivilegeCheck; } var whiteListManager = bot.Options.WhiteListManager; - var hasUserInWhiteList = await whiteListManager.HasUser(update.GetChatId()); + var hasUserInWhiteList = await whiteListManager.HasUser(context.Update.GetChatId()); if (whiteListManager.Settings == WhiteListSettings.OnlyCommands && whiteListManager.Count > 0) { - if (whiteListAttribute == null && !hasUserInWhiteList) + if (whiteListAttribute is null && !hasUserInWhiteList) { - bot.Events.OnAccessDeniedInvoke(new BotEventArgs(bot, update)); + bot.Events.OnAccessDeniedInvoke(context.CreateBotEventArgs()); return InternalCheckResult.NotInWhiteList; } } @@ -66,7 +67,7 @@ protected override async Task InternalCheck(PRBotBase bot, { foreach (var commandChecker in currentCheckers) { - var result = await commandChecker.Checker.Check(bot, update, handler); + var result = await commandChecker.Checker.Check(context, handler); if (result != InternalCheckResult.Passed) return result; } @@ -75,6 +76,7 @@ protected override async Task InternalCheck(PRBotBase bot, return InternalCheckResult.Passed; } + /// protected override bool CanExecute(string currentCommand, string command, CommandHandler handler) { if (handler.CommandComparison == CommandComparison.Equals) diff --git a/PRTelegramBot/Core/Executors/ExecutorNextStepCommand.cs b/PRTelegramBot/Core/Executors/ExecutorNextStepCommand.cs index 03b7a95..f5eb587 100644 --- a/PRTelegramBot/Core/Executors/ExecutorNextStepCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorNextStepCommand.cs @@ -9,6 +9,7 @@ internal sealed class ExecutorNextStepCommand : ExecutorMessageCommand { #region Базовый класс + /// public override CommandType CommandType => CommandType.NextStep; #endregion diff --git a/PRTelegramBot/Core/Executors/ExecutorReplyCommand.cs b/PRTelegramBot/Core/Executors/ExecutorReplyCommand.cs index 55def8f..394075c 100644 --- a/PRTelegramBot/Core/Executors/ExecutorReplyCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorReplyCommand.cs @@ -9,6 +9,7 @@ internal sealed class ExecutorReplyCommand : ExecutorMessageCommand { #region Базовый класс + /// public override CommandType CommandType => CommandType.Reply; #endregion diff --git a/PRTelegramBot/Core/Executors/ExecutorReplyDynamicCommand.cs b/PRTelegramBot/Core/Executors/ExecutorReplyDynamicCommand.cs index 0ae0d4f..3b1c010 100644 --- a/PRTelegramBot/Core/Executors/ExecutorReplyDynamicCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorReplyDynamicCommand.cs @@ -9,6 +9,7 @@ internal sealed class ExecutorReplyDynamicCommand : ExecutorMessageCommand { #region Базовый класс + /// public override CommandType CommandType => CommandType.ReplyDynamic; #endregion diff --git a/PRTelegramBot/Core/Executors/ExecutorSlashCommand.cs b/PRTelegramBot/Core/Executors/ExecutorSlashCommand.cs index 7a8280f..1e7ee83 100644 --- a/PRTelegramBot/Core/Executors/ExecutorSlashCommand.cs +++ b/PRTelegramBot/Core/Executors/ExecutorSlashCommand.cs @@ -9,6 +9,7 @@ internal sealed class ExecutorSlashCommand : ExecutorMessageCommand { #region Базовый класс + /// public override CommandType CommandType => CommandType.Slash; #endregion diff --git a/PRTelegramBot/Core/Factories/HandlerFactory.cs b/PRTelegramBot/Core/Factories/HandlerFactory.cs index 7e877c4..bf005fa 100644 --- a/PRTelegramBot/Core/Factories/HandlerFactory.cs +++ b/PRTelegramBot/Core/Factories/HandlerFactory.cs @@ -1,8 +1,6 @@ using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.Factories { @@ -16,7 +14,7 @@ public CommandHandler CreateHandler(IBaseQueryAttribute attr, MethodInfo method, return new CommandHandler(method, serviceProvider); } - public CommandHandler CreateHandler(IBaseQueryAttribute attr, Func command, IServiceProvider serviceProvider) + public CommandHandler CreateHandler(IBaseQueryAttribute attr, Func command, IServiceProvider serviceProvider) { if (attr is IStringQueryAttribute stringAttribute) return CreateStringHandler(stringAttribute, command, serviceProvider); @@ -29,7 +27,7 @@ private CommandHandler CreateStringHandler(IStringQueryAttribute attribute, Meth return new StringCommandHandler(method, serviceProvider, attribute.CommandComparison, attribute.StringComparison); } - private CommandHandler CreateStringHandler(IStringQueryAttribute attribute, Func command, IServiceProvider serviceProvider) + private CommandHandler CreateStringHandler(IStringQueryAttribute attribute, Func command, IServiceProvider serviceProvider) { return new StringCommandHandler(command, serviceProvider, attribute.CommandComparison, attribute.StringComparison); } diff --git a/PRTelegramBot/Core/Factories/PRBotFactory.cs b/PRTelegramBot/Core/Factories/PRBotFactory.cs index 5829eb6..6ecbabb 100644 --- a/PRTelegramBot/Core/Factories/PRBotFactory.cs +++ b/PRTelegramBot/Core/Factories/PRBotFactory.cs @@ -9,6 +9,7 @@ public class PRBotFactory : PRBotFactoryBase { #region Базовый класс + /// public override PRBotBase CreateBot(TelegramOptions options) { return new PRBot(options); diff --git a/PRTelegramBot/Core/Factories/PRBotPollingFactory.cs b/PRTelegramBot/Core/Factories/PRBotPollingFactory.cs index 12d415a..2c74906 100644 --- a/PRTelegramBot/Core/Factories/PRBotPollingFactory.cs +++ b/PRTelegramBot/Core/Factories/PRBotPollingFactory.cs @@ -10,6 +10,7 @@ public class PRBotPollingFactory : PRBotFactoryBase { #region Базовый класс + /// public override PRBotBase CreateBot(TelegramOptions options) { return new PRBotPolling(options); diff --git a/PRTelegramBot/Core/Factories/PRBotWebHookFactory.cs b/PRTelegramBot/Core/Factories/PRBotWebHookFactory.cs index ec66af7..3b09cc6 100644 --- a/PRTelegramBot/Core/Factories/PRBotWebHookFactory.cs +++ b/PRTelegramBot/Core/Factories/PRBotWebHookFactory.cs @@ -9,6 +9,7 @@ public class PRBotWebHookFactory : PRBotFactoryBase { #region Базовый класс + /// public override PRBotBase CreateBot(TelegramOptions options) { return new PRBotWebHook(options); diff --git a/PRTelegramBot/Core/Handler.cs b/PRTelegramBot/Core/Handler.cs index cc5ca32..467d651 100644 --- a/PRTelegramBot/Core/Handler.cs +++ b/PRTelegramBot/Core/Handler.cs @@ -3,6 +3,7 @@ using PRTelegramBot.Core.UpdateHandlers; using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; +using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; using Telegram.Bot; @@ -18,17 +19,7 @@ namespace PRTelegramBot.Core public sealed class Handler : IPRUpdateHandler { #region Поля и свойства - - /// - /// Диспетчер для обработки update типа message. - /// - internal MessageUpdateDispatcher MessageDispatcher { get; private set; } - - /// - /// Диспетчер для обработки update типа callbackQuery. - /// - internal CallBackQueryUpdateDispatcher CallBackQueryDispatcher { get; private set; } - + /// /// Хранилище callbackQuery команд. /// @@ -49,49 +40,73 @@ public sealed class Handler : IPRUpdateHandler /// public SlashCommandStore SlashCommandsStore { get; private set; } + /// + /// Диспетчер для обработки update типа message. + /// + internal MessageUpdateDispatcher MessageDispatcher { get; private set; } + + /// + /// Диспетчер для обработки update типа callbackQuery. + /// + internal CallBackQueryUpdateDispatcher CallBackQueryDispatcher { get; private set; } + /// /// Ограничитель спама логов. /// - private DateTime LastErrorPollingDate; + private DateTime lastErrorPollingDate; /// /// Бот. /// - private PRBotBase bot; + private readonly PRBotBase bot; #endregion #region IPRUpdateHandler + /// public MiddlewareBase Middleware { get; } /// /// Обработчик обновлений. /// - /// Клиент телеграм бота. - /// Обновление телеграм. + /// Клиент telegram бота. + /// Обновление telegram. /// Токен отмены. - public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + if (update == null) + return Task.CompletedTask; + + // Связь update вместе ITelegramBotClient. + update.AddTelegramClient(bot); + var context = new BotContext(bot, update, cancellationToken); + _ = HandleUpdateInternalAsync(context); + return Task.CompletedTask; + } + + /// + /// Обработать update в отдельном потоке. + /// + /// Контекст бота. + /// Task. + /// Требуется, чтобы 1 update не повесил обработку всего приложения. + private async Task HandleUpdateInternalAsync(BotContext context) { try { - if (update == null) - return; - - //Связь update вместе ITelegramBotClient - update.AddTelegramClient(bot); - - _ = Middleware.InvokeOnPreUpdateAsync(botClient, update, async () => + await Middleware.InvokeOnPreUpdateAsync(context, async () => { - await UpdateAsync(update); + await UpdateAsync(context); }); - } + } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex, update); + bot.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); } } + /// public void HotReload() { CallbackQueryCommandsStore.ClearCommands(); @@ -108,20 +123,22 @@ public void HotReload() /// /// Обработчик ошибок API. /// - /// Клиент телеграм бота. + /// Клиент telegram бота. /// Исключение. /// Исходник ошибки /// Токен отмены. - public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken) + public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken) { - if(source == HandleErrorSource.PollingError && exception.Message.Contains("Exception during making request")) + if (source == HandleErrorSource.PollingError && exception.Message.Contains("Exception during making request")) { - if(DateTime.Now < LastErrorPollingDate) - return; + if (DateTime.Now < lastErrorPollingDate) + return Task.CompletedTask; - LastErrorPollingDate = DateTime.Now.AddMinutes(bot.Options.AntiSpamErrorMinute); + lastErrorPollingDate = DateTime.Now.AddMinutes(bot.Options.AntiSpamErrorMinute); } - this.bot.Events.OnErrorLogInvoke(exception); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, exception, cancellationToken)); + + return Task.CompletedTask; } #endregion @@ -131,16 +148,16 @@ public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception excep /// /// Обработка обновлений. /// - /// Update. - public async Task UpdateAsync(Update update) + /// Контекст бота. + public async Task UpdateAsync(IBotContext context) { var whiteListManager = bot.Options.WhiteListManager; - + var update = context.Update; if (bot.Events.UpdateEvents.HasEventOnPreUpdate()) { - var resultUpdate = await bot.Events.UpdateEvents.OnPreInvoke(new BotEventArgs(bot, update)); + var resultUpdate = await bot.Events.UpdateEvents.OnPreInvoke(context.CreateBotEventArgs()); - if (resultUpdate == UpdateResult.Stop || resultUpdate == UpdateResult.Handled) + if (resultUpdate is UpdateResult.Stop or UpdateResult.Handled) return; } @@ -149,78 +166,78 @@ public async Task UpdateAsync(Update update) var hasUserInWhiteList = await whiteListManager.HasUser(update.GetChatId()); if (!hasUserInWhiteList) { - bot.Events.OnAccessDeniedInvoke(new BotEventArgs(bot, update)); + bot.Events.OnAccessDeniedInvoke(context.CreateBotEventArgs()); return; } } if (update.Type == UpdateType.CallbackQuery) - _ = CallBackQueryDispatcher.Dispatch(update); + _ = CallBackQueryDispatcher.Dispatch(context); if (update.Type == UpdateType.Message) - _ = MessageDispatcher.Dispatch(update); + _ = MessageDispatcher.Dispatch(context); if (update.Type == UpdateType.ChannelPost) - bot.Events.UpdateEvents.OnChannelPostHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnChannelPostHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.ChatJoinRequest) - bot.Events.UpdateEvents.OnChatJoinRequestHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnChatJoinRequestHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.ChatMember) - bot.Events.UpdateEvents.OnChatMemberHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnChatMemberHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.ChosenInlineResult) - bot.Events.UpdateEvents.OnChosenInlineResultHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnChosenInlineResultHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.ChatBoost) - bot.Events.UpdateEvents.OnChatBoostHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnChatBoostHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.EditedChannelPost) - bot.Events.UpdateEvents.OnEditedChannelPostHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnEditedChannelPostHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.EditedMessage) - bot.Events.UpdateEvents.OnEditedMessageHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnEditedMessageHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.BusinessConnection) - bot.Events.UpdateEvents.OnBusinessConnectionHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnBusinessConnectionHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.EditedBusinessMessage) - bot.Events.UpdateEvents.OnEditedBusinessHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnEditedBusinessHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.DeletedBusinessMessages) - bot.Events.UpdateEvents.OnDeletedBusinessConnectionHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnDeletedBusinessConnectionHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.MessageReaction) - bot.Events.UpdateEvents.OnMessageReactionHandleHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnMessageReactionHandleHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.MessageReactionCount) - bot.Events.UpdateEvents.OnMessageReactionCountHandleHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnMessageReactionCountHandleHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.InlineQuery) - bot.Events.UpdateEvents.OnInlineQueryHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnInlineQueryHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.MyChatMember) - bot.Events.UpdateEvents.OnMyChatMemberHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnMyChatMemberHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.Poll) - bot.Events.UpdateEvents.OnPollHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnPollHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.PollAnswer) - bot.Events.UpdateEvents.OnPollAnswerHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnPollAnswerHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.PreCheckoutQuery) - bot.Events.UpdateEvents.OnPreCheckoutQueryHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnPreCheckoutQueryHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.RemovedChatBoost) - bot.Events.UpdateEvents.OnRemovedChatBoostHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnRemovedChatBoostHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.ShippingQuery) - bot.Events.UpdateEvents.OnShippingQueryHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnShippingQueryHandler(context.CreateBotEventArgs()); if (update.Type == UpdateType.Unknown) - bot.Events.UpdateEvents.OnUnknownHandler(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnUnknownHandler(context.CreateBotEventArgs()); - bot.Events.UpdateEvents.OnPostInvoke(new BotEventArgs(bot, update)); + bot.Events.UpdateEvents.OnPostInvoke(context.CreateBotEventArgs()); } #endregion @@ -241,8 +258,8 @@ public Handler(PRBotBase bot) ReplyDynamicCommandsStore = new ReplyDynamicCommandStore(bot); SlashCommandsStore = new SlashCommandStore(bot); - MessageDispatcher = new MessageUpdateDispatcher(this.bot); - CallBackQueryDispatcher = new CallBackQueryUpdateDispatcher(this.bot); + MessageDispatcher = new MessageUpdateDispatcher(bot); + CallBackQueryDispatcher = new CallBackQueryUpdateDispatcher(); HotReload(); } diff --git a/PRTelegramBot/Core/Middlewares/MiddlewareBase.cs b/PRTelegramBot/Core/Middlewares/MiddlewareBase.cs index e5e11af..16bd199 100644 --- a/PRTelegramBot/Core/Middlewares/MiddlewareBase.cs +++ b/PRTelegramBot/Core/Middlewares/MiddlewareBase.cs @@ -1,5 +1,4 @@ -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Core.Middlewares { @@ -27,29 +26,29 @@ public class MiddlewareBase /// /// Выполнить следующий асинхронный промежуточный обработчик. /// - /// Update. + /// Контекст бота. /// Функция которая должна выполниться после обработчиков. - public virtual async Task InvokeOnPreUpdateAsync(ITelegramBotClient botClient, Update update, Func next) + public virtual async Task InvokeOnPreUpdateAsync(IBotContext context, Func next) { - if (nextMiddleware != null) + if (nextMiddleware is not null) { - await nextMiddleware.InvokeOnPreUpdateAsync(botClient, update, next); + await nextMiddleware.InvokeOnPreUpdateAsync(context, next); } else { await next(); - await InvokeOnPostUpdateAsync(botClient, update); + await InvokeOnPostUpdateAsync(context); } } /// /// Выполнить предыдущий асинхронный промежуточный обработчик. /// - /// Update. - public virtual async Task InvokeOnPostUpdateAsync(ITelegramBotClient botClient, Update update) + /// Контекст бота. + public virtual async Task InvokeOnPostUpdateAsync(IBotContext context) { - if (previousMiddleware != null) - await previousMiddleware.InvokeOnPostUpdateAsync(botClient, update); + if (previousMiddleware is not null) + await previousMiddleware.InvokeOnPostUpdateAsync(context); } /// diff --git a/PRTelegramBot/Core/Middlewares/MiddlewareBuilder.cs b/PRTelegramBot/Core/Middlewares/MiddlewareBuilder.cs index 9bdf0cb..e935100 100644 --- a/PRTelegramBot/Core/Middlewares/MiddlewareBuilder.cs +++ b/PRTelegramBot/Core/Middlewares/MiddlewareBuilder.cs @@ -14,7 +14,7 @@ public class MiddlewareBuilder /// Цепочка обработчиков. public virtual MiddlewareBase Build(List middlewares) { - if (middlewares == null) + if (middlewares is null) return new MiddlewareBase(); MiddlewareBase current = new MiddlewareBase(); diff --git a/PRTelegramBot/Core/PRBot.cs b/PRTelegramBot/Core/PRBot.cs index 25d350c..2981eec 100644 --- a/PRTelegramBot/Core/PRBot.cs +++ b/PRTelegramBot/Core/PRBot.cs @@ -1,5 +1,6 @@ using PRTelegramBot.Configs; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; using Telegram.Bot; namespace PRTelegramBot.Core @@ -11,48 +12,45 @@ public sealed class PRBot : PRBotBase { #region Базовый класс - public override DataRetrievalMethod DataRetrieval - { - get - { - return DataRetrievalMethod.Classic; - } - } + /// + public override DataRetrievalMethod DataRetrieval => DataRetrievalMethod.Classic; - public override async Task Start() + /// + public override async Task StartAsync(CancellationToken cancellationToken = default) { try { - await base.Start(); + await base.StartAsync(Options.CancellationTokenSource.Token); if (Options.ClearUpdatesOnStart) - await ClearUpdates(); + await ClearUpdatesAsync(Options.CancellationTokenSource.Token); - botClient.StartReceiving(Handler, Options.ReceiverOptions); + BotClient.StartReceiving(Handler, Options.ReceiverOptions, Options.CancellationTokenSource.Token); - var client = await botClient.GetMe(); + var client = await BotClient.GetMe(Options.CancellationTokenSource.Token); BotName = client?.Username; - this.Events.OnCommonLogInvoke($"Bot {BotName} is running.", "Initialization", ConsoleColor.Yellow); + Events.OnCommonLogInvoke($"Bot {BotName} is running.", "Initialization", ConsoleColor.Yellow); IsWork = true; } catch (Exception ex) { IsWork = false; - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex)); } } - public override async Task Stop() + /// + public override async Task StopAsync(CancellationToken cancellationToken = default) { try { - Options.CancellationToken.Cancel(); + Options.CancellationTokenSource.Cancel(); - await Task.Delay(3000); + await Task.Delay(3000, CancellationToken.None); IsWork = false; } catch (Exception ex) { - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex)); } } diff --git a/PRTelegramBot/Core/PRBotBase.cs b/PRTelegramBot/Core/PRBotBase.cs index c39cf96..1956cfc 100644 --- a/PRTelegramBot/Core/PRBotBase.cs +++ b/PRTelegramBot/Core/PRBotBase.cs @@ -3,11 +3,15 @@ using PRTelegramBot.Core.Events; using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Registrars; using Telegram.Bot; namespace PRTelegramBot.Core { + /// + /// Базовый класс экземпляра бота. + /// public abstract class PRBotBase { #region Поля и свойства @@ -20,12 +24,12 @@ public abstract class PRBotBase /// /// Клиент для telegram бота. /// - public ITelegramBotClient botClient { get; protected set; } + public ITelegramBotClient BotClient { get; protected set; } /// /// Идентификатор бота в telegram. /// - public long? TelegramId { get { return botClient.BotId; } } + public long? TelegramId => BotClient.BotId; /// /// Обработчик для telegram бота @@ -85,7 +89,7 @@ public bool ReloadHandlers() } catch(Exception ex) { - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex)); return false; } } @@ -98,7 +102,7 @@ private bool InitHandlers() { try { - if(Handler is null) + if (Handler is null) { Handler = Options.UpdateHandler ?? new Handler(this); if(Handler is Handler baseHandler) @@ -111,7 +115,7 @@ private bool InitHandlers() Options.CallbackQueryHandlers.Add(new InlineCommandHandler()); } } - if(Register is null) + if (Register is null) { Register = Options.CommandOptions.RegisterCommand ?? new RegisterCommand(); Register.Init(this); @@ -121,7 +125,7 @@ private bool InitHandlers() } catch (Exception ex) { - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex)); return false; } } @@ -129,59 +133,60 @@ private bool InitHandlers() /// /// Очистка очереди команд перед запуском. /// - protected async Task ClearUpdates() + protected async Task ClearUpdatesAsync(CancellationToken cancellationToken = default) { try { - var update = await botClient.GetUpdates(); - foreach (var item in update) + var updates = await BotClient.GetUpdates(cancellationToken: cancellationToken); + foreach (var item in updates) { var offset = item.Id + 1; - await botClient.GetUpdates(offset); + await BotClient.GetUpdates(offset, cancellationToken: cancellationToken); } } catch (Exception ex) { - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex)); } } /// /// Запустить бота. /// - public virtual async Task Start() + public virtual Task StartAsync(CancellationToken cancellationToken = default) { InitHandlers(); + return Task.CompletedTask; } /// /// Остановка бота. /// - public abstract Task Stop(); + public abstract Task StopAsync(CancellationToken cancellationToken = default); #endregion #region Конструкторы - protected PRBotBase(Action optionsBuilder, TelegramOptions options) + protected PRBotBase(Action? optionsBuilder, TelegramOptions? options) : base() { Options = new TelegramOptions(); - if (optionsBuilder != null) + if (optionsBuilder is not null) optionsBuilder.Invoke(Options); else - Options = options; + Options = options ?? throw new ArgumentNullException($"The arguments to the designer are incorrectly transferred, both arguments ({nameof(options)} and {nameof(optionsBuilder)}) cannot be null."); if (string.IsNullOrEmpty(Options.Token)) - throw new Exception("Bot token is empty"); + throw new ArgumentException("Bot token is empty"); if (Options.BotId < 0) - throw new Exception("Bot ID cannot be less than zero"); + throw new ArgumentException("Bot ID cannot be less than zero"); BotCollection.Instance.AddBot(this); - botClient = Options.Client ?? new TelegramBotClient(Options.Token); + BotClient = Options.Client ?? new TelegramBotClient(Options.Token); Events = new TEvents(this); InlineClassRegistrar.Register(this); InitHandlers(); diff --git a/PRTelegramBot/Core/PRBotBuilder.cs b/PRTelegramBot/Core/PRBotBuilder.cs index 0b58450..ae53ab4 100644 --- a/PRTelegramBot/Core/PRBotBuilder.cs +++ b/PRTelegramBot/Core/PRBotBuilder.cs @@ -1,5 +1,4 @@ -using Microsoft.Extensions.Options; -using PRTelegramBot.Configs; +using PRTelegramBot.Configs; using PRTelegramBot.Core.Factory; using PRTelegramBot.Core.Middlewares; using PRTelegramBot.Interfaces; @@ -20,8 +19,8 @@ public sealed class PRBotBuilder private TelegramOptions options; private PRBotFactoryBase factory; - private List admins = new List(); - private List whitelist = new List(); + private List admins = []; + private List whiteList = []; private WhiteListSettings whiteListSettings = WhiteListSettings.OnPreUpdate; #endregion @@ -35,7 +34,7 @@ public sealed class PRBotBuilder public PRBotBase Build() { options.AdminManager.AddUsers(admins.ToArray()); - options.WhiteListManager.AddUsers(whitelist.ToArray()); + options.WhiteListManager.AddUsers(whiteList.ToArray()); options.WhiteListManager.SetSettings(whiteListSettings); return factory.CreateBot(options); } @@ -47,7 +46,7 @@ public PRBotBase Build() public void ClearOptions(string token) { admins.Clear(); - whitelist.Clear(); + whiteList.Clear(); options = new TelegramOptions(); SetToken(token); } @@ -247,7 +246,7 @@ public PRBotBuilder AddAdmins(List telegramIds) /// Builder. public PRBotBuilder AddUserWhiteList(params long[] telegramId) { - whitelist.AddRange(telegramId); + whiteList.AddRange(telegramId); return this; } @@ -258,7 +257,7 @@ public PRBotBuilder AddUserWhiteList(params long[] telegramId) /// Builder. public PRBotBuilder AddUsersWhiteList(List telegramIds) { - whitelist.AddRange(telegramIds.ToArray()); + whiteList.AddRange(telegramIds.ToArray()); return this; } @@ -293,18 +292,18 @@ public PRBotBuilder AddConfigPaths(Dictionary configPaths) /// Builder. public PRBotBuilder SetServiceProvider(IServiceProvider serviceProvider) { - this.options.ServiceProvider = serviceProvider; + options.ServiceProvider = serviceProvider; return this; } /// /// Добавить параметры приемника. /// - /// параметры приемника. + /// Параметры приемника. /// Builder. - public PRBotBuilder AddRecevingOptions(ReceiverOptions recevierOptions) + public PRBotBuilder AddReceivingOptions(ReceiverOptions receiverOptions) { - this.options.ReceiverOptions = recevierOptions; + options.ReceiverOptions = receiverOptions; return this; } @@ -326,7 +325,7 @@ public PRBotBuilder UseFactory(PRBotFactoryBase factory) /// Builder. public PRBotBuilder SetUrlWebHook(string url) { - this.options.WebHookOptions.Url = url; + options.WebHookOptions.Url = url; return this; } @@ -337,18 +336,18 @@ public PRBotBuilder SetUrlWebHook(string url) /// Builder. public PRBotBuilder SetSecretTokenWebHook(string secretToken) { - this.options.WebHookOptions.SecretToken = secretToken; + options.WebHookOptions.SecretToken = secretToken; return this; } /// /// Установить IP-адрес для вебхука. /// - /// IP-адрес. + /// IP-адрес. /// Builder. - public PRBotBuilder SetIpAddresWebHook(string ipAddres) + public PRBotBuilder SetIpAddressWebHook(string ipAddress) { - this.options.WebHookOptions.IpAddress = ipAddres; + options.WebHookOptions.IpAddress = ipAddress; return this; } @@ -359,7 +358,7 @@ public PRBotBuilder SetIpAddresWebHook(string ipAddres) /// Builder. public PRBotBuilder SetDropPendingUpdates(bool flag) { - this.options.WebHookOptions.DropPendingUpdates = flag; + options.WebHookOptions.DropPendingUpdates = flag; return this; } @@ -370,7 +369,7 @@ public PRBotBuilder SetDropPendingUpdates(bool flag) /// Builder. public PRBotBuilder SetMaxConnectionsWebHook(int maxConnections) { - this.options.WebHookOptions.MaxConnections = maxConnections; + options.WebHookOptions.MaxConnections = maxConnections; return this; } @@ -381,7 +380,7 @@ public PRBotBuilder SetMaxConnectionsWebHook(int maxConnections) /// Builder. public PRBotBuilder SetTelegramClient(TelegramBotClient client) { - this.options.Client = client; + options.Client = client; return this; } @@ -392,51 +391,51 @@ public PRBotBuilder SetTelegramClient(TelegramBotClient client) /// Builder. public PRBotBuilder SetCertificateWebHook(InputFileStream certificate) { - this.options.WebHookOptions.Certificate = certificate; + options.WebHookOptions.Certificate = certificate; return this; } /// - /// Добавить новый обработчик команд для callbackQuery (inline). + /// Добавить новы(й/е) обработчик(и) команд для callbackQuery (inline). /// - /// Обработчик. + /// Обработчики для callbackQuery команд. /// Builder. public PRBotBuilder AddCallbackQueryCommandHandlers(params ICallbackQueryCommandHandler[] handlers) { - this.options.CallbackQueryHandlers.AddRange(handlers); + options.CallbackQueryHandlers.AddRange(handlers); return this; } /// /// Добавить новые обработчики команд для callbackQuery (inline). /// - /// Обработчик. + /// Обработчики для callbackQuery команд. /// Builder. public PRBotBuilder AddCallbackQueryCommandHandlers(List handlers) { - this.options.CallbackQueryHandlers.AddRange(handlers); + options.CallbackQueryHandlers.AddRange(handlers); return this; } /// - /// Добавить новый обработчик команд для message. + /// Добавить новы(й/е) обработчик(и) команд для message. /// - /// Обработчик. + /// Обработчик(и) для message команд. /// Builder. public PRBotBuilder AddMessageCommandHandlers(params IMessageCommandHandler[] handlers) { - this.options.MessageHandlers.AddRange(handlers); + options.MessageHandlers.AddRange(handlers); return this; } /// /// Добавить новые обработчики команд для message. /// - /// Обработчик. + /// Обработчики для message команд. /// Builder. public PRBotBuilder AddMessageCommandHandlers(List handlers) { - this.options.MessageHandlers.AddRange(handlers); + options.MessageHandlers.AddRange(handlers); return this; } @@ -447,7 +446,7 @@ public PRBotBuilder AddMessageCommandHandlers(List handl /// Builder. public PRBotBuilder SetAntiSpamErrorMinute(int minute) { - this.options.AntiSpamErrorMinute = minute; + options.AntiSpamErrorMinute = minute; return this; } @@ -460,9 +459,9 @@ public PRBotBuilder SetAntiSpamErrorMinute(int minute) public PRBotBuilder AddInlineClassHandler(Enum @enum, Type type) { if (type.IsAssignableTo(typeof(ICallbackQueryCommandHandler))) - this.options.CommandOptions.InlineClassHandlers.Add(@enum, type); + options.CommandOptions.InlineClassHandlers.Add(@enum, type); else - throw new Exception($"{type} must implement the {typeof(ICallbackQueryCommandHandler)} interface."); + throw new ArgumentException($"{type} must implement the {typeof(ICallbackQueryCommandHandler)} interface."); return this; } @@ -479,7 +478,7 @@ public PRBotBuilder(string token) : this() { SetToken(token); - AddRecevingOptions(new ReceiverOptions() { AllowedUpdates = { } }); + AddReceivingOptions(new ReceiverOptions() { AllowedUpdates = { } }); factory = new PRBotFactory(); } @@ -492,7 +491,7 @@ public PRBotBuilder(TelegramBotClient client) { options.Client = client; - AddRecevingOptions(new ReceiverOptions() { AllowedUpdates = { } }); + AddReceivingOptions(new ReceiverOptions() { AllowedUpdates = { } }); factory = new PRBotFactory(); } diff --git a/PRTelegramBot/Core/PRBotDummy.cs b/PRTelegramBot/Core/PRBotDummy.cs new file mode 100644 index 0000000..3380796 --- /dev/null +++ b/PRTelegramBot/Core/PRBotDummy.cs @@ -0,0 +1,50 @@ +using PRTelegramBot.Configs; +using PRTelegramBot.Models.Enums; +using Telegram.Bot; + +namespace PRTelegramBot.Core +{ + /// + /// Экземпляр заглушки бота. + /// + public class PRBotDummy : PRBotBase + { + + #region Базовый класс + + /// + public override DataRetrievalMethod DataRetrieval => DataRetrievalMethod.Dummy; + + /// + public override Task StopAsync(CancellationToken cancellationToken = default) + { + return Task.CompletedTask; + } + + #endregion + + #region Конструкторы + + /// + /// Конструктор. + /// + /// Билдер. + /// Опции. + public PRBotDummy(Action? optionsBuilder, TelegramOptions? options) : base(optionsBuilder, options) + { } + + /// + /// Конструктор. + /// + public PRBotDummy() + : this(opt => + { + opt.Client = new TelegramBotClient("35425:token"); + opt.Token = "35425:token"; + opt.BotId = 9876; + }, null) + { } + + #endregion + } +} diff --git a/PRTelegramBot/Core/PRBotPolling.cs b/PRTelegramBot/Core/PRBotPolling.cs index 9f0f3a5..75b372a 100644 --- a/PRTelegramBot/Core/PRBotPolling.cs +++ b/PRTelegramBot/Core/PRBotPolling.cs @@ -1,5 +1,6 @@ using PRTelegramBot.Configs; using PRTelegramBot.Models.Enums; +using PRTelegramBot.Models.EventsArgs; using Telegram.Bot; namespace PRTelegramBot.Core @@ -11,47 +12,44 @@ public sealed class PRBotPolling : PRBotBase { #region Базовый класс - public override DataRetrievalMethod DataRetrieval - { - get - { - return DataRetrievalMethod.Polling; - } - } + /// + public override DataRetrievalMethod DataRetrieval => DataRetrievalMethod.Polling; - public override async Task Start() + /// + public override async Task StartAsync(CancellationToken cancellationToken = default) { try { - await base.Start(); + await base.StartAsync(Options.CancellationTokenSource.Token); if (Options.ClearUpdatesOnStart) - await ClearUpdates(); + await ClearUpdatesAsync(Options.CancellationTokenSource.Token); - _ = UpdatePolling(); + _ = UpdatePollingAsync(Options.CancellationTokenSource.Token); - var client = await botClient.GetMe(); + var client = await BotClient.GetMe(Options.CancellationTokenSource.Token); BotName = client?.Username; - this.Events.OnCommonLogInvoke($"Bot {BotName} is running.", "Initialization", ConsoleColor.Yellow); + Events.OnCommonLogInvoke($"Bot {BotName} is running.", "Initialization", ConsoleColor.Yellow); IsWork = true; } catch (Exception ex) { IsWork = false; - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex, cancellationToken)); } } - public override async Task Stop() + /// + public override async Task StopAsync(CancellationToken cancellationToken = default) { try { - Options.CancellationToken.Cancel(); - await Task.Delay(3000); + Options.CancellationTokenSource.Cancel(); + await Task.Delay(3000, CancellationToken.None); IsWork = false; } catch (Exception ex) { - this.Events.OnErrorLogInvoke(ex); + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex, cancellationToken)); } } @@ -62,27 +60,28 @@ public override async Task Stop() /// /// Обработка update через polling. /// - public async Task UpdatePolling() + private async Task UpdatePollingAsync(CancellationToken cancellationToken) { - int? offset = Options.ReceiverOptions.Offset; - while (!Options.CancellationToken.IsCancellationRequested) + try { - var updates = await botClient.GetUpdates(offset, Options.ReceiverOptions.Limit, Options.Timeout, Options.ReceiverOptions.AllowedUpdates, Options.CancellationToken.Token); - foreach (var update in updates) + int? offset = Options.ReceiverOptions.Offset; + while (!Options.CancellationTokenSource.IsCancellationRequested) { - offset = update.Id + 1; - try - { - await Handler.HandleUpdateAsync(botClient, update, Options.CancellationToken.Token); - } - catch (Exception ex) + var updates = await BotClient.GetUpdates(offset, Options.ReceiverOptions.Limit, Options.Timeout, Options.ReceiverOptions.AllowedUpdates, Options.CancellationTokenSource.Token); + foreach (var update in updates) { - this.Events.OnErrorLogInvoke(ex); + offset = update.Id + 1; + await Handler.HandleUpdateAsync(BotClient, update, Options.CancellationTokenSource.Token); + + if (Options.CancellationTokenSource.IsCancellationRequested) break; } - if (Options.CancellationToken.IsCancellationRequested) break; } + IsWork = false; + } + catch (Exception ex) + { + Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(this, ex, cancellationToken)); } - IsWork = false; } #endregion diff --git a/PRTelegramBot/Core/PRBotWebHook.cs b/PRTelegramBot/Core/PRBotWebHook.cs index 36f9de2..5d96520 100644 --- a/PRTelegramBot/Core/PRBotWebHook.cs +++ b/PRTelegramBot/Core/PRBotWebHook.cs @@ -14,23 +14,19 @@ public sealed class PRBotWebHook : PRBotBase { #region Базовый класс - public override DataRetrievalMethod DataRetrieval - { - get - { - return DataRetrievalMethod.WebHook; - } - } + /// + public override DataRetrievalMethod DataRetrieval => DataRetrievalMethod.WebHook; - public override async Task Start() + /// + public override async Task StartAsync(CancellationToken cancellationToken = default) { try { - await base.Start(); + await base.StartAsync(Options.CancellationTokenSource.Token); if(string.IsNullOrEmpty(Options.WebHookOptions.SecretToken)) Options.WebHookOptions.SecretToken = Generator.RandomSymbols(Generator.Chars.Alphabet, 10); - await botClient.SetWebhook( + await BotClient.SetWebhook( url: Options.WebHookOptions.Url, certificate: Options.WebHookOptions.Certificate, ipAddress: Options.WebHookOptions.IpAddress, @@ -38,7 +34,7 @@ await botClient.SetWebhook( allowedUpdates: Array.Empty(), dropPendingUpdates: Options.WebHookOptions.DropPendingUpdates, secretToken: Options.WebHookOptions.SecretToken, - cancellationToken: Options.CancellationToken.Token); + cancellationToken: Options.CancellationTokenSource.Token); } catch(Exception ex) { @@ -46,14 +42,16 @@ await botClient.SetWebhook( } } - public override async Task Stop() + /// + public override async Task StopAsync(CancellationToken cancellationToken = default) { - await botClient.DeleteWebhook(cancellationToken: Options.CancellationToken.Token); + await BotClient.DeleteWebhook(cancellationToken: Options.CancellationTokenSource.Token); } - public async Task GetWebHookInfo() + /// + public async Task GetWebHookInfoAsync(CancellationToken cancellationToken = default) { - return await botClient.GetWebhookInfo(); + return await BotClient.GetWebhookInfo(cancellationToken); } #endregion diff --git a/PRTelegramBot/Core/UpdateDispatchers/CallBackQueryUpdateDispatcher.cs b/PRTelegramBot/Core/UpdateDispatchers/CallBackQueryUpdateDispatcher.cs index 167f159..78d893f 100644 --- a/PRTelegramBot/Core/UpdateDispatchers/CallBackQueryUpdateDispatcher.cs +++ b/PRTelegramBot/Core/UpdateDispatchers/CallBackQueryUpdateDispatcher.cs @@ -1,7 +1,7 @@ using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; -using Telegram.Bot.Types; namespace PRTelegramBot.Core.UpdateHandlers { @@ -10,38 +10,29 @@ namespace PRTelegramBot.Core.UpdateHandlers /// internal sealed class CallBackQueryUpdateDispatcher { - #region Поля и свойства - - /// - /// Бот. - /// - private readonly PRBotBase bot; - - #endregion - #region Методы /// /// Отправить update на обработку. /// - /// Update. - public async Task Dispatch(Update update) + /// Контекст бота. + public async Task Dispatch(IBotContext context) { try { - bot.Events.UpdateEvents.OnCallbackQueryHandler(new BotEventArgs(bot, update)); + context.Current.Events.UpdateEvents.OnCallbackQueryHandler(context.CreateBotEventArgs()); var result = UpdateResult.Continue; - foreach (var handler in bot.Options.CallbackQueryHandlers) + foreach (var handler in context.Current.Options.CallbackQueryHandlers) { - result = await handler.Handle(bot, update, update.CallbackQuery); - if (!result.IsContinueHandle(bot, update)) + result = await handler.Handle(context, context.Update.CallbackQuery); + if (!result.IsContinueHandle(context)) return result; } return result; } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex, update); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); return UpdateResult.Error; } } @@ -53,11 +44,7 @@ public async Task Dispatch(Update update) /// /// Конструктор. /// - /// Бот. - public CallBackQueryUpdateDispatcher(PRBotBase bot) - { - this.bot = bot; - } + public CallBackQueryUpdateDispatcher() { } #endregion } diff --git a/PRTelegramBot/Core/UpdateDispatchers/MessageUpdateDispatcher.cs b/PRTelegramBot/Core/UpdateDispatchers/MessageUpdateDispatcher.cs index fe36708..b432447 100644 --- a/PRTelegramBot/Core/UpdateDispatchers/MessageUpdateDispatcher.cs +++ b/PRTelegramBot/Core/UpdateDispatchers/MessageUpdateDispatcher.cs @@ -1,8 +1,8 @@ using PRTelegramBot.Core.CommandHandlers; using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.EventsArgs; -using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; namespace PRTelegramBot.Core.UpdateHandlers @@ -34,18 +34,18 @@ internal sealed class MessageUpdateDispatcher #region Методы /// - /// Вызвать обработку update типа message/ + /// Вызвать обработку update типа message. /// - /// Обновление. + /// Контекст бота. /// Результат выполнения. - public async Task Dispatch(Update update) + public async Task Dispatch(IBotContext context) { - var eventResult = EventHandler(update); + var eventResult = EventHandler(context); if (eventResult == UpdateResult.Handled) return eventResult; - if(update.Message.Type.Equals(MessageType.Text)) - return await UpdateMessageCommands(update); + if(context.Update.Message.Type.Equals(MessageType.Text)) + return await UpdateMessageCommands(context); return UpdateResult.NotFound; @@ -54,32 +54,32 @@ public async Task Dispatch(Update update) /// /// Логика обработки сообщений. /// - /// Обновление. + /// Контекст бота. /// Результат выполнения. - private async Task UpdateMessageCommands(Update update) + private async Task UpdateMessageCommands(IBotContext context) { var result = UpdateResult.Continue; - bot.Events.MessageEvents.OnTextHandleInvoke(new BotEventArgs(bot, update)); + bot.Events.MessageEvents.OnTextHandleInvoke(context.CreateBotEventArgs()); - if (!nextStepHandler.IgnoreBasicCommand(update)) + if (!nextStepHandler.IgnoreBasicCommand(context)) { foreach (var handler in bot.Options.MessageHandlers) { - result = await handler.Handle(bot, update, update.Message); - if (!result.IsContinueHandle(bot, update)) + result = await handler.Handle(context, context.Update.Message); + if (!result.IsContinueHandle(context)) return result; } } - result = await nextStepHandler.Handle(bot, update); + result = await nextStepHandler.Handle(context); if (result == UpdateResult.Handled) { - if (nextStepHandler.LastStepExecuted(update)) - nextStepHandler.ClearSteps(update); + if (nextStepHandler.LastStepExecuted(context.Update)) + nextStepHandler.ClearSteps(context.Update); return result; } - bot.Events.OnMissingCommandInvoke(new BotEventArgs(bot, update)); + bot.Events.OnMissingCommandInvoke(context.CreateBotEventArgs()); return UpdateResult.NotFound; } @@ -89,13 +89,13 @@ private async Task UpdateMessageCommands(Update update) /// /// Обновление. /// Результат выполнения. - private UpdateResult EventHandler(Update update) + private UpdateResult EventHandler(IBotContext context) { foreach (var item in TypeMessage) { - if ((int)item.Key == (int)update!.Message!.Type) + if ((int)item.Key == (int)context.Update!.Message!.Type) { - item.Value.Invoke(new BotEventArgs(bot, update)); + item.Value.Invoke(context.CreateBotEventArgs()); return UpdateResult.Handled; } } @@ -174,7 +174,7 @@ private void UpdateEventLink() public MessageUpdateDispatcher(PRBotBase bot) { this.bot = bot; - nextStepHandler = new NextStepCommandHandler(bot); + nextStepHandler = new NextStepCommandHandler(); UpdateEventLink(); } diff --git a/PRTelegramBot/Extensions/BotContextExtension.cs b/PRTelegramBot/Extensions/BotContextExtension.cs new file mode 100644 index 0000000..c24ffe3 --- /dev/null +++ b/PRTelegramBot/Extensions/BotContextExtension.cs @@ -0,0 +1,208 @@ +using PRTelegramBot.Interfaces; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace PRTelegramBot.Extensions +{ + /// + /// Методы расширения для контекста бота. + /// + public static class BotContextExtension + { + #region UpdateExtension + + /// + /// Получает идентификатор чата в зависимости от типа сообщений. + /// + /// Контекст бота. + /// Идентификатор чата. + /// Выбрасывается если не реализована обработка обновления. + public static long GetChatId(this IBotContext context) + { + return context.Update.GetChatId(); + } + + /// + /// Получает идентификатор в формате класса. + /// + /// Контекст бота. + /// Идентификатор в формате класса + public static ChatId GetChatIdClass(this IBotContext context) + { + return context.Update.GetChatIdClass(); + } + + /// + /// Попытаться получить идентификатор чата. + /// + /// Контекст бота. + /// Идентификатор чата. + /// True - удалось получить, false - нет. + public static bool TryGetChatId(this IBotContext context, out long chatId) + { + return context.Update.TryGetChatId(out chatId); + } + + /// + /// Получает идентификатор сообщения. + /// + /// Контекст бота. + /// Идентификатор сообщения. + /// Выбрасывается если не реализована обработка обновления. + public static int GetMessageId(this IBotContext context) + { + return context.Update.GetMessageId(); + } + + /// + /// Является ли идентификатор пользователским чатом. + /// + /// Контекст бота. + /// True - да, False - нет. + public static bool IsUserChatId(this IBotContext context) + { + return context.Update.IsUserChatId(); + } + + /// + /// Информация о пользователе. + /// + /// Контекст бота. + /// Информация о пользователе. + public static string GetInfoUser(this IBotContext context) + { + return context.Update.GetInfoUser(); + } + + /// + /// Получает идентификатор пользователя из обновления Telegram. + /// + /// Контекст бота. + /// Идентификатор пользователя (UserId). + public static long GetUserId(this IBotContext context) + { + return context.Update.GetUserId(); + } + + #endregion + + #region CacheExtension + + /// + /// Создает кеш для пользователя. + /// + /// Тип кэша. + /// Контекст бота. + /// Кэш. + public static TCache CreateCacheData(this IBotContext context) where TCache : ITelegramCache + { + return context.Update.CreateCacheData(); + } + + /// + /// Получает существующий кэш или создает новый. + /// + /// Тип кэша. + /// Контекст бота. + /// Кэш. + /// Если тип кэша отличается от существующего, будет создан кэш нового типа. + public static TCache GetOrCreate(this IBotContext context) where TCache : ITelegramCache + { + return context.Update.GetOrCreate(); + } + + /// + /// Получает кэш пользователя. + /// + /// Тип кэша. + /// Контекст бота. + /// Кэш. + public static TCache GetCacheData(this IBotContext context) where TCache : ITelegramCache + { + return context.Update.GetCacheData(); + } + + /// + /// Очищает кеш пользователя. + /// + /// Контекст бота. + public static void ClearCacheData(this IBotContext context) + { + context.Update.ClearCacheData(); + } + + /// + /// Проверяет существуют ли кеш данные пользователя. + /// + /// Контекст бота. + /// True - есть кэш, False - нет кэша. + public static bool HasCacheData(this IBotContext context) + { + return context.Update.HasCacheData(); + } + + /// + /// Полностью удаляет кэш пользователя из словаря. + /// + /// Контекст бота. + public static void RemoveCacheData(this IBotContext context) + { + context.Update.RemoveCacheData(); + } + + #endregion + + #region StepExtension + + /// + /// Регистрация следующего шага. + /// + /// Контекст бота. + /// Следующая команда которая должна быть выполнена. + public static void RegisterStepHandler(this IBotContext context, IExecuteStep command) + { + context.Update.RegisterStepHandler(command); + } + + /// + /// Получает обработчик или null пользователя. + /// + /// Контекст бота. + /// обработчик или null. + public static TExecuteStep? GetStepHandler(this IBotContext context) where TExecuteStep : IExecuteStep + { + return context.Update.GetStepHandler(); + } + + /// + /// Получить текущий обработчик шага. + /// + /// Контекст бота. + /// Обработчик или null. + public static IExecuteStep? GetStepHandler(this IBotContext context) + { + return context.Update.GetStepHandler(); + } + + /// + /// Очищает шаги пользователя. + /// + /// Контекст бота. + public static void ClearStepUserHandler(this IBotContext context) + { + context.Update.ClearStepUserHandler(); + } + + /// + /// Проверяет есть ли шаг у пользователя. + /// + /// Контекст бота. + /// True - есть обработчик, False - нет обработчика. + public static bool HasStepHandler(this IBotContext context) + { + return context.Update.HasStepHandler(); + } + + #endregion + } +} diff --git a/PRTelegramBot/Extensions/CacheExtension.cs b/PRTelegramBot/Extensions/CacheExtension.cs index ac6cf76..7cfbd40 100644 --- a/PRTelegramBot/Extensions/CacheExtension.cs +++ b/PRTelegramBot/Extensions/CacheExtension.cs @@ -14,7 +14,7 @@ public static class CacheExtension /// /// Словарь для работы который хранит идентификатор пользователя и его кеш. /// - static ConcurrentDictionary _userHandlerData = new(); + static ConcurrentDictionary userHandlerData = new(); #endregion @@ -25,17 +25,39 @@ public static class CacheExtension /// /// Тип кэша. /// Обновление telegram. - public static void CreateCacheData(this Update update) where TCache : ITelegramCache + /// Кэш. + public static TCache CreateCacheData(this Update update) where TCache : ITelegramCache + { + string userKey = update.GetKeyMappingUserTelegram(); + var newData = Activator.CreateInstance(); + userHandlerData.AddOrUpdate(userKey, newData, (_, existingData) => newData); + return newData; + } + + /// + /// Получает существующий кэш или создает новый. + /// + /// Тип кэша. + /// Обновление telegram. + /// Кэш. + /// Если тип кэша отличается от существующего, будет создан кэш нового типа. + public static TCache GetOrCreate(this Update update) where TCache : ITelegramCache { string userKey = update.GetKeyMappingUserTelegram(); - if (_userHandlerData.TryGetValue(userKey, out var data)) + if (userHandlerData.TryGetValue(userKey, out var data)) { - data?.ClearData(); + if (data is TCache cache) + return cache; + + var newData = Activator.CreateInstance(); + userHandlerData.AddOrUpdate(userKey, newData, (_, existingData) => newData); + return newData; } else { var newData = Activator.CreateInstance(); - _userHandlerData.AddOrUpdate(userKey, newData, (_, existingData) => newData); + userHandlerData.AddOrUpdate(userKey, newData, (_, existingData) => newData); + return newData; } } @@ -48,10 +70,10 @@ public static void CreateCacheData(this Update update) where TCache : IT public static TCache GetCacheData(this Update update) where TCache : ITelegramCache { string userKey = update.GetKeyMappingUserTelegram(); - if (!_userHandlerData.TryGetValue(userKey, out var data)) + if (!userHandlerData.TryGetValue(userKey, out var data)) { - update.CreateCacheData(); - return (TCache)_userHandlerData[userKey]; + update.GetOrCreate(); + return (TCache)userHandlerData[userKey]; } return (TCache)data; } @@ -63,7 +85,7 @@ public static TCache GetCacheData(this Update update) where TCache : ITe public static void ClearCacheData(this Update update) { string userKey = update.GetKeyMappingUserTelegram(); - if (_userHandlerData.TryGetValue(userKey, out var data)) + if (userHandlerData.TryGetValue(userKey, out var data)) data.ClearData(); } @@ -76,7 +98,7 @@ public static void ClearCacheData(this Update update) public static bool HasCacheData(this Update update) { string userKey = update.GetKeyMappingUserTelegram(); - return _userHandlerData.ContainsKey(userKey); + return userHandlerData.ContainsKey(userKey); } /// @@ -86,7 +108,7 @@ public static bool HasCacheData(this Update update) public static void RemoveCacheData(this Update update) { string userKey = update.GetKeyMappingUserTelegram(); - _userHandlerData.TryRemove(userKey, out _); + userHandlerData.TryRemove(userKey, out _); } #endregion diff --git a/PRTelegramBot/Extensions/DescriptionExtension.cs b/PRTelegramBot/Extensions/DescriptionExtension.cs index 28c85da..7ae86f9 100644 --- a/PRTelegramBot/Extensions/DescriptionExtension.cs +++ b/PRTelegramBot/Extensions/DescriptionExtension.cs @@ -13,7 +13,7 @@ public static class DescriptionExtension /// Получить атрибут из перечисления. /// /// Тип атрибута. - /// Значение из перечесления. + /// Значение из перечисления. /// Атрибут. internal static TAttribute GetAttribute(this Enum @enum) where TAttribute : Attribute { @@ -25,11 +25,11 @@ internal static TAttribute GetAttribute(this Enum @enum) where TAttr /// /// Позволяет получить описание у Enum. /// - /// Значение из перечесления. + /// Значение из перечисления. /// Описание. public static string GetDescription(this Enum @enum) { - return @enum.GetAttribute()?.Description ?? ""; + return @enum.GetAttribute()?.Description ?? string.Empty; } #endregion diff --git a/PRTelegramBot/Extensions/EventExtension.cs b/PRTelegramBot/Extensions/EventExtension.cs new file mode 100644 index 0000000..1e2f7fa --- /dev/null +++ b/PRTelegramBot/Extensions/EventExtension.cs @@ -0,0 +1,21 @@ +using PRTelegramBot.Interfaces; +using PRTelegramBot.Models.EventsArgs; + +namespace PRTelegramBot.Extensions +{ + /// + /// Методы расширения для событий. + /// + public static class EventExtension + { + /// + /// Создать базовые аргументы событий для контекста. + /// + /// Контекст бота. + /// Аргументы. + public static BotEventArgs CreateBotEventArgs(this IBotContext context) + { + return new BotEventArgs(context); + } + } +} \ No newline at end of file diff --git a/PRTelegramBot/Extensions/ITelegramBotClientExtension.cs b/PRTelegramBot/Extensions/ITelegramBotClientExtension.cs index 3c41507..7d94add 100644 --- a/PRTelegramBot/Extensions/ITelegramBotClientExtension.cs +++ b/PRTelegramBot/Extensions/ITelegramBotClientExtension.cs @@ -1,7 +1,6 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Interfaces; +using PRTelegramBot.Interfaces; +using PRTelegramBot.Models.EventsArgs; using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Extensions { @@ -15,130 +14,99 @@ public static class ITelegramBotClientExtension /// /// Проверяет пользователя, является ли он администратором бота. /// - /// Бот клиент. - /// Обновление из telegram. + /// Контекст бота. /// True - администратор, False - не администратор. - public static async Task IsAdmin(this ITelegramBotClient botClient, Update update) + public static async Task IsAdmin(this IBotContext context) { - return await IsAdmin(botClient, update.GetChatId()); + return await IsAdmin(context); } /// /// Проверяет пользователя, является ли он администратором бота. /// - /// Бот клиент. + /// Контекст бота. /// Идентификатор пользователя. /// True - администратор, False - не администратор. - public static async Task IsAdmin(this ITelegramBotClient botClient, long userId) + public static async Task IsAdmin(this IBotContext context, long userId) { - var botData = GetBotDataOrNull(botClient); - return botData != null && await botData.Options.AdminManager.HasUser(userId); + return await context.Current.Options.AdminManager.HasUser(userId); } /// /// Проверяет пользователя, присутствует ли в белом списке бота. /// - /// Бот клиент. - /// Обновление из telegram. + /// Контекст бота. /// True - есть в списке, False - нет в списке. - public static async Task InWhiteList(this ITelegramBotClient botClient, Update update) + public static async Task InWhiteList(this IBotContext context) { - return await InWhiteList(botClient, update.GetChatId()); + return await InWhiteList(context, context.Update.GetChatId()); } /// /// Проверяет пользователя, присутствует ли в белом списке бота. /// - /// Бот клиент. - /// Идентификатор пользователя. + /// Контекст бота. /// True - есть в списке, False - нет в списке. - public static async Task InWhiteList(this ITelegramBotClient botClient, long userId) + public static async Task InWhiteList(this IBotContext context, long userId) { - var botData = GetBotDataOrNull(botClient); - return botData != null && await botData.Options.WhiteListManager.HasUser(userId); + return await context.Current.Options.WhiteListManager.HasUser(userId); } /// - /// Возращает список администраторов бота. + /// Возвращает список администраторов бота. /// - /// Бот клиент. + /// Контекст бота. /// Список идентификаторов. - public static async Task> GetAdminsIds(this ITelegramBotClient botClient) + public static async Task> GetAdminsIds(this IBotContext context) { - var botData = GetBotDataOrNull(botClient); - return botData != null ? await botData.Options.AdminManager.GetUsersIds() : new List(); + return await context.Current.Options.AdminManager.GetUsersIds(); } /// - /// Возращает белый список пользователей. + /// Возвращает белый список пользователей. /// - /// Бот клиент. + /// Контекст бота. /// Список идентификаторов. - public static async Task> GetWhiteListIds(this ITelegramBotClient botClient) + public static async Task> GetWhiteListIds(this IBotContext context) { - var botData = GetBotDataOrNull(botClient); - return botData != null ? await botData.Options.WhiteListManager.GetUsersIds() : new List(); - } - - /// - /// Получить экземпляр класса бота. - /// - /// Бот клиент. - /// Экземпляр класса или null. - public static PRBotBase GetBotDataOrNull(this ITelegramBotClient botClient) - { - return BotCollection.Instance.GetBotByTelegramIdOrNull(botClient.BotId); + return await context.Current.Options.WhiteListManager.GetUsersIds(); } /// /// Вызов события простого лога. /// - /// Бот. + /// Контекст бота. /// Сообщение. /// Тип события. /// Цвет. - public static void InvokeCommonLog(this ITelegramBotClient botClient, string msg, string typeEvent = "", ConsoleColor color = ConsoleColor.Blue) - { - var bot = GetBotDataOrNull(botClient); - bot?.Events.OnCommonLogInvoke(msg, typeEvent, color); - } - - /// - /// Вызов события логирование ошибок. - /// - /// Бот. - /// Исключение. - public static void InvokeErrorLog(this ITelegramBotClient botClient, Exception ex) + public static void InvokeCommonLog(this IBotContext context, string msg, string typeEvent = "", ConsoleColor color = ConsoleColor.Blue) { - var bot = GetBotDataOrNull(botClient); - bot?.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnCommonLogInvoke(msg, typeEvent, color); } /// /// Вызов события логирование ошибок. /// - /// Бот. + /// Контекст бота. /// Исключение. - /// обновление. - public static void InvokeErrorLog(this ITelegramBotClient botClient, Exception ex, Update update) + public static void InvokeErrorLog(this IBotContext context, Exception ex) { - var bot = GetBotDataOrNull(botClient); - bot?.Events.OnErrorLogInvoke(ex, update); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); } /// /// Генерация реферальной ссылки. /// - /// Бот. + /// Контекст бота. /// Текст реферальной ссылки. /// Сгенерированная реферальная ссылка https://t.me/{bot.Username}?start={refLink}. /// Вызывается в случае пустого текста. - public async static Task GetGeneratedRefLink(this ITelegramBotClient botClient, string refLink) + public async static Task GetGeneratedRefLink(this IBotContext context, string refLink) { if (string.IsNullOrEmpty(refLink)) throw new ArgumentNullException(nameof(refLink)); - var bot = await botClient.GetMe(); + var bot = await context.BotClient.GetMe(); return $"https://t.me/{bot.Username}?start={refLink}"; } @@ -147,14 +115,14 @@ public async static Task GetGeneratedRefLink(this ITelegramBotClient bot /// /// Провайдера работы с файлами. /// Возращаемый тип. - /// Бот клиент. + /// Контекст бота. /// Ключ конфига. /// Ключ для значения. /// Значение из конфиг файла. - public static TReturn GetConfigValue(this ITelegramBotClient botClient, string configKey, string key) + public static TReturn GetConfigValue(this IBotContext context, string configKey, string key) where TBotProvider : IBotConfigProvider { - string configPath = botClient.GetBotDataOrNull().Options.ConfigPaths[configKey]; + string configPath = context.Current.Options.ConfigPaths[configKey]; var botConfiguration = Activator.CreateInstance(typeof(TBotProvider)) as IBotConfigProvider; botConfiguration.SetConfigPath(configPath); return botConfiguration.GetValue(key); @@ -165,21 +133,21 @@ public static TReturn GetConfigValue(this ITelegramBotCli /// /// Провайдера работы с файлами. /// Возращаемый тип. - /// Бот клиент. + /// Контекст бота. /// Ключ конфига. /// Ключ для значения. /// Значение. /// True - значение получено, False - не удалось получить значение. - public static bool TryGetConfigValue(this ITelegramBotClient botClient, string configKey, string key, out TReturn result) + public static bool TryGetConfigValue(this IBotContext context, string configKey, string key, out TReturn result) where TBotProvider : IBotConfigProvider, new() { result = default(TReturn); try { var botConfiguration = new TBotProvider(); // Создание экземпляра поставщика конфигурации - string configPath = botClient.GetBotDataOrNull()?.Options?.ConfigPaths?.GetValueOrDefault(configKey); + string configPath = context.Current.Options?.ConfigPaths?.GetValueOrDefault(configKey); - if (configPath == null) + if (configPath is null) { // Если путь конфигурации не найден, возвращаем false return false; diff --git a/PRTelegramBot/Extensions/MessageExtension.cs b/PRTelegramBot/Extensions/MessageExtension.cs index 617f49d..91e12b1 100644 --- a/PRTelegramBot/Extensions/MessageExtension.cs +++ b/PRTelegramBot/Extensions/MessageExtension.cs @@ -1,4 +1,5 @@ -using Telegram.Bot; +using PRTelegramBot.Interfaces; +using Telegram.Bot; using Telegram.Bot.Types; namespace PRTelegramBot.Extensions @@ -13,17 +14,16 @@ public static class MessageExtension /// /// Сообщение которое нужно удалить. /// Через сколько секунд будет удалено сообщение. - /// Бот клиент. - /// Update. - public static void AutoDeleteMessage(this Message message, int seconds, ITelegramBotClient botClient, Update update) + /// Контекст бота. + public static void AutoDeleteMessage(this Message message, int seconds, IBotContext context) { - if(message == null) + if(message is null) return; _ = Task.Run(async () => { await Task.Delay(seconds * 1000); - await botClient.DeleteMessage(update.GetChatIdClass(), message.MessageId); + await context.BotClient.DeleteMessage(context.Update.GetChatIdClass(), message.MessageId); }); } @@ -31,18 +31,18 @@ public static void AutoDeleteMessage(this Message message, int seconds, ITelegra /// Автоматическое редактирования сообщения через определенное время. /// /// Сообщение которое нужно удалить. + /// Текст сообщения. /// Через сколько секунд будет удалено сообщение. - /// Бот клиент. - /// Update. - public static void AutoEditMessage(this Message message, string messageText, int seconds, ITelegramBotClient botClient, Update update) + /// Контекст бота. + public static void AutoEditMessage(this Message message, string messageText, int seconds, IBotContext context) { - if (message == null) + if (message is null) return; _ = Task.Run(async () => { await Task.Delay(seconds * 1000); - await botClient.EditMessageText(update.GetChatIdClass(), message.MessageId, messageText); + await context.BotClient.EditMessageText(context.Update.GetChatIdClass(), message.MessageId, messageText); }); } @@ -50,12 +50,12 @@ public static void AutoEditMessage(this Message message, string messageText, int /// Автоматическое редактирования сообщения через определенное время в цикле. /// /// Сообщение которое нужно удалить. + /// Коллекция текстов сообщений. /// Через сколько секунд будет удалено сообщение. - /// Бот клиент. - /// Update. - public static void AutoEditMessageСycle(this Message message, List messageTexts, int seconds, ITelegramBotClient botClient, Update update) + /// Контекст бота. + public static void AutoEditMessageСycle(this Message message, List messageTexts, int seconds, IBotContext context) { - if (message == null) + if (message is null) return; _ = Task.Run(async () => @@ -63,7 +63,7 @@ public static void AutoEditMessage(this Message message, string messageText, int foreach (var text in messageTexts) { await Task.Delay(seconds * 1000); - await botClient.EditMessageText(update.GetChatIdClass(), message.MessageId, text); + await context.BotClient.EditMessageText(context.Update.GetChatIdClass(), message.MessageId, text); } }); } diff --git a/PRTelegramBot/Extensions/ServiceProviderExtension.cs b/PRTelegramBot/Extensions/ServiceProviderExtension.cs index be3e00c..772bda9 100644 --- a/PRTelegramBot/Extensions/ServiceProviderExtension.cs +++ b/PRTelegramBot/Extensions/ServiceProviderExtension.cs @@ -59,7 +59,7 @@ public static IServiceCollection AddSingletonBotHandlers(this IServiceCollection /// Обновленная коллекция сервисов. private static IServiceCollection AddBotHandlersInDI(this IServiceCollection services, LifeCycle lifeCycle) { - if (services == null) + if (services is null) throw new ArgumentNullException(nameof(services)); var types = ReflectionUtils.FindClassesWithBotHandlerAttribute(); diff --git a/PRTelegramBot/Extensions/StepExtension.cs b/PRTelegramBot/Extensions/StepExtension.cs index beb3d1f..5ae5f69 100644 --- a/PRTelegramBot/Extensions/StepExtension.cs +++ b/PRTelegramBot/Extensions/StepExtension.cs @@ -14,7 +14,7 @@ public static class StepExtension /// /// Список шагов для пользователя. /// - static ConcurrentDictionary _step = new(); + static ConcurrentDictionary step = new(); #endregion @@ -29,7 +29,7 @@ public static void RegisterStepHandler(this Update update, IExecuteStep command) { string userKey = update.GetKeyMappingUserTelegram(); update.ClearStepUserHandler(); - _step.AddOrUpdate(userKey, command, (_, existingData) => command); + step.AddOrUpdate(userKey, command, (_, existingData) => command); } /// @@ -40,7 +40,7 @@ public static void RegisterStepHandler(this Update update, IExecuteStep command) public static TExecuteStep? GetStepHandler(this Update update) where TExecuteStep : IExecuteStep { string userKey = update.GetKeyMappingUserTelegram(); - return _step.TryGetValue(userKey, out var data) && data is TExecuteStep stepHandler + return step.TryGetValue(userKey, out var data) && data is TExecuteStep stepHandler ? stepHandler : default(TExecuteStep); } @@ -63,7 +63,7 @@ public static void ClearStepUserHandler(this Update update) { string userKey = update.GetKeyMappingUserTelegram(); if (update.HasStepHandler()) - _step.Remove(userKey, out _); + step.Remove(userKey, out _); } /// @@ -74,7 +74,7 @@ public static void ClearStepUserHandler(this Update update) public static bool HasStepHandler(this Update update) { string userKey = update.GetKeyMappingUserTelegram(); - return _step.ContainsKey(userKey); + return step.ContainsKey(userKey); } #endregion diff --git a/PRTelegramBot/Extensions/UpdateExtension.cs b/PRTelegramBot/Extensions/UpdateExtension.cs index 900831b..3cad9da 100644 --- a/PRTelegramBot/Extensions/UpdateExtension.cs +++ b/PRTelegramBot/Extensions/UpdateExtension.cs @@ -1,5 +1,6 @@ using PRTelegramBot.Core; using PRTelegramBot.Models; +using PRTelegramBot.Models.EventsArgs; using System.Collections.Concurrent; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; @@ -7,7 +8,7 @@ namespace PRTelegramBot.Extensions { /// - /// Методы расширения для update в телеграм. + /// Методы расширения для update в telegram. /// public static class UpdateExtension { @@ -77,7 +78,7 @@ public static bool TryGetChatId(this Update update, out long chatId) chatId = update.GetChatId(); return true; } - catch(Exception e) + catch { return false; } @@ -114,7 +115,7 @@ public static bool IsUserChatId(this Update update) catch(Exception ex) { if(update.TryGetBot(out var bot)) - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, ex)); return false; } } @@ -144,14 +145,14 @@ public static string GetInfoUser(this Update update) UpdateType.MyChatMember => GetFullNameFromChat(update.MyChatMember.Chat), UpdateType.PollAnswer => GetFullNameFromChat(update.PollAnswer.VoterChat), UpdateType.RemovedChatBoost => GetFullNameFromChat(update.RemovedChatBoost.Chat), - _ => "" + _ => string.Empty }; } /// /// Попытаться получить бота из update. /// - /// Обновление телеграм. + /// Обновление telegram. /// Возвращаемый объект бота. /// True, если бот найден; иначе False. public static bool TryGetBot(this Update update, out PRBotBase bot) @@ -159,15 +160,38 @@ public static bool TryGetBot(this Update update, out PRBotBase bot) return botLink.TryGetValue(update.Id, out bot); } + /// + /// Получает идентификатор пользователя из обновления Telegram. + /// + /// Объект обновления Telegram. + /// Идентификатор пользователя (UserId). + public static long GetUserId(this Update update) + { + return update.Type switch + { + UpdateType.Message => update.Message.From.Id, + UpdateType.CallbackQuery => update.CallbackQuery.Message.From.Id, + UpdateType.BusinessMessage => update.BusinessMessage.From.Id, + UpdateType.ChannelPost => update.ChannelPost.From.Id, + UpdateType.ChatJoinRequest => update.ChatJoinRequest.From.Id, + UpdateType.ChatMember => update.ChatMember.From.Id, + UpdateType.EditedBusinessMessage => update.EditedBusinessMessage.From.Id, + UpdateType.EditedChannelPost => update.EditedChannelPost.From.Id, + UpdateType.EditedMessage => update.EditedMessage.From.Id, + UpdateType.MyChatMember => update.MyChatMember.From.Id, + _ => throw new NotImplementedException($"Not implemented get userId for {update.Type}") + }; + } + /// /// Связать update с PRBotBase. /// /// Обновление telegram. - /// Экзпляр PRBotBase. + /// Экземпляр PRBotBase. /// True - удалось добавить, False - не удалось. internal static bool AddTelegramClient(this Update update, PRBotBase bot) { - if(update == null) + if(update is null) return false; return botLink.TryAdd(update.Id, bot); @@ -204,11 +228,11 @@ internal static bool ClearTelegramClient(this Update update) /// Информация. private static string GetFullNameFromChat(Chat chat) { - string result = ""; + string result = string.Empty; result += chat?.Id + " "; - result += string.IsNullOrEmpty(chat.FirstName) ? "" : chat.FirstName + " "; - result += string.IsNullOrEmpty(chat?.LastName) ? "" : chat.LastName + " "; - result += string.IsNullOrEmpty(chat?.Username) ? "" : chat.Username + " "; + result += string.IsNullOrEmpty(chat.FirstName) ? string.Empty : chat.FirstName + " "; + result += string.IsNullOrEmpty(chat?.LastName) ? string.Empty : chat.LastName + " "; + result += string.IsNullOrEmpty(chat?.Username) ? string.Empty : chat.Username + " "; return result; } diff --git a/PRTelegramBot/Extensions/UpdateResultExtension.cs b/PRTelegramBot/Extensions/UpdateResultExtension.cs index 21aaa63..ebee497 100644 --- a/PRTelegramBot/Extensions/UpdateResultExtension.cs +++ b/PRTelegramBot/Extensions/UpdateResultExtension.cs @@ -1,7 +1,5 @@ -using PRTelegramBot.Core; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; -using PRTelegramBot.Models.EventsArgs; -using Telegram.Bot.Types; namespace PRTelegramBot.Extensions { @@ -14,14 +12,13 @@ internal static class UpdateResultExtension /// Продолжить обработку. /// /// Результат update. - /// Бот. - /// Update. + /// Контекст бота. /// True - продолжить, False - нет. - public static bool IsContinueHandle(this UpdateResult result, PRBotBase bot, Update update) + public static bool IsContinueHandle(this UpdateResult result, IBotContext context) { if (result == UpdateResult.Error) { - bot.Events.OnErrorCommandInvoke(new BotEventArgs(bot, update)); + context.Current.Events.OnErrorCommandInvoke(context.CreateBotEventArgs()); return false; } diff --git a/PRTelegramBot/Helpers/FileWorker.cs b/PRTelegramBot/Helpers/FileWorker.cs index 08501c2..190e793 100644 --- a/PRTelegramBot/Helpers/FileWorker.cs +++ b/PRTelegramBot/Helpers/FileWorker.cs @@ -1,4 +1,5 @@ -using System.Reflection; +using PRTelegramBot.Interfaces; +using System.Reflection; using Telegram.Bot; namespace PRTelegramBot.Helpers @@ -16,22 +17,21 @@ public static class FileWorker /// /// Скачивание файлов с telegram серверов /// - /// Telegram клиент + /// Контекст бота. /// Идентификатор пользователя /// Идентификатор файла /// Название файла /// Путь до файла - public static async Task DownloadFileFromTelegram(ITelegramBotClient botClient, long telegramId, string fileId, string fileName) + public static async Task DownloadFileFromTelegram(IBotContext context, long telegramId, string fileId, string fileName) { - string folder = $"/Uploads/Users/{telegramId}/"; - string fullPath = BaseDir + folder + "/" +fileName; - string dbpath = folder + "/" +fileName; - if (!Directory.Exists(BaseDir + folder)) - { - Directory.CreateDirectory(BaseDir + folder); - } - await using Stream fileStream = System.IO.File.OpenWrite(fullPath); - var file = await botClient.GetInfoAndDownloadFile( + string folder = Path.Combine("Uploads", "Users", telegramId.ToString()); + string fullPath = Path.Combine(BaseDir, folder, fileName); + string dbpath = Path.Combine(folder, fileName).Replace('\\', '/'); + + Directory.CreateDirectory(Path.Combine(BaseDir, folder)); + + await using Stream fileStream = File.OpenWrite(fullPath); + var file = await context.BotClient.GetInfoAndDownloadFile( fileId: fileId, destination: fileStream); return dbpath; @@ -44,15 +44,13 @@ public static async Task DownloadFileFromTelegram(ITelegramBotClient bot /// Потом /// Название файла /// - public static string SaveFileToUser(long telegramId,MemoryStream stream, string fileName) + public static string SaveFileToUser(long telegramId, MemoryStream stream, string fileName) { - string folder = $"/Uploads/Users/{telegramId}/"; - string fullPath = BaseDir + folder + "/" + fileName; - string dbpath = folder + "/" + fileName; - if (!Directory.Exists(BaseDir + folder)) - { - Directory.CreateDirectory(BaseDir + folder); - } + string folder = Path.Combine("Uploads", "Users", telegramId.ToString()); + string fullPath = Path.Combine(BaseDir, folder, fileName); + + Directory.CreateDirectory(Path.Combine(BaseDir, folder)); + File.WriteAllBytes(fullPath, stream.ToArray()); return fullPath; } diff --git a/PRTelegramBot/Helpers/Message.cs b/PRTelegramBot/Helpers/Message.cs index 165eaa4..b8422bb 100644 --- a/PRTelegramBot/Helpers/Message.cs +++ b/PRTelegramBot/Helpers/Message.cs @@ -1,4 +1,5 @@ using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Utils; using Telegram.Bot; @@ -21,15 +22,34 @@ public class Message #region Методы + /// + /// Копирует коллекцию сообщений. + /// + /// Контекст бота. + /// Сообщения. + /// Идентификатор чата. + /// Параметры сообщения. + /// Коллекция идентификаторов сообщений. + public static async Task> CopyMessages(IBotContext context, List messages, long chatId, OptionMessage option = null) + { + option = CreateOptionsIfNull(option); + List messageIds = new List(); + + foreach (var message in messages) + messageIds.Add(await CopyMessage(context, message, chatId, option)); + + return messageIds; + } + /// /// Копировать сообщение. /// - /// Клиент telegram бота. + /// Контекст бота. /// Сообщение. /// Идентификатор чата. /// Параметры сообщения. /// Идентификатор сообщения. - public static async Task CopyMessage(ITelegramBotClient botClient, Telegram.Bot.Types.Message message, long chatId, OptionMessage option = null) + public static async Task CopyMessage(IBotContext context, Telegram.Bot.Types.Message message, long chatId, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); @@ -37,78 +57,77 @@ public static async Task CopyMessage(ITelegramBotClient botClient, Te ChatId toMsg = new ChatId(chatId); ChatId fromMsg = new ChatId(message.Chat.Id); - var rMessage = await botClient.CopyMessage( - chatId: toMsg, - fromChatId: fromMsg, - messageId: message.MessageId, - messageThreadId: option.MessageThreadId, - caption: option.Caption, - parseMode: option.ParseMode, - captionEntities: option.Entities, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - replyMarkup: replyMarkup, - cancellationToken: option.CancellationToken); - return rMessage; + var messageId = await context.BotClient.CopyMessage( + chatId: toMsg, + fromChatId: fromMsg, + messageId: message.MessageId, + messageThreadId: option.MessageThreadId, + caption: option.Caption, + parseMode: option.ParseMode, + captionEntities: option.Entities, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + replyMarkup: replyMarkup, + cancellationToken: option.CancellationToken); + return messageId; } /// - /// Копирует коллекцию сообщений. + /// Сообщение ожидание обработки сообщения. /// - /// Клиент телеграм бота. - /// Сообщения. + /// Контекст бота. /// Идентификатор чата. + /// Текст сообщения. /// Параметры сообщения. - /// Коллекция идентификаторов сообщений. - public static async Task> CopyMessages(ITelegramBotClient botClient, List messages, long chatId, OptionMessage option = null) + /// Сообщение. + public static async Task AwaitAnswerBot(IBotContext context, long chatId, string message = "⏳ Генерирую ответ...", OptionMessage option = null) { option = CreateOptionsIfNull(option); - List messageIds = new List(); - foreach (var message in messages) - messageIds.Add(await CopyMessage(botClient, message, chatId, option)); - return messageIds; + var sentMessage = await Send(context, chatId, message, option); + return sentMessage; } /// - /// Сообщение ожидание обработки сообщения. + /// Отправка сообщения. /// - /// Клиент телеграм бота. - /// Идентификатор чата. - /// Параметры сообщения. + /// Контекст бота. + /// Обновление телерграм. + /// Текст. + /// Настройка сообщения. /// Сообщение. - public static async Task AwaitAnswerBot(ITelegramBotClient botClient, long chatId, string message = "⏳ Генерирую ответ...", OptionMessage option = null) + public static async Task Send(IBotContext context, Update update, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); - var sentMessage = await Send(botClient, chatId, message, option); - return sentMessage; + + var message = await Send(context, update.GetChatId(), text, option); + return message; } /// /// Отправка сообщения. /// - /// Клиент телеграм бота. - /// Обновление телерграм. + /// Контекст бота. /// Текст. /// Настройка сообщения. /// Сообщение. - public static async Task Send(ITelegramBotClient botClient, Update update, string text, OptionMessage option = null) + public static async Task Send(IBotContext context, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); - var message = await Send(botClient, update.GetChatId(), text, option); + var message = await Send(context, context.Update.GetChatId(), text, option); return message; } /// /// Отправка сообщения. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Текст. /// Настройка сообщения. /// Сообщение. - public static async Task Send(ITelegramBotClient botClient, long chatId, string text, OptionMessage option = null) + public static async Task Send(IBotContext context, long chatId, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); @@ -123,35 +142,36 @@ public static async Task> CopyMessages(ITelegramBotClient botCli { count++; if (count < chunk.Count) - await Send(botClient, chatId, item, option); + await Send(context, chatId, item, option); if (count == chunk.Count) text = item; } } - return await botClient.SendMessage( - chatId: chatId, - text: text, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - messageThreadId: option.MessageThreadId, - entities: option.Entities, - linkPreviewOptions: linkOptions, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - cancellationToken: option.CancellationToken); + return await context.BotClient.SendMessage( + chatId: chatId, + text: text, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + messageThreadId: option.MessageThreadId, + entities: option.Entities, + linkPreviewOptions: linkOptions, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + cancellationToken: option.CancellationToken); } /// /// Отправка группы фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Текст. /// Путь к файлам. + /// Настройка сообщения. /// Коллекция сообщений. - public static async Task SendPhotoGroup(ITelegramBotClient botClient, long chatId, string text, List filepaths, OptionMessage option = null) + public static async Task SendPhotoGroup(IBotContext context, long chatId, string text, List filepaths, OptionMessage option = null) { option = CreateOptionsIfNull(option); List media = new(); @@ -182,7 +202,7 @@ public static async Task> CopyMessages(ITelegramBotClient botCli } - return await botClient.SendMediaGroup( + return await context.BotClient.SendMediaGroup( chatId: chatId, media: media.ToArray(), messageThreadId:option.MessageThreadId, @@ -195,57 +215,58 @@ public static async Task> CopyMessages(ITelegramBotClient botCli /// /// Отправка сообщения с фото. /// - /// Клиент телеграм бота. - /// Идентификатор чата<./param> + /// Контекст бота. + /// Идентификатор чата. /// Текст. /// Путь к файлу. /// Настройки сообщения. /// Сообщение. - public static async Task SendPhoto(ITelegramBotClient botClient, long chatId, string text, string filePath, OptionMessage option = null) + public static async Task SendPhoto(IBotContext context, long chatId, string text, string filePath, OptionMessage option = null) { option = CreateOptionsIfNull(option); - if (!System.IO.File.Exists(filePath)) - return await Send(botClient, chatId, text, option); + if (!File.Exists(filePath)) + return await Send(context, chatId, text, option); using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) - return await SendPhoto(botClient, chatId, text, fileStream, option); + return await SendPhoto(context, chatId, text, fileStream, option); } /// /// Отправка файла. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Текст. /// Путь к файлу. + /// Настройки сообщения. /// Сообщение. - public static async Task SendFile(ITelegramBotClient botClient, long chatId, string text, string filePath, OptionMessage option = null) + public static async Task SendFile(IBotContext context, long chatId, string text, string filePath, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); var replyParams = CreateReplyParametersFromOptions(option); - if (!System.IO.File.Exists(filePath)) + if (!File.Exists(filePath)) { - var message = await Send(botClient, chatId, text, option); + var message = await Send(context, chatId, text, option); return message; } using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { - var message = await botClient.SendDocument(chatId: chatId, - document: InputFile.FromStream(fileStream, Path.GetFileName(filePath)), - caption: text, - messageThreadId: option.MessageThreadId, - replyMarkup: replyMarkup, - thumbnail: option.thumbnail, - parseMode: option.ParseMode, - captionEntities: option.Entities, - disableContentTypeDetection: option.DisableContentTypeDetection, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - cancellationToken: option.CancellationToken); + var message = await context.BotClient.SendDocument(chatId: chatId, + document: InputFile.FromStream(fileStream, Path.GetFileName(filePath)), + caption: text, + messageThreadId: option.MessageThreadId, + replyMarkup: replyMarkup, + thumbnail: option.thumbnail, + parseMode: option.ParseMode, + captionEntities: option.Entities, + disableContentTypeDetection: option.DisableContentTypeDetection, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + cancellationToken: option.CancellationToken); return message; } @@ -254,232 +275,211 @@ public static async Task> CopyMessages(ITelegramBotClient botCli /// /// Редактирование сообщения. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Текст. /// Настройки сообщения. /// Сообщение. - public static async Task Edit(ITelegramBotClient botClient, long chatId, int messageId, string text, OptionMessage option = null) + public static async Task Edit(IBotContext context, long chatId, int messageId, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option) as InlineKeyboardMarkup; var linkOptions = CreateLinkPreviewOptionsFromOption(option); - return await botClient.EditMessageText( - chatId: chatId, - messageId: messageId, - text: text, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - entities: option.Entities, - linkPreviewOptions: linkOptions, - cancellationToken: option.CancellationToken); + return await context.BotClient.EditMessageText( + chatId: chatId, + messageId: messageId, + text: text, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + entities: option.Entities, + linkPreviewOptions: linkOptions, + cancellationToken: option.CancellationToken); } /// /// Редактирование сообщения. /// - /// Клиент телеграм бота. - /// Обновление телеграм. + /// Контекст бота. /// Текст. /// Настройки сообщения. /// Сообщение. - public static async Task Edit(ITelegramBotClient botClient, Update update, string text, OptionMessage option = null) + public static async Task Edit(IBotContext context, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); - long chatId = update.GetChatId(); - int messageId = update.GetMessageId(); + long chatId = context.GetChatId(); + int messageId = context.GetMessageId(); - var editmessage = await Edit(botClient, chatId, messageId, text, option); - return editmessage; + var editMessage = await Edit(context, chatId, messageId, text, option); + return editMessage; } /// /// Редактировать текст под фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Текст. /// Параметры сообщения. - /// Сообщщения. - public static async Task EditCaption(ITelegramBotClient botClient, long chatId, int messageId, string text, OptionMessage option = null) + /// Сообщение. + public static async Task EditCaption(IBotContext context, long chatId, int messageId, string text, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option) as InlineKeyboardMarkup; - return await botClient.EditMessageCaption( - chatId: chatId, - messageId: messageId, - caption: text, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - captionEntities: option.Entities, - cancellationToken: option.CancellationToken); + return await context.BotClient.EditMessageCaption( + chatId: chatId, + messageId: messageId, + caption: text, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + captionEntities: option.Entities, + cancellationToken: option.CancellationToken); } /// /// Редактирование фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Путь к фото. - /// Насройки сообщения. + /// Настройка сообщения. /// Сообщение. - public static async Task EditPhoto(ITelegramBotClient botClient, long chatId, int messageId, string photoPath, OptionMessage option = null) + public static async Task EditPhoto(IBotContext context, long chatId, int messageId, string photoPath, OptionMessage option = null) { option = CreateOptionsIfNull(option); - Telegram.Bot.Types.Message message; - if (!System.IO.File.Exists(photoPath)) - return await EditInline(botClient, chatId, messageId, option); - + if (!File.Exists(photoPath)) + return await EditInline(context, chatId, messageId, option); using (var fileStream = new FileStream(photoPath, FileMode.Open, FileAccess.Read, FileShare.Read)) - return await EditPhoto(botClient, chatId, messageId, fileStream, option: option); + return await EditPhoto(context, chatId, messageId, fileStream, option: option); } /// /// Удалить сообщение. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. - public static async Task DeleteMessage(ITelegramBotClient botClient, long chatId, int messageId, OptionMessage option = null) - { - option = CreateOptionsIfNull(option); - await botClient.DeleteMessage(chatId, messageId, option.CancellationToken); - } - - /// - /// Редактирование текста под фото. - /// - /// Клиент телеграм бота. - /// Обновление телеграм. - /// Текст. - /// Параметры сообщения. - /// Сообщение. - public static async Task EditCaption(ITelegramBotClient botClient, Update update, string text, OptionMessage option = null) + /// Настройка сообщения. + public static async Task DeleteMessage(IBotContext context, long chatId, int messageId, OptionMessage option = null) { option = CreateOptionsIfNull(option); - - long chatId = update.GetChatId(); - int messageId = update.GetMessageId(); - - var editmessage = await EditCaption(botClient, chatId, messageId, text, option); - return editmessage; + await context.BotClient.DeleteMessage(chatId, messageId, option.CancellationToken); } /// /// Отправка сообщения с фото. /// - /// Клиент телеграм бота<./param> + /// Контекст бота. /// Идентификатор чата. /// Текст. /// Поток. /// Настройки сообщения. /// Сообщение. - public static async Task SendPhoto(ITelegramBotClient botClient, long chatId, string text, Stream stream, OptionMessage option = null) + public static async Task SendPhoto(IBotContext context, long chatId, string text, Stream stream, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); var replyParams = CreateReplyParametersFromOptions(option); - return await botClient.SendPhoto( - chatId: chatId, - photo: InputFile.FromStream(stream), - caption: text, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - messageThreadId: option.MessageThreadId, - captionEntities: option.Entities, - hasSpoiler: option.HasSpoiler, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - cancellationToken: option.CancellationToken); + return await context.BotClient.SendPhoto( + chatId: chatId, + photo: InputFile.FromStream(stream), + caption: text, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + messageThreadId: option.MessageThreadId, + captionEntities: option.Entities, + hasSpoiler: option.HasSpoiler, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + cancellationToken: option.CancellationToken); } /// /// Отправка сообщения с фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Текст. /// url. /// Настройки сообщения. /// Сообщение. - public static async Task SendPhotoWithUrl(ITelegramBotClient botClient, long chatId, string msg, string url, OptionMessage option = null) + public static async Task SendPhotoWithUrl(IBotContext context, long chatId, string msg, string url, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); var replyParams = CreateReplyParametersFromOptions(option); - return await botClient.SendPhoto( - chatId: chatId, - photo: InputFile.FromString(url), - caption: msg, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - messageThreadId: option.MessageThreadId, - captionEntities: option.Entities, - hasSpoiler: option.HasSpoiler, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - cancellationToken: option.CancellationToken); + return await context.BotClient.SendPhoto( + chatId: chatId, + photo: InputFile.FromString(url), + caption: msg, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + messageThreadId: option.MessageThreadId, + captionEntities: option.Entities, + hasSpoiler: option.HasSpoiler, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + cancellationToken: option.CancellationToken); } /// /// Отправка сообщения с фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Текст. /// url. /// Настройки сообщения. /// Сообщение. - public static async Task SendMediaWithUrl(ITelegramBotClient botClient, long chatId, string msg, string url, OptionMessage option = null) + public static async Task SendMediaWithUrl(IBotContext context, long chatId, string msg, string url, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option); var replyParams = CreateReplyParametersFromOptions(option); - return await botClient.SendDocument( - chatId: chatId, - document: InputFile.FromString(url), - caption: msg, - parseMode: option.ParseMode, - replyMarkup: replyMarkup, - messageThreadId: option.MessageThreadId, - captionEntities: option.Entities, - disableContentTypeDetection: option.DisableContentTypeDetection, - disableNotification: option.DisableNotification, - protectContent: option.ProtectedContent, - replyParameters: replyParams, - cancellationToken: option.CancellationToken); + return await context.BotClient.SendDocument( + chatId: chatId, + document: InputFile.FromString(url), + caption: msg, + parseMode: option.ParseMode, + replyMarkup: replyMarkup, + messageThreadId: option.MessageThreadId, + captionEntities: option.Entities, + disableContentTypeDetection: option.DisableContentTypeDetection, + disableNotification: option.DisableNotification, + protectContent: option.ProtectedContent, + replyParameters: replyParams, + cancellationToken: option.CancellationToken); } /// /// Редактирование меню inline. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Насройки сообщения. /// Сообщение. - public static async Task EditInline(ITelegramBotClient botClient, long chatId, int messageId, OptionMessage option) + public static async Task EditInline(IBotContext context, long chatId, int messageId, OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option) as InlineKeyboardMarkup; Telegram.Bot.Types.Message message = null; - if (option?.MenuInlineKeyboardMarkup != null) + if (option?.MenuInlineKeyboardMarkup is not null) { - message = await botClient.EditMessageReplyMarkup( - chatId: chatId, - messageId: messageId, - replyMarkup: replyMarkup, - cancellationToken: option.CancellationToken); + message = await context.BotClient.EditMessageReplyMarkup( + chatId: chatId, + messageId: messageId, + replyMarkup: replyMarkup, + cancellationToken: option.CancellationToken); } return message; @@ -488,56 +488,57 @@ public static async Task DeleteMessage(ITelegramBotClient botClient, long chatId /// /// Редактирование фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Поток. - /// Насройки сообщения. + /// Название файла. + /// Настройки сообщения. /// Сообщение. - public static async Task EditPhoto(ITelegramBotClient botClient, long chatId, int messageId, Stream stream, string filename = "file", OptionMessage option = null) + public static async Task EditPhoto(IBotContext context, long chatId, int messageId, Stream stream, string filename = "file", OptionMessage option = null) { option = CreateOptionsIfNull(option); var replyMarkup = GetReplyMarkup(option) as InlineKeyboardMarkup; - return await botClient.EditMessageMedia( - chatId: chatId, - media: new InputMediaPhoto(InputFile.FromStream(stream, filename)), - messageId: messageId, - replyMarkup: replyMarkup, - cancellationToken: option.CancellationToken); + return await context.BotClient.EditMessageMedia( + chatId: chatId, + media: new InputMediaPhoto(InputFile.FromStream(stream, filename)), + messageId: messageId, + replyMarkup: replyMarkup, + cancellationToken: option.CancellationToken); } /// /// Редактировать inline меню вместе с фото. /// - /// Клиент телеграм бота. + /// Контекст бота. /// Идентификатор чата. /// Идентификатор сообщения. /// Текст. /// Медиа. /// Параметры сообщения. /// Сообщение. - public static async Task EditWithPhoto(ITelegramBotClient botClient, long chatId, int messageId, string text, InputMedia media, OptionMessage option) + public static async Task EditWithPhoto(IBotContext context, long chatId, int messageId, string text, InputMedia media, OptionMessage option = null) { option = CreateOptionsIfNull(option); Telegram.Bot.Types.Message message = null; - if (option?.MenuInlineKeyboardMarkup != null) + if (option?.MenuInlineKeyboardMarkup is not null) { - await botClient.EditMessageMedia( - chatId: chatId, - messageId: messageId, - media: media, - replyMarkup: option.MenuInlineKeyboardMarkup, - cancellationToken: option.CancellationToken); - - message = await botClient.EditMessageCaption( - chatId: chatId, - messageId: messageId, - caption: text, - parseMode: option.ParseMode, - replyMarkup: option.MenuInlineKeyboardMarkup, - cancellationToken: option.CancellationToken); + await context.BotClient.EditMessageMedia( + chatId: chatId, + messageId: messageId, + media: media, + replyMarkup: option.MenuInlineKeyboardMarkup, + cancellationToken: option.CancellationToken); + + message = await context.BotClient.EditMessageCaption( + chatId: chatId, + messageId: messageId, + caption: text, + parseMode: option.ParseMode, + replyMarkup: option.MenuInlineKeyboardMarkup, + cancellationToken: option.CancellationToken); } return message; @@ -574,7 +575,7 @@ public static async Task NotifyFromCallBack( /// Экземпляр класса OptionMessage. private static OptionMessage CreateOptionsIfNull(OptionMessage option = null) { - if (option == null) + if (option is null) option = new OptionMessage(); return option; } @@ -584,16 +585,16 @@ private static OptionMessage CreateOptionsIfNull(OptionMessage option = null) /// /// Параметры сообщения. /// Готовое меню или null. - private static ReplyMarkup? GetReplyMarkup(OptionMessage option) + private static ReplyMarkup? GetReplyMarkup(OptionMessage option = null) { option = CreateOptionsIfNull(option); ReplyMarkup replyMarkup = null; if (option.ClearMenu) replyMarkup = new ReplyKeyboardRemove(); - else if (option.MenuReplyKeyboardMarkup != null) + else if (option.MenuReplyKeyboardMarkup is not null) replyMarkup = option.MenuReplyKeyboardMarkup; - else if (option.MenuInlineKeyboardMarkup != null) + else if (option.MenuInlineKeyboardMarkup is not null) replyMarkup = option.MenuInlineKeyboardMarkup; return replyMarkup; @@ -602,7 +603,7 @@ private static OptionMessage CreateOptionsIfNull(OptionMessage option = null) private static ReplyParameters CreateReplyParametersFromOptions(OptionMessage option) { ReplyParameters parameters = new ReplyParameters(); - if(option.ReplyToMessageId != null) + if(option.ReplyToMessageId is not null) parameters.MessageId = option.ReplyToMessageId.Value; parameters.AllowSendingWithoutReply = option.AllowSendingWithoutReply; diff --git a/PRTelegramBot/Interfaces/CommandHandlers/ICommandHandlerBase.cs b/PRTelegramBot/Interfaces/CommandHandlers/ICommandHandlerBase.cs index bc2658c..d25da2b 100644 --- a/PRTelegramBot/Interfaces/CommandHandlers/ICommandHandlerBase.cs +++ b/PRTelegramBot/Interfaces/CommandHandlers/ICommandHandlerBase.cs @@ -1,6 +1,4 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Models.Enums; -using Telegram.Bot.Types; +using PRTelegramBot.Models.Enums; namespace PRTelegramBot.Interfaces { @@ -13,10 +11,9 @@ public interface ICommandHandlerBase /// /// Обработка. /// - /// Бот. - /// Update. + /// Контекст бота. /// Конкретный класс update. /// Результат обновления. - public Task Handle(PRBotBase bot, Update update, T updateType); + public Task Handle(IBotContext context, T updateType); } } diff --git a/PRTelegramBot/Interfaces/Configs/IBotConfigProvider.cs b/PRTelegramBot/Interfaces/Configs/IBotConfigProvider.cs index 51c0123..5caba32 100644 --- a/PRTelegramBot/Interfaces/Configs/IBotConfigProvider.cs +++ b/PRTelegramBot/Interfaces/Configs/IBotConfigProvider.cs @@ -21,7 +21,7 @@ public interface IBotConfigProvider /// /// Получить значение из параметра. /// - /// Тип возращаемого значения. + /// Тип возвращаемого значения. /// Название параметра. /// Значение параметра. public TReturn GetValue(string optionName); diff --git a/PRTelegramBot/Interfaces/IBotContext.cs b/PRTelegramBot/Interfaces/IBotContext.cs new file mode 100644 index 0000000..4ca2213 --- /dev/null +++ b/PRTelegramBot/Interfaces/IBotContext.cs @@ -0,0 +1,43 @@ +using PRTelegramBot.Core; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace PRTelegramBot.Interfaces +{ + /// + /// Интерфейс контекста бота. + /// + public interface IBotContext + { + /// + /// Все экземпляры ботов. + /// + public IEnumerable Bots { get; } + + /// + /// Экземпляр бота. + /// + public PRBotBase Current { get; } + + /// + /// Клиент Telegram.Bot. + /// + public ITelegramBotClient BotClient { get; } + + /// + /// Обновление. + /// + public Update Update { get; } + + /// + /// Текущий тип обновления. + /// + public UpdateType CurrentUpdateType { get; } + + /// + /// Токен отмены. + /// + public CancellationToken CancellationToken { get; } + } +} diff --git a/PRTelegramBot/Interfaces/IExecuteStep.cs b/PRTelegramBot/Interfaces/IExecuteStep.cs index 67c1213..518ab38 100644 --- a/PRTelegramBot/Interfaces/IExecuteStep.cs +++ b/PRTelegramBot/Interfaces/IExecuteStep.cs @@ -1,6 +1,4 @@ using PRTelegramBot.Models.Enums; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Interfaces { @@ -23,15 +21,14 @@ public interface IExecuteStep /// Получить ссылку на метод, который нужно выполнить. /// /// Метод для выполнения. - Func GetExecuteMethod(); + Func GetExecuteMethod(); /// /// Выполнить команду. /// - /// Бот клиент. - /// Обновления telegram. + /// Контекст бота. /// Результат выполнения команды. - Task ExecuteStep(ITelegramBotClient botClient, Update update); + Task ExecuteStep(IBotContext context); /// /// Может ли быть выполнен шаг diff --git a/PRTelegramBot/Interfaces/IInternalCheck.cs b/PRTelegramBot/Interfaces/IInternalCheck.cs index 71cd046..c8e27ac 100644 --- a/PRTelegramBot/Interfaces/IInternalCheck.cs +++ b/PRTelegramBot/Interfaces/IInternalCheck.cs @@ -1,7 +1,5 @@ -using PRTelegramBot.Core; -using PRTelegramBot.Models; +using PRTelegramBot.Models; using PRTelegramBot.Models.Enums; -using Telegram.Bot.Types; namespace PRTelegramBot.Interfaces { @@ -13,11 +11,10 @@ public interface IInternalCheck /// /// Выполнить проверку перед выполнение команды. /// - /// Бот. - /// Update. + /// Контекст бота. /// Команда обработчик. /// Результат выполнения. /// - Task Check(PRBotBase bot, Update update, CommandHandler handler); + Task Check(IBotContext context, CommandHandler handler); } } diff --git a/PRTelegramBot/Interfaces/IRegisterCommands.cs b/PRTelegramBot/Interfaces/IRegisterCommands.cs index cec14ab..d2e13f0 100644 --- a/PRTelegramBot/Interfaces/IRegisterCommands.cs +++ b/PRTelegramBot/Interfaces/IRegisterCommands.cs @@ -1,6 +1,4 @@ using PRTelegramBot.Core; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Interfaces { @@ -15,7 +13,7 @@ public interface IRegisterCommand /// Команда /// Метод /// True - метод зарегистрирован, false - ошибка/не зарегистрирован - public bool AddSlashCommand(string command, Func method); + public bool AddSlashCommand(string command, Func method); /// /// Регистрация Reply command @@ -23,7 +21,7 @@ public interface IRegisterCommand /// Команда /// Метод /// True - метод зарегистрирован, false - ошибка/не зарегистрирован - public bool AddReplyCommand(string command, Func method); + public bool AddReplyCommand(string command, Func method); /// /// Регистрация inline command @@ -31,7 +29,7 @@ public interface IRegisterCommand /// Команда /// Метод /// True - метод зарегистрирован, false - ошибка/не зарегистрирован - public bool AddInlineCommand(Enum command, Func method); + public bool AddInlineCommand(Enum command, Func method); /// /// Удаление Reply команды diff --git a/PRTelegramBot/Models/BotContext.cs b/PRTelegramBot/Models/BotContext.cs index 6006b0d..1d78b54 100644 --- a/PRTelegramBot/Models/BotContext.cs +++ b/PRTelegramBot/Models/BotContext.cs @@ -1,19 +1,86 @@ -using Telegram.Bot; +using PRTelegramBot.Core; +using PRTelegramBot.Interfaces; +using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; namespace PRTelegramBot.Models { - public class BotContext + /// + /// Контекст бота. + /// + public class BotContext : IBotContext { - public ITelegramBotClient BotClient { get; protected set; } - public Update Update { get; protected set; } - public CancellationToken CancellationToken { get; protected set; } + #region IIBotContext - public BotContext(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + /// + public IEnumerable Bots => BotCollection.Instance.GetBots(); + + /// + public PRBotBase Current { get; } + + /// + public ITelegramBotClient BotClient => Current.BotClient; + + /// + public Update Update { get; } + + /// + public UpdateType CurrentUpdateType => Update.Type; + + /// + public CancellationToken CancellationToken { get; } + + #endregion + + #region Методы + + /// + /// Создать заглушку контекста. + /// + /// Заглушка. + public static IBotContext CreateEmpty() { - BotClient = botClient; + return new BotContext(new PRBotDummy()); + } + + #endregion + + #region Конструкторы + + /// + /// Конструктор. + /// + /// Экземпляр бота. + /// Обновление telegram. + /// Токен отмены. + public BotContext(PRBotBase bot, Update update, CancellationToken cancellationToken) + { + Current = bot; Update = update; CancellationToken = cancellationToken; } + + /// + /// Конструктор. + /// + /// Экземпляр бота. + public BotContext(PRBotBase bot) : this(bot, new Update(), CancellationToken.None) {} + + /// + /// Конструктор. + /// + /// Экземпляр бота. + /// Обновление telegram. + public BotContext(PRBotBase bot, Update update) : this(bot, update, CancellationToken.None) { } + + /// + /// Конструктор. + /// + /// Экземпляр бота. + /// Токен отмены. + public BotContext(PRBotBase bot, CancellationToken cancellationToken) : this(bot, new Update(), cancellationToken) { } + + #endregion } } diff --git a/PRTelegramBot/Models/CommandHandler.cs b/PRTelegramBot/Models/CommandHandler.cs index 8bc5dbd..be60466 100644 --- a/PRTelegramBot/Models/CommandHandler.cs +++ b/PRTelegramBot/Models/CommandHandler.cs @@ -1,9 +1,8 @@ using Microsoft.Extensions.DependencyInjection; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; using PRTelegramBot.Utils; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Models { @@ -19,7 +18,6 @@ public class CommandHandler /// public CommandComparison CommandComparison { get;} - /// /// Сервис провайдер. /// @@ -37,35 +35,34 @@ public class CommandHandler /// /// Выполнить команду. /// - /// Бот клиент. - /// Update. - public async Task ExecuteCommand(ITelegramBotClient botClient, Update update) + /// Контекст бота. + public async Task ExecuteCommand(IBotContext context) { - if (Method == null) + if (Method is null) return; if (Method.IsStatic) { - Delegate serverMessageHandler = Delegate.CreateDelegate(typeof(Func), Method, false); - await ((Func)serverMessageHandler).Invoke(botClient, update); + Delegate serverMessageHandler = Delegate.CreateDelegate(typeof(Func), Method, false); + await ((Func)serverMessageHandler).Invoke(context); } else { - if (serviceProvider != null) + if (serviceProvider is not null) { var factory = serviceProvider.GetRequiredService(); using (var scope = factory.CreateScope()) { var instance = scope.ServiceProvider.GetRequiredService(Method.DeclaringType); - var instanceMethod = Delegate.CreateDelegate(typeof(Func), instance, Method); - await (((Func)instanceMethod)).Invoke(botClient, update); + var instanceMethod = Delegate.CreateDelegate(typeof(Func), instance, Method); + await (((Func)instanceMethod)).Invoke(context); } } else { var instance = ReflectionUtils.CreateInstanceWithNullArguments(Method.DeclaringType); - var instanceMethod = Delegate.CreateDelegate(typeof(Func), instance, Method); - await (((Func)instanceMethod)).Invoke(botClient, update); + var instanceMethod = Delegate.CreateDelegate(typeof(Func), instance, Method); + await (((Func)instanceMethod)).Invoke(context); } } } @@ -101,7 +98,7 @@ public CommandHandler(MethodInfo method, IServiceProvider ServiceProvider) /// Конструктор. /// /// Команда. - public CommandHandler(Func command) + public CommandHandler(Func command) : this (command, null, CommandComparison.Equals) { } /// @@ -109,7 +106,7 @@ public CommandHandler(Func command) /// /// Команда. /// Сервис провайдер. - public CommandHandler(Func command, IServiceProvider ServiceProvider) + public CommandHandler(Func command, IServiceProvider ServiceProvider) : this(command, ServiceProvider, CommandComparison.Equals) { } /// @@ -117,7 +114,7 @@ public CommandHandler(Func command, IServicePr /// /// Команда. /// Сравнение команд. - public CommandHandler(Func command, CommandComparison commandComparison) + public CommandHandler(Func command, CommandComparison commandComparison) : this(command, null, commandComparison) { } /// @@ -126,7 +123,7 @@ public CommandHandler(Func command, CommandCom /// Команда. /// Сервис провайдер. /// Сравнение команд. - public CommandHandler(Func command, IServiceProvider ServiceProvider, CommandComparison commandComparison) + public CommandHandler(Func command, IServiceProvider ServiceProvider, CommandComparison commandComparison) : this(command.Method, ServiceProvider, commandComparison) { } /// diff --git a/PRTelegramBot/Models/Enums/DataRetrievalMethod.cs b/PRTelegramBot/Models/Enums/DataRetrievalMethod.cs index f441027..d11ec45 100644 --- a/PRTelegramBot/Models/Enums/DataRetrievalMethod.cs +++ b/PRTelegramBot/Models/Enums/DataRetrievalMethod.cs @@ -16,6 +16,10 @@ public enum DataRetrievalMethod /// /// Обработка данных webhook. /// - WebHook + WebHook, + /// + /// Заглушка. + /// + Dummy, } } diff --git a/PRTelegramBot/Models/EventsArgs/BotEventArgs.cs b/PRTelegramBot/Models/EventsArgs/BotEventArgs.cs index ad22dce..604756b 100644 --- a/PRTelegramBot/Models/EventsArgs/BotEventArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/BotEventArgs.cs @@ -1,6 +1,4 @@ -using PRTelegramBot.Core; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { @@ -12,19 +10,23 @@ public class BotEventArgs : EventArgs #region Поля и свойства /// - /// Бот. + /// Контекст бота. /// - public PRBotBase Bot { get; private set; } + public IBotContext Context { get; private set; } - /// - /// Клиент бота. - /// - public ITelegramBotClient BotClient { get; private set; } + #endregion + + #region Методы /// - /// Обновление. + /// Создать аргументы событий для бота. /// - public Update Update { get; private set; } + /// Контекст бота. + /// Базовые аргументы события для ботов + public static BotEventArgs CreateEventArgs(IBotContext context) + { + return new BotEventArgs(context); + } #endregion @@ -33,13 +35,10 @@ public class BotEventArgs : EventArgs /// /// Конструктор. /// - /// Бот. - /// Обновление. - public BotEventArgs(PRBotBase bot, Update update) + /// Контекст бота. + public BotEventArgs(IBotContext context) { - Bot = bot; - BotClient = bot.botClient; - Update = update; + Context = context; } #endregion diff --git a/PRTelegramBot/Models/EventsArgs/CommandEventsArgs.cs b/PRTelegramBot/Models/EventsArgs/CommandEventsArgs.cs index 501e64d..683c6a5 100644 --- a/PRTelegramBot/Models/EventsArgs/CommandEventsArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/CommandEventsArgs.cs @@ -1,29 +1,34 @@ -using PRTelegramBot.Core; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { /// - /// + /// Событие с сылкой на команду. /// public class CommandEventsArgs : BotEventArgs { + #region Поля и свойства + /// - /// + /// Метод для выполнения. /// - public Func ExecuteMethod { get; private set; } + public Func ExecuteMethod { get; private set; } + + #endregion + + #region Конструкторы /// /// Конструктор. /// - /// Бот. - /// Обновление. + /// Контекст бота. /// - public CommandEventsArgs(PRBotBase bot, Update update, Func executeMethod) - : base(bot, update) + public CommandEventsArgs(IBotContext context, Func executeMethod) + : base(context) { this.ExecuteMethod = executeMethod; } + + #endregion } } diff --git a/PRTelegramBot/Models/EventsArgs/CommonLogEventArgs.cs b/PRTelegramBot/Models/EventsArgs/CommonLogEventArgs.cs index e87e088..81aaa7d 100644 --- a/PRTelegramBot/Models/EventsArgs/CommonLogEventArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/CommonLogEventArgs.cs @@ -1,4 +1,4 @@ -using PRTelegramBot.Core; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { @@ -31,9 +31,8 @@ public class CommonLogEventArgs : BotEventArgs /// /// Конструктор. /// - /// Бот. - /// Событие. - public CommonLogEventArgs(PRBotBase bot, CommonLogEventArgsCreator e) : base(bot, e.Update) + /// Контекст. + public CommonLogEventArgs(IBotContext context, CommonLogEventArgsCreator e) : base(context) { this.Message = e.Message; this.Type = e.Type; diff --git a/PRTelegramBot/Models/EventsArgs/CommonLogEventArgsCreator.cs b/PRTelegramBot/Models/EventsArgs/CommonLogEventArgsCreator.cs index 0d6e094..f120de2 100644 --- a/PRTelegramBot/Models/EventsArgs/CommonLogEventArgsCreator.cs +++ b/PRTelegramBot/Models/EventsArgs/CommonLogEventArgsCreator.cs @@ -1,4 +1,4 @@ -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { @@ -25,9 +25,9 @@ public class CommonLogEventArgsCreator : EventArgs public ConsoleColor Color { get; private set; } /// - /// Обновление. + /// Context. /// - public Update Update { get; private set; } + public IBotContext Context { get; private set; } #endregion @@ -39,16 +39,16 @@ public class CommonLogEventArgsCreator : EventArgs /// Сообщение. /// Тип. public CommonLogEventArgsCreator(string message, string type) - : this(message, type, ConsoleColor.White, new Update()) { } + : this(message, type, ConsoleColor.White, BotContext.CreateEmpty()) { } /// /// Конструктор. /// /// Сообщение. /// Тип. - /// Обновление. - public CommonLogEventArgsCreator(string message, string type, Update update) - : this(message, type, ConsoleColor.White, update) { } + /// Контекст бота. + public CommonLogEventArgsCreator(string message, string type, IBotContext context) + : this(message, type, ConsoleColor.White, context) { } /// /// Конструктор. @@ -57,7 +57,7 @@ public CommonLogEventArgsCreator(string message, string type, Update update) /// Тип. /// Цвет. public CommonLogEventArgsCreator(string message, string type, ConsoleColor color) - : this(message, type, color, new Update()) { } + : this(message, type, color, BotContext.CreateEmpty()) { } /// /// Конструктор. @@ -65,13 +65,13 @@ public CommonLogEventArgsCreator(string message, string type, ConsoleColor color /// Сообщение. /// Тип. /// Цвет. - /// Обновление. - public CommonLogEventArgsCreator(string message, string type, ConsoleColor color, Update update) + /// Контекст бота. + public CommonLogEventArgsCreator(string message, string type, ConsoleColor color, IBotContext context) { this.Message = message; this.Type = type; this.Color = color; - this.Update = update; + this.Context = context; } #endregion diff --git a/PRTelegramBot/Models/EventsArgs/ErrorLogEventArgs.cs b/PRTelegramBot/Models/EventsArgs/ErrorLogEventArgs.cs index 8c370ec..f1d2735 100644 --- a/PRTelegramBot/Models/EventsArgs/ErrorLogEventArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/ErrorLogEventArgs.cs @@ -1,4 +1,5 @@ using PRTelegramBot.Core; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { @@ -16,17 +17,44 @@ public class ErrorLogEventArgs : BotEventArgs #endregion + #region Методы + + /// + /// Создать аргументы событий с ошибкой. + /// + /// Экземпляр бота. + /// Исключение. + /// + public static ErrorLogEventArgs Create(PRBotBase bot, Exception exception) + { + return new ErrorLogEventArgs(new BotContext(bot), exception); + } + + /// + /// Создать аргументы событий с ошибкой. + /// + /// Экземпляр бота. + /// Исключение. + /// Токен отмены. + /// + public static ErrorLogEventArgs Create(PRBotBase bot, Exception exception, CancellationToken cancellationToken) + { + return new ErrorLogEventArgs(new BotContext(bot, cancellationToken), exception); + } + + #endregion + #region Конструкторы /// /// Конструктор. /// - /// Бот. - /// Аргументы события. - public ErrorLogEventArgs(PRBotBase bot, ErrorLogEventArgsCreator e) - : base(bot, e.Update) + /// Контекст бота. + /// Исключение. + public ErrorLogEventArgs(IBotContext context, Exception exception) + : base(context) { - this.Exception = e.Exception; + this.Exception = exception; } #endregion diff --git a/PRTelegramBot/Models/EventsArgs/PrivilegeEventArgs.cs b/PRTelegramBot/Models/EventsArgs/PrivilegeEventArgs.cs index 0f31345..3f53616 100644 --- a/PRTelegramBot/Models/EventsArgs/PrivilegeEventArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/PrivilegeEventArgs.cs @@ -1,11 +1,9 @@ -using PRTelegramBot.Core; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { /// - /// Аргументы при проверки привелегий. + /// Аргументы при проверки привилегий. /// public class PrivilegeEventArgs : CommandEventsArgs { @@ -23,12 +21,11 @@ public class PrivilegeEventArgs : CommandEventsArgs /// /// Конструктор. /// - /// Бот. - /// Обновление. + /// Контекст бота. /// Метод для выполнения. /// Маска доступа. - public PrivilegeEventArgs(PRBotBase bot, Update update, Func executeMethod, int? mask) - : base(bot, update, executeMethod) + public PrivilegeEventArgs(IBotContext context, Func executeMethod, int? mask) + : base(context, executeMethod) { Mask = mask; } diff --git a/PRTelegramBot/Models/EventsArgs/StartEventArgs.cs b/PRTelegramBot/Models/EventsArgs/StartEventArgs.cs index 35ec1ee..637a66b 100644 --- a/PRTelegramBot/Models/EventsArgs/StartEventArgs.cs +++ b/PRTelegramBot/Models/EventsArgs/StartEventArgs.cs @@ -1,5 +1,4 @@ -using PRTelegramBot.Core; -using Telegram.Bot.Types; +using PRTelegramBot.Interfaces; namespace PRTelegramBot.Models.EventsArgs { @@ -22,11 +21,10 @@ public class StartEventArgs : BotEventArgs /// /// Конструктор. /// - /// Бот. - /// Обновление. + /// Контекст. /// Данные. - public StartEventArgs(PRBotBase bot, Update update, string data) - : base(bot, update) + public StartEventArgs(IBotContext context, string data) + : base(context) { Data = data; } diff --git a/PRTelegramBot/Models/InlineButtons/InlineBase.cs b/PRTelegramBot/Models/InlineButtons/InlineBase.cs index 16f874e..3fca95d 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineBase.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineBase.cs @@ -17,6 +17,10 @@ public abstract class InlineBase #region Методы + /// + /// Получить текст кнопки. + /// + /// Текст кнопки. public virtual string GetTextButton() { return ButtonName; diff --git a/PRTelegramBot/Models/InlineButtons/InlineCallback.cs b/PRTelegramBot/Models/InlineButtons/InlineCallback.cs index 5f6e0a9..678b7f1 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineCallback.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineCallback.cs @@ -1,12 +1,12 @@ -using System.Text; -using PRTelegramBot.Converters; +using PRTelegramBot.Converters; using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models.CallbackCommands; +using PRTelegramBot.Models.EventsArgs; +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using Telegram.Bot; -using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; namespace PRTelegramBot.Models.InlineButtons @@ -40,19 +40,29 @@ public class InlineCallback : InlineCallback where T : TCommandBase { return JsonSerializer.Deserialize>(data); } - catch (Exception ex) + catch { return null; } } + /// + /// Преобразовать данные в команду. + /// + /// Контекст бота. + /// InlineCallback или null. + public new static InlineCallback GetCommandByCallbackOrNull(IBotContext context) + { + return GetCommandByCallbackOrNull(context?.Update?.CallbackQuery?.Data ?? string.Empty); + } + /// /// Преобразовать данные в команду. /// /// InlineCallback или null. - public InlineCallback GetCommandByCallbackOrNull() + public new InlineCallback GetCommandByCallbackOrNull() { - return GetCommandByCallbackOrNull(Update.CallbackQuery.Data); + return GetCommandByCallbackOrNull(Context?.Update?.CallbackQuery?.Data ?? string.Empty); } public override object GetContent() @@ -93,10 +103,9 @@ public InlineCallback(string buttonName, Enum commandType) : base(buttonName, co /// /// Конструктор. /// - /// Bot client. - /// Update. - public InlineCallback(ITelegramBotClient botClient, Update update) - : base(botClient,update) {} + /// Контекст бота. + public InlineCallback(IBotContext context) : base(context) + { } /// /// Конструктор. @@ -139,7 +148,7 @@ public class InlineCallback : InlineBase, IInlineContent, IDisposable /// Update. /// [JsonIgnore] - public Update Update { get; private set; } + public IBotContext Context { get; private set; } /// /// Update. @@ -162,19 +171,29 @@ public static InlineCallback GetCommandByCallbackOrNull(string data) { return JsonSerializer.Deserialize(data); } - catch (Exception ex) + catch { return null; } } + /// + /// Преобразовать данные в команду. + /// + /// Контекст бота. + /// InlineCallback или null. + public static InlineCallback GetCommandByCallbackOrNull(IBotContext context) + { + return GetCommandByCallbackOrNull(context?.Update?.CallbackQuery?.Data ?? string.Empty); + } + /// /// Преобразовать данные в команду. /// /// InlineCallback или null. public InlineCallback GetCommandByCallbackOrNull() { - return GetCommandByCallbackOrNull(Update.CallbackQuery.Data); + return GetCommandByCallbackOrNull(Context?.Update?.CallbackQuery?.Data ?? string.Empty); } /// @@ -195,19 +214,19 @@ protected void ThrowExceptionIfBytesMore128(string result) /// public async Task ExecuteActionWithLastMessage() { - if (Update?.CallbackQuery == null || BotClient == null || Data == null) + if (Context is null || Data is null || Context.Update?.CallbackQuery is null ) return; try { - var lastMessage = Update.CallbackQuery.Message; + var lastMessage = Context.Update.CallbackQuery.Message; var actionWithLastMessage = Data.GetActionWithLastMessage(); if (actionWithLastMessage == Enums.ActionWithLastMessage.Delete) - await BotClient.DeleteMessage(Update.GetChatIdClass(), lastMessage.MessageId); + await BotClient.DeleteMessage(Context.Update.GetChatIdClass(), lastMessage.MessageId); } catch (Exception ex) { - BotClient.GetBotDataOrNull().Events.OnErrorLogInvoke(ex); + Context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(Context, ex)); } } @@ -217,7 +236,7 @@ public async Task ExecuteActionWithLastMessage() public void TryUpdateData() { var command = GetCommandByCallbackOrNull(); - if(command != null) + if(command is not null) { Data = command.Data; } @@ -227,6 +246,7 @@ public void TryUpdateData() #region IInlineContent + /// public virtual object GetContent() { var result = JsonSerializer.Serialize(this); @@ -234,6 +254,7 @@ public virtual object GetContent() return result; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithCallbackData(ButtonName, GetContent() as string); @@ -243,6 +264,7 @@ public override InlineKeyboardButton GetInlineButton() #region IDisposable + /// public void Dispose() { _ = ExecuteActionWithLastMessage(); @@ -280,12 +302,10 @@ public InlineCallback(string buttonName, Enum commandType) /// /// Конструктор. /// - /// Bot client. - /// Update. - public InlineCallback(ITelegramBotClient botClient, Update update) + /// Контекст бота. + public InlineCallback(IBotContext context) { - Update = update; - BotClient = botClient; + Context = context; TryUpdateData(); } diff --git a/PRTelegramBot/Models/InlineButtons/InlineCallbackGame.cs b/PRTelegramBot/Models/InlineButtons/InlineCallbackGame.cs index c0610fc..ebe7129 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineCallbackGame.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineCallbackGame.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Interfaces; using Telegram.Bot.Types.ReplyMarkups; -using Telegram.Bot.Types; namespace PRTelegramBot.Models.InlineButtons { @@ -11,11 +10,13 @@ public class InlineCallbackGame : InlineBase, IInlineContent { #region IInlineContent + /// public object GetContent() { - return ""; + return string.Empty; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithCallbackGame(ButtonName); diff --git a/PRTelegramBot/Models/InlineButtons/InlineCallbackWithConfirmation.cs b/PRTelegramBot/Models/InlineButtons/InlineCallbackWithConfirmation.cs index 950072a..ac5b5bc 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineCallbackWithConfirmation.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineCallbackWithConfirmation.cs @@ -53,7 +53,8 @@ public class InlineCallbackWithConfirmation : InlineCallback + public override object GetContent() { return base.GetContent(); } @@ -62,6 +63,7 @@ public object GetContent() #region Базовый класс + /// public override InlineKeyboardButton GetInlineButton() { return base.GetInlineButton(); @@ -69,7 +71,6 @@ public override InlineKeyboardButton GetInlineButton() #endregion - #region Конструкторы /// @@ -97,7 +98,7 @@ public InlineCallbackWithConfirmation(InlineCallback inlineCallBack, ActionWithL : base(inlineCallBack.ButtonName, callbackWithConfirmation) { string guidString = Guid.NewGuid().ToString(); - var id = guidString.Replace("-", "").Remove(0, guidString.Length / 2); + var id = guidString.Replace("-", string.Empty).Remove(0, guidString.Length / 2); YesCallback = inlineCallBack; Data = new EntityTCommand(id, actionWithLastMessage); DataCollection.Add(id, this); diff --git a/PRTelegramBot/Models/InlineButtons/InlineLoginUrl.cs b/PRTelegramBot/Models/InlineButtons/InlineLoginUrl.cs index c480444..898f4b5 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineLoginUrl.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineLoginUrl.cs @@ -17,11 +17,13 @@ public class InlineLoginUrl : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { return LoginUrl; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithLoginUrl(ButtonName, LoginUrl); diff --git a/PRTelegramBot/Models/InlineButtons/InlinePay.cs b/PRTelegramBot/Models/InlineButtons/InlinePay.cs index dad9695..ed8b79c 100644 --- a/PRTelegramBot/Models/InlineButtons/InlinePay.cs +++ b/PRTelegramBot/Models/InlineButtons/InlinePay.cs @@ -11,11 +11,13 @@ public class InlinePay : InlineBase, IInlineContent { #region IInlineContent + /// public object GetContent() { - return ""; + return string.Empty; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithPay(ButtonName); diff --git a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQuery.cs b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQuery.cs index c5d5263..c7f8edc 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQuery.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQuery.cs @@ -1,11 +1,10 @@ using PRTelegramBot.Interfaces; using Telegram.Bot.Types.ReplyMarkups; -using Telegram.Bot.Types; namespace PRTelegramBot.Models.InlineButtons { /// - /// Создает кнопку встроенной клавиатуры. При нажатии на кнопку пользователю будет предложено выбрать один из своих чатов, открыть этот чат и вставить имя пользователя бота и указанной инлайн-запрос в поле ввода. Может быть пустым, в этом случае будет вставлено только имя пользователя бота. Не поддерживается для сообщений, отправленных от имени аккаунта Telegram Business. + /// Создает кнопку встроенной клавиатуры. При нажатии на кнопку пользователю будет предложено выбрать один из своих чатов, открыть этот чат и вставить имя пользователя бота и указанной inline-запрос в поле ввода. Может быть пустым, в этом случае будет вставлено только имя пользователя бота. Не поддерживается для сообщений, отправленных от имени аккаунта Telegram Business. /// public class InlineSwitchInlineQuery : InlineBase, IInlineContent { @@ -20,11 +19,13 @@ public class InlineSwitchInlineQuery : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { return SwitchInlineQuery; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithSwitchInlineQuery(ButtonName, SwitchInlineQuery); diff --git a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryChosenChat.cs b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryChosenChat.cs index e9a4961..27d6e3b 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryChosenChat.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryChosenChat.cs @@ -20,11 +20,13 @@ public class InlineSwitchInlineQueryChosenChat : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { return SwitchInlineQueryChosenChat; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithSwitchInlineQueryChosenChat(ButtonName, SwitchInlineQueryChosenChat); diff --git a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryCurrentChat.cs b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryCurrentChat.cs index 3fd88f4..da10eff 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryCurrentChat.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineSwitchInlineQueryCurrentChat.cs @@ -1,5 +1,4 @@ using PRTelegramBot.Interfaces; -using System; using Telegram.Bot.Types.ReplyMarkups; namespace PRTelegramBot.Models.InlineButtons @@ -20,11 +19,13 @@ public class InlineSwitchInlineQueryCurrentChat : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { return SwitchInlineQueryCurrentChat; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithSwitchInlineQueryCurrentChat(ButtonName, SwitchInlineQueryCurrentChat); diff --git a/PRTelegramBot/Models/InlineButtons/InlineURL.cs b/PRTelegramBot/Models/InlineButtons/InlineURL.cs index a64fe35..e0c3b45 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineURL.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineURL.cs @@ -1,7 +1,6 @@ using PRTelegramBot.Interfaces; using PRTelegramBot.Models.InlineButtons; using Telegram.Bot.Types.ReplyMarkups; -using Telegram.Bot.Types; namespace PRTelegramBot.InlineButtons { @@ -21,11 +20,13 @@ public sealed class InlineURL : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { return URL; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithUrl(ButtonName, URL); diff --git a/PRTelegramBot/Models/InlineButtons/InlineWebApp.cs b/PRTelegramBot/Models/InlineButtons/InlineWebApp.cs index 81b843f..0fab05e 100644 --- a/PRTelegramBot/Models/InlineButtons/InlineWebApp.cs +++ b/PRTelegramBot/Models/InlineButtons/InlineWebApp.cs @@ -20,12 +20,14 @@ public sealed class InlineWebApp : InlineBase, IInlineContent #region IInlineContent + /// public object GetContent() { var webApp = new WebAppInfo(WebAppUrl); return webApp; } + /// public override InlineKeyboardButton GetInlineButton() { return InlineKeyboardButton.WithWebApp(ButtonName, GetContent() as WebAppInfo); diff --git a/PRTelegramBot/Models/StepTelegram.cs b/PRTelegramBot/Models/StepTelegram.cs index 71c0c88..2076caf 100644 --- a/PRTelegramBot/Models/StepTelegram.cs +++ b/PRTelegramBot/Models/StepTelegram.cs @@ -1,8 +1,7 @@ using PRTelegramBot.Extensions; using PRTelegramBot.Interfaces; using PRTelegramBot.Models.Enums; -using Telegram.Bot; -using Telegram.Bot.Types; +using PRTelegramBot.Models.EventsArgs; namespace PRTelegramBot.Models { @@ -13,14 +12,10 @@ public sealed class StepTelegram : IExecuteStep { #region Свойства и константы - public bool LastStepExecuted { get; set; } - - public bool IgnoreBasicCommands { get; set; } - /// /// Ссылка на метод который должен быть выполнен. /// - public Func CommandDelegate { get; set; } + public Func CommandDelegate { get; set; } /// /// До какого времени команду можно выполнить. @@ -36,34 +31,43 @@ public sealed class StepTelegram : IExecuteStep #region IExecuteStep - public async Task ExecuteStep(ITelegramBotClient botClient, Update update) + /// + public bool LastStepExecuted { get; set; } + + /// + public bool IgnoreBasicCommands { get; set; } + + /// + public async Task ExecuteStep(IBotContext context) { - if (ExpiredTime != null && DateTime.Now > ExpiredTime) + if (ExpiredTime is not null && DateTime.Now > ExpiredTime) { - update.ClearStepUserHandler(); + context.Update.ClearStepUserHandler(); return ExecuteStepResult.ExpiredTime; } try { - await CommandDelegate.Invoke(botClient, update); + await CommandDelegate.Invoke(context); return ExecuteStepResult.Success; } catch (Exception ex) { - botClient.GetBotDataOrNull()!.Events.OnErrorLogInvoke(ex); + context.Current.Events.OnErrorLogInvoke(new ErrorLogEventArgs(context, ex)); return ExecuteStepResult.Failure; } } - public Func GetExecuteMethod() + /// + public Func GetExecuteMethod() { return CommandDelegate; } + /// public bool CanExecute() { - return ExpiredTime == null || DateTime.Now < ExpiredTime; + return ExpiredTime is null || DateTime.Now < ExpiredTime; } #endregion @@ -74,7 +78,7 @@ public bool CanExecute() /// Регистрация следующего шага. /// /// Метод для следующей обработки. - public void RegisterNextStep(Func nextStep) + public void RegisterNextStep(Func nextStep) { RegisterNextStep(nextStep, null); } @@ -84,7 +88,7 @@ public void RegisterNextStep(Func nextStep) /// /// Метод для следующей обработки. /// До какого времени команду можно выполнить - public void RegisterNextStep(Func nextStep, TimeSpan addTime) + public void RegisterNextStep(Func nextStep, TimeSpan addTime) { RegisterNextStep(nextStep, DateTime.Now.Add(addTime)); } @@ -94,7 +98,7 @@ public void RegisterNextStep(Func nextStep, Ti /// /// Метод для следующей обработки. /// До какого времени команду можно выполнить. - public void RegisterNextStep(Func nextStep, DateTime? expiriedTime) + public void RegisterNextStep(Func nextStep, DateTime? expiriedTime) { RegisterNextStep(nextStep, expiriedTime, false); } @@ -105,7 +109,7 @@ public void RegisterNextStep(Func nextStep, Da /// Метод для следующей обработки. /// До какого времени команду можно выполнить. /// Игнорировать базовые команды при выполнение шагов. - public void RegisterNextStep(Func nextStep, DateTime? expiriedTime, bool ignoreBasicCommands) + public void RegisterNextStep(Func nextStep, DateTime? expiriedTime, bool ignoreBasicCommands) { CommandDelegate = nextStep; ExpiredTime = expiriedTime; @@ -130,7 +134,7 @@ public T GetCache() /// Создать новый следующий шаг. /// /// Команда для выполнения - public StepTelegram(Func command) + public StepTelegram(Func command) : this(command, null, null) { } /// @@ -138,7 +142,7 @@ public StepTelegram(Func command) /// /// Команда для выполнения. /// Кэш. - public StepTelegram(Func command, ITelegramCache cache) + public StepTelegram(Func command, ITelegramCache cache) : this(command, null, cache, false) { } /// @@ -146,7 +150,7 @@ public StepTelegram(Func command, ITelegramCac /// /// Команда для выполнения. /// Максимальный срок выполнения команды после чего команда будет проигнорирована. - public StepTelegram(Func command, DateTime expiriedTime) + public StepTelegram(Func command, DateTime expiriedTime) : this(command, expiriedTime, null, false) { } /// @@ -155,7 +159,7 @@ public StepTelegram(Func command, DateTime exp /// Команда для выполнения. /// Максимальный срок выполнения команды после чего команда будет проигнорирована. /// Кэш. - public StepTelegram(Func command, DateTime? expiriedTime, ITelegramCache cache) + public StepTelegram(Func command, DateTime? expiriedTime, ITelegramCache cache) : this(command, expiriedTime, cache, false) { } /// @@ -165,7 +169,7 @@ public StepTelegram(Func command, DateTime? ex /// Максимальный срок выполнения команды после чего команда будет проигнорирована. /// Кэш. /// Игнорировать базовые команды при выполнение шагов. - public StepTelegram(Func command, DateTime? expiriedTime, ITelegramCache cache, bool ignoreBasicCommands) + public StepTelegram(Func command, DateTime? expiriedTime, ITelegramCache cache, bool ignoreBasicCommands) { this.cache = cache; IgnoreBasicCommands = ignoreBasicCommands; diff --git a/PRTelegramBot/Models/StringCommandHandler.cs b/PRTelegramBot/Models/StringCommandHandler.cs index 74fa099..d077760 100644 --- a/PRTelegramBot/Models/StringCommandHandler.cs +++ b/PRTelegramBot/Models/StringCommandHandler.cs @@ -1,7 +1,6 @@ -using PRTelegramBot.Models.Enums; +using PRTelegramBot.Interfaces; +using PRTelegramBot.Models.Enums; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Models { @@ -48,7 +47,7 @@ public StringCommandHandler(MethodInfo method, IServiceProvider ServiceProvider) /// Конструктор. /// /// Команда. - public StringCommandHandler(Func command) + public StringCommandHandler(Func command) : this(command, null, CommandComparison.Equals, StringComparison.OrdinalIgnoreCase) { } /// @@ -56,7 +55,7 @@ public StringCommandHandler(Func command) /// /// Команда. /// Сервис провайдер. - public StringCommandHandler(Func command, IServiceProvider ServiceProvider) + public StringCommandHandler(Func command, IServiceProvider ServiceProvider) : this(command, ServiceProvider, CommandComparison.Equals, StringComparison.OrdinalIgnoreCase) { } /// @@ -64,7 +63,7 @@ public StringCommandHandler(Func command, ISer /// /// Команда. /// Сравнение команд. - public StringCommandHandler(Func command, CommandComparison commandComparison) + public StringCommandHandler(Func command, CommandComparison commandComparison) : this(command,null, commandComparison, StringComparison.OrdinalIgnoreCase) { } /// @@ -87,7 +86,7 @@ public StringCommandHandler(MethodInfo method, IServiceProvider ServiceProvider, /// Сервис провайдер. /// Сравнение команд. /// Сравнение строк. - public StringCommandHandler(Func command, IServiceProvider ServiceProvider, CommandComparison commandComparison, StringComparison stringComparison) + public StringCommandHandler(Func command, IServiceProvider ServiceProvider, CommandComparison commandComparison, StringComparison stringComparison) : base(command, ServiceProvider, commandComparison) { this.StringComparison = stringComparison; diff --git a/PRTelegramBot/Models/TCommands/CalendarTCommand.cs b/PRTelegramBot/Models/TCommands/CalendarTCommand.cs index 82bf989..ad76fd6 100644 --- a/PRTelegramBot/Models/TCommands/CalendarTCommand.cs +++ b/PRTelegramBot/Models/TCommands/CalendarTCommand.cs @@ -17,6 +17,9 @@ public class CalendarTCommand : TCommandBase [JsonConverter(typeof(DateOnlyConverter))] public DateTime Date { get; set; } + /// + /// Культура. + /// [JsonPropertyName("2")] public string Culture { get; set; } diff --git a/PRTelegramBot/PRTelegramBot.csproj b/PRTelegramBot/PRTelegramBot.csproj index 14480e3..15167d1 100644 --- a/PRTelegramBot/PRTelegramBot.csproj +++ b/PRTelegramBot/PRTelegramBot.csproj @@ -6,7 +6,7 @@ latest enable enable - 0.7.12 + 0.8 Ilya Samarin git diff --git a/PRTelegramBot/README.md b/PRTelegramBot/README.md index aa742fa..25e2985 100644 --- a/PRTelegramBot/README.md +++ b/PRTelegramBot/README.md @@ -1,4 +1,4 @@ -![Static Badge](https://img.shields.io/badge/version-v0.7.12-brightgreen) ![Static Badge](https://img.shields.io/badge/telegram.bot-22.7.2-blue) ![NuGet Downloads](https://img.shields.io/nuget/dt/prtelegrambot) ![NuGet Version](https://img.shields.io/nuget/v/prtelegrambot) +![Static Badge](https://img.shields.io/badge/version-v0.8-brightgreen) ![Static Badge](https://img.shields.io/badge/telegram.bot-22.7.2-blue) ![NuGet Downloads](https://img.shields.io/nuget/dt/prtelegrambot) ![NuGet Version](https://img.shields.io/nuget/v/prtelegrambot) > **Если данный проект был для вас полезен и хотите его поддержать, можете поставить ⭐ в репозитории проекта. diff --git a/PRTelegramBot/Registrars/CommandRegistrar.cs b/PRTelegramBot/Registrars/CommandRegistrar.cs index a90586f..979fe16 100644 --- a/PRTelegramBot/Registrars/CommandRegistrar.cs +++ b/PRTelegramBot/Registrars/CommandRegistrar.cs @@ -1,7 +1,5 @@ using PRTelegramBot.Core; using PRTelegramBot.Interfaces; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Registrars { @@ -21,7 +19,8 @@ public class RegisterCommand : IRegisterCommand #region IRegisterCommand - public bool AddSlashCommand(string command, Func method) + /// + public bool AddSlashCommand(string command, Func method) { if (bot.Handler is Handler handler) return handler.SlashCommandsStore.AddCommand(command, method); @@ -30,7 +29,8 @@ public bool AddSlashCommand(string command, Func method) + /// + public bool AddReplyCommand(string command, Func method) { if (bot.Handler is Handler handler) return handler.ReplyCommandsStore.AddCommand(command, method); @@ -38,7 +38,8 @@ public bool AddReplyCommand(string command, Func method) + /// + public bool AddInlineCommand(Enum command, Func method) { if (bot.Handler is Handler handler) return handler.CallbackQueryCommandsStore.AddCommand(command, method); @@ -46,6 +47,7 @@ public bool AddInlineCommand(Enum command, Func public bool RemoveReplyCommand(string command) { if (bot.Handler is Handler handler) @@ -54,6 +56,7 @@ public bool RemoveReplyCommand(string command) return false; } + /// public bool RemoveSlashCommand(string command) { if (bot.Handler is Handler handler) @@ -62,6 +65,7 @@ public bool RemoveSlashCommand(string command) return false; } + /// public bool RemoveInlineCommand(Enum command) { if (bot.Handler is Handler handler) @@ -70,6 +74,7 @@ public bool RemoveInlineCommand(Enum command) return false; } + /// public void Init(PRBotBase bot) { this.bot = bot; diff --git a/PRTelegramBot/Registrars/InlineClassRegistrar.cs b/PRTelegramBot/Registrars/InlineClassRegistrar.cs index 5aea332..a8c5c15 100644 --- a/PRTelegramBot/Registrars/InlineClassRegistrar.cs +++ b/PRTelegramBot/Registrars/InlineClassRegistrar.cs @@ -6,6 +6,10 @@ namespace PRTelegramBot.Registrars { internal class InlineClassRegistrar { + /// + /// Регистратор inline классов обработчиков. + /// + /// Экземпляр бота. public static void Register(PRBotBase bot) { bot.InlineClassHandlerInstances.Clear(); diff --git a/PRTelegramBot/Registrars/MethodRegistrar.cs b/PRTelegramBot/Registrars/MethodRegistrar.cs index dd309f0..88ed0af 100644 --- a/PRTelegramBot/Registrars/MethodRegistrar.cs +++ b/PRTelegramBot/Registrars/MethodRegistrar.cs @@ -2,6 +2,7 @@ using PRTelegramBot.Core.Factories; using PRTelegramBot.Interfaces; using PRTelegramBot.Models; +using PRTelegramBot.Models.EventsArgs; using PRTelegramBot.Utils; using System.Reflection; using Telegram.Bot; @@ -26,6 +27,7 @@ public sealed class MethodRegistrar /// Команды. /// Сервис провайдер. public void RegisterMethodFromClass(PRBotBase bot, Type attributetype, MethodInfo[] methods, Dictionary commands, IServiceProvider serviceProvider) + where Tkey : notnull { foreach (var method in methods) { @@ -33,14 +35,15 @@ public void RegisterMethodFromClass(PRBotBase bot, Type attributetype, Met { var attribute = method.GetCustomAttributes().FirstOrDefault(attr => attr.GetType().Name == attributetype.Name); - if (attribute == null || !((IBaseQueryAttribute)attribute).BotIds.Contains(bot.Options.BotId) && !((IBaseQueryAttribute)attribute).BotIds.Contains(-1)) + if (attribute is null || !((IBaseQueryAttribute)attribute).BotIds.Contains(bot.Options.BotId) && !((IBaseQueryAttribute)attribute).BotIds.Contains(-1)) continue; bool isValidMethod = ReflectionUtils.IsValidMethodForBaseBaseQueryAttribute(bot, method); if (!isValidMethod) { - bot.Events.OnErrorLogInvoke(new Exception($"The method {method.Name} has an invalid signature. " + - $"Required return {nameof(Task)} arg1 {nameof(ITelegramBotClient)} arg2 {nameof(Update)}")); + var exception = new InvalidOperationException($"The method {method.Name} has an invalid signature. " + + $"Required return {nameof(Task)} arg1 {nameof(ITelegramBotClient)} arg2 {nameof(Update)}"); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, exception)); continue; } @@ -50,7 +53,7 @@ public void RegisterMethodFromClass(PRBotBase bot, Type attributetype, Met } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, ex)); } } } @@ -64,6 +67,7 @@ public void RegisterMethodFromClass(PRBotBase bot, Type attributetype, Met /// Методы. /// Команды. public void RegisterStaticCommand(PRBotBase bot, Type attributetype, MethodInfo[] methods, Dictionary commands) + where Tkey : notnull { foreach (var method in methods) { @@ -73,7 +77,7 @@ public void RegisterStaticCommand(PRBotBase bot, Type attributetype, Metho continue; var attribute = method.GetCustomAttributes().FirstOrDefault(attr => attr.GetType().Name == attributetype.Name); - if (attribute == null) + if (attribute is null) continue; foreach (var command in ((ICommandStore)attribute).Commands) @@ -81,18 +85,19 @@ public void RegisterStaticCommand(PRBotBase bot, Type attributetype, Metho bool isValidMethod = ReflectionUtils.IsValidMethodForBaseBaseQueryAttribute(bot, method); if (!isValidMethod) { - bot.Events.OnErrorLogInvoke(new Exception($"The method {method.Name} has an invalid signature for the {attribute.GetType()} attribute. The method will be ignored.")); + var exception = new InvalidOperationException($"The method {method.Name} has an invalid signature for the {attribute.GetType()} attribute. The method will be ignored."); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, exception)); continue; } - Delegate serverMessageHandler = Delegate.CreateDelegate(typeof(Func), method, false); - var telegramCommand = new HandlerFactory().CreateHandler((IBaseQueryAttribute)attribute, (Func)serverMessageHandler, null); + Delegate serverMessageHandler = Delegate.CreateDelegate(typeof(Func), method, false); + var telegramCommand = new HandlerFactory().CreateHandler((IBaseQueryAttribute)attribute, (Func)serverMessageHandler, null); commands.Add(command, telegramCommand); } } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, ex)); } } } diff --git a/PRTelegramBot/Utils/AccessUtils.cs b/PRTelegramBot/Utils/AccessUtils.cs index 855e3dd..b4b5c1f 100644 --- a/PRTelegramBot/Utils/AccessUtils.cs +++ b/PRTelegramBot/Utils/AccessUtils.cs @@ -12,7 +12,7 @@ public static class AccessUtils /// /// Тип перечисления. /// Маска доступа. - /// Перечесление флагов доступа. + /// Перечисление флагов доступа. public static TEnum ReadFlags(int mask) where TEnum : Enum { diff --git a/PRTelegramBot/Utils/CalendarUtils.cs b/PRTelegramBot/Utils/CalendarUtils.cs index e447ec4..c928c3e 100644 --- a/PRTelegramBot/Utils/CalendarUtils.cs +++ b/PRTelegramBot/Utils/CalendarUtils.cs @@ -1,59 +1,54 @@ -using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models; using PRTelegramBot.Utils.Controls.CalendarControl.Common; using System.Globalization; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Utils { /// - /// Утилиты для работы с календерем + /// Утилиты для работы с календарем. /// public static class CalendarUtils { /// /// Создать новый календарь. /// - /// Бот. - /// Update. + /// Контекст бота. /// Язык календаря. /// Заголовок callback команды. /// Параметры сообщения. /// Текст сообщение. - public static async Task Create(ITelegramBotClient botClient, Update update, CultureInfo culture, Enum headerCallbackCommand, OptionMessage option, string message) + public static async Task Create(IBotContext context, CultureInfo culture, Enum headerCallbackCommand, OptionMessage option, string message) { var calendarMarkup = Markup.Calendar(DateTime.Today, culture, Convert.ToInt32(headerCallbackCommand)); option.MenuInlineKeyboardMarkup = calendarMarkup; option.MenuReplyKeyboardMarkup = null; - await Helpers.Message.Send(botClient, update.GetChatId(), message, option); + await Helpers.Message.Send(context, message, option); } /// /// Создать новый календарь. /// - /// Бот. - /// Update. + /// Контекст бота. /// Язык календаря. /// Заголовок callback команды. /// Текст сообщение. - public static async Task Create(ITelegramBotClient botClient, Update update, CultureInfo culture, Enum headerCallbackCommand, string message) + public static async Task Create(IBotContext context, CultureInfo culture, Enum headerCallbackCommand, string message) { var option = new OptionMessage(); - await Create(botClient, update, culture, headerCallbackCommand, option, message); + await Create(context, culture, headerCallbackCommand, option, message); } /// /// Создать новый календарь. /// - /// Бот. - /// Update. + /// Контекст бота. /// Заголовок callback команды. /// Текст сообщение. - public static async Task Create(ITelegramBotClient botClient, Update update, Enum headerCallbackCommand, string message) + public static async Task Create(IBotContext context, Enum headerCallbackCommand, string message) { var culture = CultureInfo.GetCultureInfo("ru-RU", false); - await Create(botClient, update, culture, headerCallbackCommand, message); + await Create(context, culture, headerCallbackCommand, message); } } } diff --git a/PRTelegramBot/Utils/Controls/CalendarControl/Common/Markup.cs b/PRTelegramBot/Utils/Controls/CalendarControl/Common/Markup.cs index 7501684..3d0af8e 100644 --- a/PRTelegramBot/Utils/Controls/CalendarControl/Common/Markup.cs +++ b/PRTelegramBot/Utils/Controls/CalendarControl/Common/Markup.cs @@ -2,7 +2,6 @@ using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using System.Globalization; -using System.Text.RegularExpressions; using Telegram.Bot.Types.ReplyMarkups; namespace PRTelegramBot.Utils.Controls.CalendarControl.Common @@ -15,7 +14,7 @@ public static class Markup #region Методы /// - /// Разметка калердаря. + /// Разметка календаря. /// /// Дата. /// Язык календаря. diff --git a/PRTelegramBot/Utils/Controls/CalendarControl/Common/Row.cs b/PRTelegramBot/Utils/Controls/CalendarControl/Common/Row.cs index 19d0bb3..8154671 100644 --- a/PRTelegramBot/Utils/Controls/CalendarControl/Common/Row.cs +++ b/PRTelegramBot/Utils/Controls/CalendarControl/Common/Row.cs @@ -2,7 +2,6 @@ using PRTelegramBot.Models.Enums; using PRTelegramBot.Models.InlineButtons; using System.Globalization; -using System.Text.RegularExpressions; using Telegram.Bot.Types.ReplyMarkups; namespace PRTelegramBot.Utils.Controls.CalendarControl.Common diff --git a/PRTelegramBot/Utils/EnumHeaders.cs b/PRTelegramBot/Utils/EnumHeaders.cs index bda50f0..19b8d1f 100644 --- a/PRTelegramBot/Utils/EnumHeaders.cs +++ b/PRTelegramBot/Utils/EnumHeaders.cs @@ -5,7 +5,7 @@ namespace PRTelegramBot.Utils public class EnumHeaders { private static readonly object _lock = new object(); - private static EnumHeaders _instance; + private static EnumHeaders instance; private HashSet _uniqueValues; private Dictionary _headers; @@ -19,17 +19,17 @@ public static EnumHeaders Instance { get { - if (_instance == null) + if (instance is null) { lock (_lock) { - if (_instance == null) + if (instance is null) { - _instance = new EnumHeaders(); + instance = new EnumHeaders(); } } } - return _instance; + return instance; } } @@ -70,7 +70,7 @@ public int Get(Enum key) lock (_lock) { var @enum = _headers.FirstOrDefault(x => x.Value.Equals(key)); - if (@enum.Value == null) + if (@enum.Value is null) throw new InlineCommandNotFoundException(key); return @enum.Key; diff --git a/PRTelegramBot/Utils/Generator.cs b/PRTelegramBot/Utils/Generator.cs index ddd68ea..a405364 100644 --- a/PRTelegramBot/Utils/Generator.cs +++ b/PRTelegramBot/Utils/Generator.cs @@ -31,12 +31,12 @@ public enum Chars } /// - /// Генериурет случайный набор символов + /// Генерирует случайный набор символов. /// - /// Указывает какого типа должны быть символы - /// Длина набора символов - /// Префикс ставится перед сгенерированным набором символов - /// Сгенерированный набор символов + /// Указывает какого типа должны быть символы. + /// Длина набора символов. + /// Префикс ставится перед сгенерированным набором символов. + /// Сгенерированный набор символов. public static string RandomSymbols(Chars chars, int length, string prefix = "") { var random = new Random(); @@ -63,13 +63,13 @@ public static string RandomSymbols(Chars chars, int length, string prefix = "") } /// - /// Генерирует купон - /// Можно использовать для разных акций или промо кодов + /// Генерирует купон. + /// Можно использовать для разных акций или промо кодов. /// - /// Длина сегмента кода - /// Количество разделителей - /// Символ разделителя, по умолчанию - - /// Сгенерированный купон + /// Длина сегмента кода. + /// Количество разделителей. + /// Символ разделителя, по умолчанию - . + /// Сгенерированный купон. public static string Coupon(int segmentLength = 6, int countSplit = 1, char symbolSplit = '-') { var random = new Random((int)DateTime.Now.Ticks); diff --git a/PRTelegramBot/Utils/GroupUtils.cs b/PRTelegramBot/Utils/GroupUtils.cs index b48c039..4934557 100644 --- a/PRTelegramBot/Utils/GroupUtils.cs +++ b/PRTelegramBot/Utils/GroupUtils.cs @@ -1,4 +1,5 @@ -using Telegram.Bot; +using PRTelegramBot.Interfaces; +using Telegram.Bot; namespace PRTelegramBot.Utils { @@ -12,13 +13,13 @@ public static class GroupUtils /// /// Проверяет находится ли пользователь в группе. /// - /// Телеграм бот клиент. + /// Контекст бота. /// Идентификатор группы. /// Идентификатор пользователя. /// True - есть иначе false. - public static async Task IsGroupMember(ITelegramBotClient botClient, long groupId, long userId) + public static async Task IsGroupMember(IBotContext context, long groupId, long userId) { - var data = await botClient.GetChatMember(groupId, userId); + var data = await context.BotClient.GetChatMember(groupId, userId); return data.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Member || data.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator || data.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator; @@ -27,26 +28,26 @@ public static async Task IsGroupMember(ITelegramBotClient botClient, long /// /// Проверяет является ли администратором группы. /// - /// Телеграм бот клиент. + /// Контекст бота. /// Идентификатор группы. /// Идентификатор пользователя. /// True - администратор иначе false. - public static async Task IsGroupAdmin(ITelegramBotClient botClient, long groupId, long userId) + public static async Task IsGroupAdmin(IBotContext context, long groupId, long userId) { - var data = await botClient.GetChatMember(groupId, userId); + var data = await context.BotClient.GetChatMember(groupId, userId); return data.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator; } /// /// Проверяет является ли создателем группы. /// - /// Телеграм бот клиент. + /// Контекст бота. /// Идентификатор группы. /// Идентификатор пользователя. /// True - создатель иначе false. - public static async Task IsGroupCreator(ITelegramBotClient botClient, long groupId, long userId) + public static async Task IsGroupCreator(IBotContext context, long groupId, long userId) { - var data = await botClient.GetChatMember(groupId, userId); + var data = await context.BotClient.GetChatMember(groupId, userId); return data.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator; } diff --git a/PRTelegramBot/Utils/InstanceFactory.cs b/PRTelegramBot/Utils/InstanceFactory.cs index fbec0af..8156fb6 100644 --- a/PRTelegramBot/Utils/InstanceFactory.cs +++ b/PRTelegramBot/Utils/InstanceFactory.cs @@ -19,7 +19,7 @@ public static object GetOrCreate(Type type, IServiceProvider serviceProvider = n { object instance = null; - if (serviceProvider != null) + if (serviceProvider is not null) { var factory = serviceProvider.GetRequiredService(); using (var scope = factory.CreateScope()) diff --git a/PRTelegramBot/Utils/MenuGenerator.cs b/PRTelegramBot/Utils/MenuGenerator.cs index 9415db8..5fee063 100644 --- a/PRTelegramBot/Utils/MenuGenerator.cs +++ b/PRTelegramBot/Utils/MenuGenerator.cs @@ -9,47 +9,47 @@ namespace PRTelegramBot.Utils { /// - /// Класс для удобной генерации меню + /// Класс для удобной генерации меню. /// public static class MenuGenerator { #region Reply кнопки и меню /// - /// Генерирует reply меню для бота + /// Генерирует reply меню для бота. /// - /// Максимальное количество столбцов - /// Коллекция меню - /// Изменяет размер по вертикали - /// Если значение не пустое добавляет пункт в самый конец меню + /// Максимальное количество столбцов. + /// Коллекция меню. + /// Изменяет размер по вертикали. + /// Если значение не пустое добавляет пункт в самый конец меню. /// Признак, того что клавиатура будет скрыта после нажатия на кнопку. /// Готовое меню public static ReplyKeyboardMarkup ReplyKeyboard(int maxColumn, List menu, bool resizeKeyboard = true, string mainMenu = "", bool OneTimeKeyboard = false) { var buttons = ReplyButtons(maxColumn, menu, mainMenu); - return ReplyKeyboard(buttons, resizeKeyboard, "", OneTimeKeyboard); + return ReplyKeyboard(buttons, resizeKeyboard, string.Empty, OneTimeKeyboard); } /// - /// Генерирует reply меню для бота + /// Генерирует reply меню для бота. /// - /// Максимальное количество столбцов - /// Коллекция кнопок - /// Изменяет размер по вертикали - /// Есть не пусто, добавляет главное меню + /// Максимальное количество столбцов. + /// Коллекция кнопок. + /// Изменяет размер по вертикали. + /// Есть не пусто, добавляет главное меню. /// Признак, того что клавиатура будет скрыта после нажатия на кнопку. /// Готовое меню public static ReplyKeyboardMarkup ReplyKeyboard(int maxColumn, List keyboardButtons, bool resizeKeyboard = true, string mainMenu = "", bool OneTimeKeyboard = false) { var buttons = ReplyButtons(maxColumn, keyboardButtons, mainMenu); - return ReplyKeyboard(buttons, resizeKeyboard, "", OneTimeKeyboard); + return ReplyKeyboard(buttons, resizeKeyboard, string.Empty, OneTimeKeyboard); } /// - /// Генерирует reply меню для бота + /// Генерирует reply меню для бота. /// /// - /// Изменяет размер по вертикали - /// Есть не пусто, добавляет главное меню + /// Изменяет размер по вертикали. + /// Есть не пусто, добавляет главное меню. /// Признак, того что клавиатура будет скрыта после нажатия на кнопку. /// Готовое меню public static ReplyKeyboardMarkup ReplyKeyboard(List> buttons, bool resizeKeyboard = true, string mainMenu = "", bool OneTimeKeyboard = false) @@ -70,12 +70,12 @@ public static ReplyKeyboardMarkup ReplyKeyboard(List> butto } /// - /// Генерирует reply кнокпи для бота + /// Генерирует reply кнопки для бота. /// - /// Максимальное количество столбцов - /// - /// Есть не пусто, добавляет главное меню - /// Коллекция кнопок + /// Максимальное количество столбцов. + /// Меню. + /// Есть не пусто, добавляет главное меню. + /// Коллекция кнопок. public static List> ReplyButtons(int maxColumn, List menu, string mainMenu = "") { List buttons = new(); @@ -87,12 +87,12 @@ public static List> ReplyButtons(int maxColumn, List - /// Генерирует reply кнокпи для бота + /// Генерирует reply кнопки для бота. /// - /// Максимальное количество столбцов - /// Кнокпки - /// Есть не пусто, добавляет главное меню - /// Коллекция кнопок + /// Максимальное количество столбцов. + /// Кнопки. + /// Есть не пусто, добавляет главное меню. + /// Коллекция кнопок. public static List> ReplyButtons(int maxColumn, List buttons, string mainMenu = "") { List> generateButtons = new(); @@ -133,11 +133,11 @@ public static List> ReplyButtons(int maxColumn, List - /// Объединяет reply кнопки для бота + /// Объединяет reply кнопки для бота. /// - /// Первая лист кнопок - /// Второй лист кнопок - /// Коллекция кнопок + /// Первая лист кнопок. + /// Второй лист кнопок. + /// Коллекция кнопок. public static List> ReplyButtons(List> buttonsOne, List> buttonsTwo) { buttonsOne.AddRange(buttonsTwo); @@ -147,10 +147,10 @@ public static List> ReplyButtons(List> #region Inline кнопки и меню /// - /// Создает Inline меню для бота + /// Создает Inline меню для бота. /// - /// Коллекция кнопок - /// Inline меню для бота + /// Коллекция кнопок. + /// Inline меню для бота. public static InlineKeyboardMarkup InlineKeyboard(List> buttons) { InlineKeyboardMarkup Keyboard = new(buttons); @@ -158,11 +158,11 @@ public static InlineKeyboardMarkup InlineKeyboard(List - /// Создает Inline меню для бота + /// Создает Inline меню для бота. /// - /// Максимальное количество столбцов - /// Коллекция кнопок - /// Inline меню для бота + /// Максимальное количество столбцов. + /// Коллекция кнопок. + /// Inline меню для бота. public static InlineKeyboardMarkup InlineKeyboard(int maxColumn, List menu) { var buttons = InlineButtons(maxColumn, menu); @@ -170,11 +170,11 @@ public static InlineKeyboardMarkup InlineKeyboard(int maxColumn, List - /// Создает коллекцию inline кнопок + /// Создает коллекцию inline кнопок. /// - /// Максимальное количество столбцов - /// Коллекция меню - /// Коллекция кнопок + /// Максимальное количество столбцов. + /// Коллекция меню. + /// Коллекция кнопок. public static List> InlineButtons(int maxColumn, List menu) { List> buttons = new(); @@ -207,11 +207,10 @@ public static List> InlineButtons(int maxColumn, List } /// - /// Создает inline кнопку + /// Создает inline кнопку. /// - /// Данные inline кнопки - /// Inline кнопка - /// + /// Данные inline кнопки. + /// Inline кнопка. public static InlineKeyboardButton GetInlineButton(IInlineContent inlineData) { return inlineData switch @@ -226,15 +225,15 @@ public static InlineKeyboardButton GetInlineButton(IInlineContent inlineData) InlineSwitchInlineQueryCurrentChat inlineSwitchInlineQueryCurrentChat => InlineKeyboardButton.WithSwitchInlineQueryCurrentChat(inlineSwitchInlineQueryCurrentChat.GetTextButton(), inlineSwitchInlineQueryCurrentChat.GetContent() as string), InlineSwitchInlineQueryChosenChat inlineSwitchInlineQueryChosenChat => InlineKeyboardButton.WithSwitchInlineQueryChosenChat(inlineSwitchInlineQueryChosenChat.GetTextButton(), inlineSwitchInlineQueryChosenChat.GetContent() as SwitchInlineQueryChosenChat), - _ => throw new NotImplementedException() + _ => throw new NotImplementedException($"{inlineData.GetType()} is not implemented yet.") }; } /// - /// Создает одно inline меню из нескольких + /// Создает одно inline меню из нескольких. /// - /// Массив меню - /// Inline меню для бота + /// Массив меню. + /// Inline меню для бота. public static InlineKeyboardMarkup UnitInlineKeyboard(params InlineKeyboardMarkup[] keyboards) { List> buttons = new(); @@ -246,15 +245,15 @@ public static InlineKeyboardMarkup UnitInlineKeyboard(params InlineKeyboardMarku } /// - /// Генерирует меню для постраничного вывода + /// Генерирует меню для постраничного вывода. /// - /// Текущая страница - /// Всего страниц - /// Маркер nextpage - /// Маркер prevpage - /// Маркер currentPage - /// Дополнительное меню с которым требуется объединить данные - /// Постраничное inline menu + /// Текущая страница. + /// Всего страниц. + /// Маркер nextpage. + /// Маркер prevpage. + /// Маркер currentPage. + /// Дополнительное меню с которым требуется объединить данные. + /// Постраничное inline menu. public static InlineKeyboardMarkup GetPageMenu( int currentPage, int pageCount, @@ -269,15 +268,15 @@ public static InlineKeyboardMarkup GetPageMenu( } /// - /// Генерирует меню для постраничного вывода + /// Генерирует меню для постраничного вывода. /// - /// Текущая страница - /// Всего страниц - /// Маркер nextpage - /// Маркер prevpage - /// Кнопка обработчик в центре - /// Дополнительное меню с которым требуется объединить данные - /// Постраничное inline menu + /// Текущая страница. + /// Всего страниц. + /// Маркер nextpage. + /// Маркер prevpage. + /// Кнопка обработчик в центре. + /// Дополнительное меню с которым требуется объединить данные. + /// Постраничное inline menu. public static InlineKeyboardMarkup GetPageMenu( int currentPage, int pageCount, @@ -292,14 +291,14 @@ public static InlineKeyboardMarkup GetPageMenu( } /// - /// Генерирует меню для постраничного вывода + /// Генерирует меню для постраничного вывода. /// - /// Текущая страница - /// Всего страниц - /// Маркер nextpage - /// Маркер prevpage - /// Маркер currentPage - /// Постраничное inline menu + /// Текущая страница. + /// Всего страниц. + /// Маркер nextpage. + /// Маркер prevpage. + /// Маркер currentPage. + /// Постраничное inline menu. public static InlineKeyboardMarkup GetPageMenu( Enum enumToInt, int currentPage, @@ -316,15 +315,15 @@ public static InlineKeyboardMarkup GetPageMenu( } /// - /// Генерирует меню для постраничного вывода + /// Генерирует меню для постраничного вывода. /// - /// Текущая страница - /// Всего страниц - /// Маркер nextpage - /// Заголовок команды - /// Маркер prevpage - /// Кнопка обработчик в центре - /// Постраничное inline menu + /// Текущая страница. + /// Всего страниц. + /// Маркер nextpage. + /// Заголовок команды. + /// Маркер prevpage. + /// Кнопка обработчик в центре. + /// Постраничное inline menu. public static InlineKeyboardMarkup GetPageMenu( int currentPage, int pageCount, @@ -337,7 +336,7 @@ public static InlineKeyboardMarkup GetPageMenu( if (currentPage != 1) buttons.Add(new InlineCallback($"({pageCount - (pageCount - currentPage + 1)}) {previousPageMarker}", PRTelegramBotCommand.PreviousPage, new PageTCommand(currentPage - 1, enumToInt))); - if (button != null) + if (button is not null) buttons.Add(button); if (currentPage != pageCount) @@ -347,15 +346,15 @@ public static InlineKeyboardMarkup GetPageMenu( } /// - /// Генерирует меню для постраничного вывода + /// Генерирует меню для постраничного вывода. /// - /// Текущая страница - /// Всего страниц - /// Маркер nextpage - /// Заголовок команды - /// Маркер prevpage - /// Кнопки обработчики - /// Постраничное inline menu + /// Текущая страница. + /// Всего страниц. + /// Маркер nextpage. + /// Заголовок команды. + /// Маркер prevpage. + /// Кнопки обработчики. + /// Постраничное inline menu. public static InlineKeyboardMarkup GetPageMenu( int currentPage, int pageCount, diff --git a/PRTelegramBot/Utils/MessageAwaiter.cs b/PRTelegramBot/Utils/MessageAwaiter.cs index 4e8c49b..496fc9a 100644 --- a/PRTelegramBot/Utils/MessageAwaiter.cs +++ b/PRTelegramBot/Utils/MessageAwaiter.cs @@ -1,4 +1,6 @@ -using Telegram.Bot; +using PRTelegramBot.Extensions; +using PRTelegramBot.Interfaces; +using Telegram.Bot; using Telegram.Bot.Types; using Message = Telegram.Bot.Types.Message; @@ -12,9 +14,9 @@ public class MessageAwaiter : IDisposable #region Поля и свойства /// - /// Клиент бота. + /// Контекст бота. /// - private ITelegramBotClient botClient; + private IBotContext context; /// /// Сообщение. @@ -30,6 +32,7 @@ public class MessageAwaiter : IDisposable #region IDisposable + /// public void Dispose() { _ = DeleteMessage(); @@ -45,7 +48,7 @@ public void Dispose() /// Текст сообщения. public async Task CreateAwaitMessage(string messageText) { - message = await botClient.SendMessage(chatId, messageText); + message = await context.BotClient.SendMessage(chatId, messageText); } /// @@ -55,7 +58,7 @@ public async Task DeleteMessage() { try { - await botClient.DeleteMessage(chatId, message.MessageId); + await context.BotClient.DeleteMessage(chatId, message.MessageId); } catch (Exception ex) { } } @@ -67,21 +70,20 @@ public async Task DeleteMessage() /// /// Конструктор. /// - /// Бот клиент. + /// Контекст бота. /// Идентификатор чата. - public MessageAwaiter(ITelegramBotClient botClient, long chatId) - : this(botClient, chatId, "⏳ Генерирую ответ...") { } + public MessageAwaiter(IBotContext context, long chatId) + : this(context, "⏳ Генерирую ответ...") { } /// /// Конструктор. /// - /// Бот клиент. - /// Идентификатор чата. + /// Контекст бота. /// тест сообщения ожидания. - public MessageAwaiter(ITelegramBotClient botClient, long chatId, string messageAwaiterText) + public MessageAwaiter(IBotContext context, string messageAwaiterText) { - this.botClient = botClient; - this.chatId = new ChatId(chatId); + this.context = context; + this.chatId = new ChatId(context.GetChatId()); _ = CreateAwaitMessage(messageAwaiterText); } diff --git a/PRTelegramBot/Utils/ReflectionUtils.cs b/PRTelegramBot/Utils/ReflectionUtils.cs index 0cbdc8e..45194dc 100644 --- a/PRTelegramBot/Utils/ReflectionUtils.cs +++ b/PRTelegramBot/Utils/ReflectionUtils.cs @@ -1,9 +1,8 @@ using PRTelegramBot.Attributes; using PRTelegramBot.Core; using PRTelegramBot.Interfaces; +using PRTelegramBot.Models.EventsArgs; using System.Reflection; -using Telegram.Bot; -using Telegram.Bot.Types; namespace PRTelegramBot.Utils { @@ -166,7 +165,7 @@ public static Type[] FindClassesWithBotHandlerAttribute() { var types = assembly .GetTypes() - .Where(t => t.IsClass && t.GetCustomAttribute(typeof(BotHandlerAttribute)) != null); + .Where(t => t.IsClass && t.GetCustomAttribute(typeof(BotHandlerAttribute)) is not null); foreach (var type in types) uniqueTypes.Add(type); @@ -179,15 +178,13 @@ public static bool IsValidMethodForBaseBaseQueryAttribute(PRBotBase bot, MethodI try { Type expectedReturnType = typeof(Task); - Type expectedBotClientType = typeof(ITelegramBotClient); - Type expectedUpdateType = typeof(Update); + Type expectedBotContext = typeof(IBotContext); ParameterInfo[] parameters = method.GetParameters(); if (method.ReturnType == expectedReturnType && - parameters.Length == 2 && - parameters[0].ParameterType == expectedBotClientType && - parameters[1].ParameterType == expectedUpdateType) + parameters.Length == 1 && + parameters[0].ParameterType == expectedBotContext) { return true; } @@ -198,7 +195,7 @@ public static bool IsValidMethodForBaseBaseQueryAttribute(PRBotBase bot, MethodI } catch (Exception ex) { - bot.Events.OnErrorLogInvoke(ex); + bot.Events.OnErrorLogInvoke(ErrorLogEventArgs.Create(bot, ex)); return false; } } diff --git a/README.md b/README.md index aa742fa..25e2985 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![Static Badge](https://img.shields.io/badge/version-v0.7.12-brightgreen) ![Static Badge](https://img.shields.io/badge/telegram.bot-22.7.2-blue) ![NuGet Downloads](https://img.shields.io/nuget/dt/prtelegrambot) ![NuGet Version](https://img.shields.io/nuget/v/prtelegrambot) +![Static Badge](https://img.shields.io/badge/version-v0.8-brightgreen) ![Static Badge](https://img.shields.io/badge/telegram.bot-22.7.2-blue) ![NuGet Downloads](https://img.shields.io/nuget/dt/prtelegrambot) ![NuGet Version](https://img.shields.io/nuget/v/prtelegrambot) > **Если данный проект был для вас полезен и хотите его поддержать, можете поставить ⭐ в репозитории проекта. diff --git a/Templates/FastBotTemplate/Commands/StartCommands.cs b/Templates/FastBotTemplate/Commands/StartCommands.cs index 4496aef..433fc27 100644 --- a/Templates/FastBotTemplate/Commands/StartCommands.cs +++ b/Templates/FastBotTemplate/Commands/StartCommands.cs @@ -1,6 +1,5 @@ using PRTelegramBot.Attributes; -using Telegram.Bot.Types; -using Telegram.Bot; +using PRTelegramBot.Interfaces; using PRTelegramBot.Models.EventsArgs; namespace FastBotTemplateConsole.Commands @@ -8,14 +7,14 @@ namespace FastBotTemplateConsole.Commands internal class StartCommands { [SlashHandler("/start")] - public static async Task Start(ITelegramBotClient botClient, Update update) + public static Task Start(IBotContext context) { - + return Task.CompletedTask; } - public static async Task StartWithArguments(StartEventArgs e) + public static Task StartWithArguments(StartEventArgs e) { - + return Task.CompletedTask; } } } diff --git a/Templates/FastBotTemplate/Events/LogEvents.cs b/Templates/FastBotTemplate/Events/LogEvents.cs index 4ce260b..a8b6b35 100644 --- a/Templates/FastBotTemplate/Events/LogEvents.cs +++ b/Templates/FastBotTemplate/Events/LogEvents.cs @@ -4,20 +4,22 @@ namespace FastBotTemplateConsole.Events { internal class LogEvents { - public static async Task OnLogError(ErrorLogEventArgs e) + public static Task OnLogError(ErrorLogEventArgs e) { Console.ForegroundColor = ConsoleColor.Red; string errorMsg = $"{DateTime.Now}: {e.Exception.ToString()}"; Console.WriteLine(errorMsg); Console.ResetColor(); + return Task.CompletedTask; } - public static async Task OnLogCommon(CommonLogEventArgs e) + public static Task OnLogCommon(CommonLogEventArgs e) { Console.ForegroundColor = e.Color; string formatMsg = $"{DateTime.Now}: {e.Message}"; Console.WriteLine(formatMsg); Console.ResetColor(); + return Task.CompletedTask; } } } diff --git a/Templates/FastBotTemplate/Models/Announcement.cs b/Templates/FastBotTemplate/Models/Announcement.cs index 353f43e..57d2de7 100644 --- a/Templates/FastBotTemplate/Models/Announcement.cs +++ b/Templates/FastBotTemplate/Models/Announcement.cs @@ -8,101 +8,101 @@ namespace FastBotTemplateConsole.Models { /// - /// Реклама / объявления + /// Реклама / объявления. /// Entity framework /// [Table("Announcements")] public class Announcement { /// - /// Идентификатор + /// Идентификатор. /// [Column("id")] public long Id { get; set; } /// - /// Описание + /// Описание. /// [Column("description")] public string Description { get; set; } /// - /// Ссылка на медиа, фото, видео + /// Ссылка на медиа, фото, видео. /// [Column("media")] public string? Media { get; set; } /// - /// Текст сообщения рекламы + /// Текст сообщения рекламы. /// [Column("text")] public string Text { get; set; } /// - /// Дата создания + /// Дата создания. /// [Column("create_date")] public DateTime CreateDate { get; set; } /// - /// Активна или нет + /// Активна или нет. /// [Column("is_active")] public bool IsActive { get; set; } /// - /// Данные для меню + /// Данные для меню. /// [Column("menu_data")] public string? MenuData { get; set; } /// - /// Тип меню рекламы + /// Тип меню рекламы. /// [Column("menu_type")] public MenuType MenuType { get; set; } /// - /// Тип сообщения рекламы + /// Тип сообщения рекламы. /// [Column("message_type")] public MessageType MessageType { get; set; } /// - /// Минимальный возраст для показа рекламы + /// Минимальный возраст для показа рекламы. /// [Column("start_age")] public long? StartAge { get; set; } /// - /// Максимальный возраст для показа рекламы + /// Максимальный возраст для показа рекламы. /// [Column("end_age")] public long? EndAge { get; set; } /// - /// Список тегов, перечесление через ; + /// Список тегов, перечисление через ";". /// [Column("tags")] public string? Tags { get; set; } /// - /// Количество просмотров + /// Количество просмотров. /// [Column("viewed")] public long Viewed { get; set; } /// - /// Генерирует inline меню со ссылками есть есть данные для меню в MenuData + /// Генерирует inline меню со ссылками есть есть данные для меню в MenuData. /// - /// Возращает меню или пустой список + /// Возвращает меню или пустой список. public List GetMenu() { try { - return JsonSerializer.Deserialize>(MenuData ?? ""); + return JsonSerializer.Deserialize>(MenuData ?? string.Empty); } - catch (Exception ex) + catch { return new List(); } @@ -110,9 +110,9 @@ public List GetMenu() } /// - /// Сериази + /// Сериализация inline меню. /// - /// + /// Меню /// public static string WriteMenu(List menu) { @@ -120,9 +120,9 @@ public static string WriteMenu(List menu) { return JsonSerializer.Serialize(menu); } - catch (Exception ex) + catch { - return ""; + return string.Empty; } } diff --git a/Templates/FastBotTemplate/Models/UserBot.cs b/Templates/FastBotTemplate/Models/UserBot.cs index c446188..cbdcc85 100644 --- a/Templates/FastBotTemplate/Models/UserBot.cs +++ b/Templates/FastBotTemplate/Models/UserBot.cs @@ -86,7 +86,7 @@ public string GetName() { if (!string.IsNullOrEmpty(FirstName) || !string.IsNullOrEmpty(LastName)) { - string tempName = ""; + string tempName = string.Empty; tempName += FirstName + " "; tempName += LastName; return tempName; diff --git a/Templates/FastBotTemplate/Program.cs b/Templates/FastBotTemplate/Program.cs index 1a7becc..4f46694 100644 --- a/Templates/FastBotTemplate/Program.cs +++ b/Templates/FastBotTemplate/Program.cs @@ -6,7 +6,7 @@ namespace FastBotTemplateConsole { internal class Program { - static async Task Main(string[] args) + static Task Main(string[] args) { var bot = new PRBotBuilder("Token") .SetBotId(0) @@ -17,7 +17,7 @@ static async Task Main(string[] args) bot.Events.OnErrorLog += LogEvents.OnLogError; bot.Events.OnUserStartWithArgs += StartCommands.StartWithArguments; - _ = bot.Start(); + _ = bot.StartAsync(); // Чтобы консолька не закрылась. while(true) { }