示例#1
0
 /// <summary>
 /// Removes and disables webhooks for bot. Using default Telegram Bot Instance
 /// </summary>
 /// <param name="app">Instance of IApplicationBuilder</param>
 /// <param name="botBuilder">Bot builder, implemented by framework user</param>
 /// <param name="startAfter">Timeout for starting update manager</param>
 /// <param name="cancellationToken">Standart threading cancellation token to stop process</param>
 /// <returns>Instance of IApplicationBuilder</returns>
 public static IApplicationBuilder UseTelegramBotLongPolling(this IApplicationBuilder app,
                                                             IBotBuilder botBuilder,
                                                             TimeSpan startAfter = default,
                                                             CancellationToken cancellationToken = default)
 {
     return(UseTelegramBotLongPolling <TelegramBot>(app, botBuilder, startAfter, cancellationToken));
 }
        public static void UseTelegramBotLongPolling <TBot>(
            this IApplicationBuilder app,
            IBotBuilder botBuilder,
            TimeSpan startAfter = default,
            CancellationToken cancellationToken = default
            )
            where TBot : BotBase
        {
            var logger = app.ApplicationServices.GetRequiredService <ILogger <Startup> >();

            if (startAfter == default)
            {
                startAfter = TimeSpan.FromSeconds(2);
            }

            var updateManager = new UpdatePollingManager <TBot>(botBuilder, new BotServiceProvider(app));

            Task.Run(async() =>
            {
                await Task.Delay(startAfter, cancellationToken)
                .ConfigureAwait(false);
                await updateManager.RunAsync(cancellationToken: cancellationToken)
                .ConfigureAwait(false);
            },
                     cancellationToken)
            .ContinueWith(t =>
            {
                logger.LogError(t.Exception, "Bot update manager failed.");
                throw t.Exception;
            }, TaskContinuationOptions.OnlyOnFaulted
                          );
        }
示例#3
0
        /// <summary>
        /// Removes and disables webhooks for bot
        /// </summary>
        /// <typeparam name="TBot">Type of bot</typeparam>
        /// <param name="app">Instance of IApplicationBuilder</param>
        /// <param name="botBuilder">Bot builder, implemented by framework user</param>
        /// <param name="startAfter">Timeout for starting update manager</param>
        /// <param name="cancellationToken">Standart threading cancellation token to stop process</param>
        /// <returns>Instance of IApplicationBuilder</returns>
        public static IApplicationBuilder UseTelegramBotLongPolling <TBot>(this IApplicationBuilder app,
                                                                           IBotBuilder botBuilder,
                                                                           TimeSpan startAfter = default,
                                                                           CancellationToken cancellationToken = default) where TBot : IBot
        {
            if (startAfter == default)
            {
                startAfter = TimeSpan.FromSeconds(2);
            }

            using (var scope = app.ApplicationServices.CreateScope())
            {
                var logger        = scope.ServiceProvider.GetRequiredService <ILogger <IApplicationBuilder> >();
                var updateManager = new UpdatePollingManager <TBot>(botBuilder, new BotServiceProvider(app));

                Task.Run(async() =>
                {
                    await Task.Delay(startAfter, cancellationToken);
                    await updateManager.RunAsync(cancellationToken: cancellationToken);
                }, cancellationToken)
                .ContinueWith(t =>
                {
                    logger.LogError(t.Exception, "Error on updating the bot by LongPooling method.");
                    throw t.Exception;
                }, TaskContinuationOptions.OnlyOnFaulted);
            }
            return(app);
        }
示例#4
0
 /// <summary>
 /// Add Telegram bot webhook handling functionality to the pipeline. Using default Telegram Bot Instance
 /// </summary>
 /// <param name="app">Instance of IApplicationBuilder</param>
 /// <param name="botBuilder">Bot builder, implemented by framework user</param>
 /// <returns>Instance of IApplicationBuilder</returns>
 public static IApplicationBuilder UseTelegramBotWebhook(
     this IApplicationBuilder app,
     IBotBuilder botBuilder
     )
 {
     return(UseTelegramBotWebhook <TelegramBot>(app, botBuilder));
 }
