Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        static async Task Main(string[] args)
        {
            var options = new ConfigurationBuilder().AddJsonFile("appsettings.Development.json").Build()
                          ?? throw new ArgumentNullException(
                                    "new ConfigurationBuilder().AddJsonFile(\"appsettings.Development.json\").Build()");
            ServiceCollection services = new ServiceCollection();

            services.AddScoped <IMongoDatabase>(x =>
                                                new MongoClient(options["MongoDbConnectionString"]).GetDatabase("GameBot"));
            services.AddSingleton <ITelegramBotClient>(x =>
                                                       new TelegramBotClient(options.GetSection("GameBot")["ApiToken"]));

            services.AddSingleton <GameBot>();
            services.AddScoped <ExceptionHandler>();
            services.AddScoped <GameObjectBuilder>();
            services.AddScoped <UserStateReaction>();
            services.AddScoped <StartCommand>();
            services.AddScoped <HelpCommand>();
            services.AddScoped <SosCommand>();
            services.AddScoped <InlineQueryResolver>();
            services.AddScoped <BasicTextInputsResolver>();
            services.AddScoped <QuestExampleHandler>();
            services.AddScoped <ExampleCallbackQuery>();
            services.AddScoped <ExampleButtonHandler>();

            var manager = new UpdatePollingManager <GameBot>(ConfigureBot(),
                                                             new BotServiceProvider(services.BuildServiceProvider()));
            var requestFilter = new GetUpdatesRequest();

            requestFilter.AllowedUpdates = new[] { UpdateType.Message, UpdateType.CallbackQuery, UpdateType.InlineQuery };

            await manager.RunAsync();
        }
        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
                          );
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            string token = Environment.GetEnvironmentVariable("BOT_API_TOKEN") ?? "YOUR_API_TOKEN_HERE";

            var container = new Container();

            container.Register(() => new EchoBot(token));
            container.Register <ExceptionHandler>();
            container.Register <IWeatherService, WeatherService>();
            container.Verify();

            var mgr = new UpdatePollingManager <EchoBot>(ConfigureBot(), new BotServiceProvider(container));

            var tokenSrc = new CancellationTokenSource();

            Task.Run(() =>
            {
                Console.ReadLine();
                tokenSrc.Cancel();
            });

            mgr.RunAsync(cancellationToken: tokenSrc.Token).GetAwaiter().GetResult();
        }
Exemplo n.º 6
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);
        }