示例#5
0
        public static IApplicationBuilder UseTelegramBotLongPolling <TBot>(
            this IApplicationBuilder app,
            IBotBuilder botBuilder,
            TimeSpan startAfter = default,
            CancellationToken cancellationToken = default)
            where TBot : BotBase
        {
            if (startAfter == default)
            {
                startAfter = TimeSpan.FromSeconds(2);
            }

            var updateManager = new UpdatePollingManager <TBot>(botBuilder, new BotServiceProvider(app));

            Task.Run(async() =>
            {
                await Task.Delay(startAfter, cancellationToken);
                await updateManager.RunAsync(cancellationToken: cancellationToken);
            }, cancellationToken)
            .ContinueWith(t =>
            {                               // ToDo use logger
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(t.Exception);
                Console.ResetColor();
                if (t.Exception != null)
                {
                    throw t.Exception;
                }
            }, TaskContinuationOptions.OnlyOnFaulted);

            return(app);
        }
示例#6
0
 public static IBotBuilder TaskMenuHandlers(this IBotBuilder builder) =>
 builder.UseWhen <RootPageHandle>(RootPageHandle.CanHandle)
 .UseWhen <SelectedTaskHandle>(SelectedTaskHandle.CanHandle)
 .UseWhen <SelectedOptionHandle>(SelectedOptionHandle.CanHandle)
 .UseWhen <SelectedResourceHandle>(SelectedResourceHandle.CanHandle)
 .UseWhen <SelectedDeadlineHandle>(SelectedDeadlineHandle.CanHandle)
 .UseWhen <SelectedHourTask>(SelectedHourTask.CanHandle)
 .UseWhen <CancelHandle>(CancelHandle.CanHandle);
        public static IBotBuilder UseWhen <THandler>(this IBotBuilder builder, Predicate <IUpdateContext> predicate)
            where THandler : IUpdateHandler
        {
            var branchDelegate = new BotBuilder().Use <THandler>().Build();

            builder.Use(new UseWhenMiddleware(predicate, branchDelegate));
            return(builder);
        }
 public UpdatePollingManager(
     IBotBuilder botBuilder,
     IBotServiceProvider rootProvider
     )
 {
     // ToDo Receive update types array
     _updateDelegate = botBuilder.Build();
     _rootProvider   = rootProvider;
 }
 public static IBotBuilder UseCommand <TCommand>(
     this IBotBuilder builder,
     string command
     )
     where TCommand : CommandBase
 => builder
 .MapWhen(
     ctx => ctx.Bot.CanHandleCommand(command, ctx.Update.Message),
     botBuilder => botBuilder.Use <TCommand>()
     );
示例#10
0
        public static IBotBuilder UseCommandLogger(this IBotBuilder botBuilder)
        {
            var logger = botBuilder.Services.GetService <ILogger>();

            botBuilder.Commands.Log += message =>
            {
                logger.LogInformation(message.ToString());
                return(Task.CompletedTask);
            };

            return(botBuilder);
        }
示例#11
0
        public static IBotBuilder MapWhen(this IBotBuilder builder,
                                          Predicate <IUpdateContext> predicate,
                                          Action <IBotBuilder> configure)
        {
            var mapBuilder = new BotBuilder();

            configure(mapBuilder);
            UpdateDelegate mapDelegate = mapBuilder.Build();

            builder.Use(new MapWhenMiddleware(predicate, mapDelegate));

            return(builder);
        }
        public static IBotBuilder UseWhen(
            this IBotBuilder builder,
            Predicate <IUpdateContext> predicate,
            Action <IBotBuilder> configure
            )
        {
            var branchBuilder = new BotBuilder();

            configure(branchBuilder);
            UpdateDelegate branchDelegate = branchBuilder.Build();

            builder.Use(new UseWhenMiddleware(predicate, branchDelegate));

            return(builder);
        }
示例#13
0
        /// <summary>
        /// Add Telegram bot webhook handling functionality to the pipeline
        /// </summary>
        /// <typeparam name="TBot">Type of bot</typeparam>
        /// <param name="app">Instance of IApplicationBuilder</param>
        /// <param name="ensureWebhookEnabled">Whether to set the webhook immediately by making a request to Telegram bot API</param>
        /// <returns>Instance of IApplicationBuilder</returns>
        public static IApplicationBuilder UseTelegramBotWebhook <TBot>(
            this IApplicationBuilder app,
            IBotBuilder botBuilder
            )
            where TBot : BotBase
        {
            var updateDelegate = botBuilder.Build();

            var options = app.ApplicationServices.GetRequiredService <IOptions <BotOptions <TBot> > >();

            app.Map(
                options.Value.WebhookPath,
                builder => builder.UseMiddleware <TelegramBotMiddleware <TBot> >(updateDelegate)
                );

            return(app);
        }
示例#14
0
        public static IApplicationBuilder UseTelegramBotLongPolling <TBot>(
            this IApplicationBuilder app,
            IBotBuilder botBuilder,
            IConfiguration configuration,
            TimeSpan startAfter = default,
            CancellationToken cancellationToken = default
            )
            where TBot : BotBase
        {
            if (startAfter == default)
            {
                startAfter = TimeSpan.FromSeconds(2);
            }
            var updateManager = new UpdatePollingManager <TBot>(botBuilder, new BotServiceProvider(app));

            Task.Run(async() =>
            {
                await Task.Delay(startAfter, cancellationToken);
                await updateManager.RunAsync(cancellationToken: cancellationToken);
            }, cancellationToken)
            .ContinueWith(t =>
            {// ToDo use logger
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(t.Exception);
                Console.ResetColor();
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    var bot            = scope.ServiceProvider.GetRequiredService <TBot>();
                    var debugGroupId   = configuration.GetValue <string>("DebugGroup", "-368260554");
                    var siteName       = configuration.GetValue <string>("SiteName", "TelegramBotApi");
                    var restartService = scope.ServiceProvider.GetRequiredService <KeepAliveService>();
                    Task.Run(() => restartService.DoRestart(bot.Client, debugGroupId, t.Exception, siteName));
                }
                throw t.Exception;
            }, TaskContinuationOptions.OnlyOnFaulted);
            return(app);
        }
        public static void UseViews(this IBotBuilder botBuilder, CommandViewService.ErrorHandler errorHandler)
        {
            var commandView = new CommandViewService(errorHandler);

            botBuilder.Commands.CommandExecuted += commandView.OnCommandExecutedAsync;
        }
示例#16
0
 public StateCacheService(
     IBotBuilder botBuilder
     )
 {
     _updateDelegate = botBuilder.Build();
 }
 public static IServiceCollection AddBotStateCache <TStateCache>(
     this IServiceCollection services,
     IBotBuilder botBuilder
     )
     where TStateCache : IStateProvider, new()
 => services.AddSingleton <IStateCacheService>(new StateCacheService <TStateCache>(botBuilder));
示例#18
0
 protected virtual void Configure(IBotBuilder builder)
 {
 }
示例#19
0
        //public static IServiceCollection AddCalendarBot(this IServiceCollection services, IConfigurationSection botConfiguration) =>
        //    services.AddTransient<CalendarBot>()
        //        .Configure<BotOptions<CalendarBot>>(botConfiguration)
        //        .Configure<CustomBotOptions<CalendarBot>>(botConfiguration)
        //        .AddScoped<FaultedUpdateHandler>()
        //        .AddScoped<CalendarCommand>()
        //        .AddScoped<ChangeToHandler>()
        //        .AddScoped<PickDateHandler>()
        //        .AddScoped<YearMonthPickerHandler>()
        //        .AddScoped<MonthPickerHandler>()
        //        .AddScoped<YearPickerHandler>();

        //public static IServiceCollection AddOperationServices(this IServiceCollection services) =>
        //    services
        //        .AddTransient<LocalizationService>();

        public static IBotBuilder CalendarHandlers(this IBotBuilder builder) =>
        builder.UseWhen <ChangeToHandler>(ChangeToHandler.CanHandle)
        .UseWhen <YearMonthPickerHandler>(YearMonthPickerHandler.CanHandle)
        .UseWhen <MonthPickerHandler>(MonthPickerHandler.CanHandle)
        .UseWhen <YearPickerHandler>(YearPickerHandler.CanHandle);