Esempio n. 1
0
        static BotManager ConfSecondBot(IServiceCollection services)
        {
            var bot = new TelegramBotClient(
                BotTokenResolver.GetSecondToken(),
                new QueuedHttpClient(TimeSpan.FromMilliseconds(50))
                );
            var botManager = new BotManager(bot, services);

            botManager.ConfigureServices((servicesWrap) =>
            {
                servicesWrap.AddMvc();
            });
            botManager.ConfigureBuilder(builder =>
            {
                builder.UseDevEceptionMessage();
                builder.UseOldUpdatesIgnoring();
                builder.UseMvc(mvcBuilder =>
                {
                    //mvcBuilder.Controllers = new List<Type>()
                    //{
                    //    typeof(SecondBotController)
                    //};
                    mvcBuilder.RemoveControllersByNamespace(
                        "IRO.Tests.Telegram.TwoBotsOneServiceProvider.TelegramControllers.FirstBotControllers"
                        );
                    mvcBuilder.UseDebugInfo();
                });
            });
            return(botManager);
        }
Esempio n. 2
0
        public void Run(BotManager botManager, bool isDebug)
        {
            botManager.ConfigureServices((servicesWrap) =>
            {
                var serv = servicesWrap.Services;
                LoggerStarter.InitLogger(servicesWrap);
                servicesWrap.AddMvc(new MvcOptions()
                {
                    CheckEqualsRouteInfo = true
                });

                serv.AddSingleton <ITelegramBotClient>((sp) =>
                {
                    return(botManager.BotContext.Bot);
                });
                serv.AddScoped <ISomeScopedService, SomeScopedService>();


                //Telegram storage test
                var opt = new TelegramStorageOptions()
                {
                    SaveResourcesChatId = BotTokenResolver.GetSaveResChatId(),
                    SaveOnSet           = true
                };
                serv.AddSingleton(opt);
                serv.AddSingleton <TelegramStorage>();
                serv.AddSingleton <IKeyValueStorage>((sp) =>
                {
                    return(sp.GetRequiredService <TelegramStorage>());
                });
                serv.AddSingleton <TelegramFilesCloud>();
            });

            botManager.ConfigureBuilder((builder) =>
            {
                if (isDebug)
                {
                    builder.UseDevEceptionMessage();
                }

                builder.UseExceptionHandler(async(ctx, ex) =>
                {
                    //Throw exception if false. False mean 'not handled'.
                    return(false);
                });

                builder.UseMvc(mvcBuilder =>
                {
                    mvcBuilder.UseDebugInfo();
                    mvcBuilder.MapRouteAction(async(actionCtx) =>
                    {
                        await actionCtx.UpdateContext.SendTextMessageAsync("Mvc works.");
                    }, template: "/mvc");
                });
            });
            botManager.Start();
        }
Esempio n. 3
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            app.Use(async(ctx, next) =>
            {
                var path = ctx.Request.Path.ToString();
                if (path == "" || path == "/")
                {
                    await ctx.Response.WriteAsync("Webhooks server. Please don't forget update domain constant.");
                }
                await next();
            });

            _botManager.ConfigureBuilder(builder =>
            {
                //builder.UseExceptionHandler(async (ctx, ex) =>
                //{
                //    await ctx.SendTextMessageAsync("Unhandled bot exception.");
                //    return false;
                //});
                builder.UseDevEceptionMessage();
                builder.UseOldUpdatesIgnoring();
                builder.UseMvc(mvcBuilder =>
                {
                    mvcBuilder.UseDebugInfo();
                });
            });

            //Note: update your pathTemplate and add there some string, that will identify telegram webhooks.
            //Something like: "wad5kK2PVL0SAEPq43q5cR2qwFWF4434/{0}". It must be same for all server processes.
            //=========
            //Use setWebhookAutomatically:false to configure how telegram webhook will work.
            var webhookReceiver = WebhookUpdatesReceiver.Create(
                app,
                _domain,
                pathTemplate: "telegram/update/{0}",
                setWebhookAutomatically: false
                );

            _botManager.Setup(
                updatesReceiver: webhookReceiver
                );

            //SetWebhookAsync not needed if setWebhookAutomatically is true.
            _botManager.BotContext.Bot.SetWebhookAsync(
                webhookReceiver.WebhookFullUrl,
                allowedUpdates: UpdateTypeExtensions.All
                ).Wait();

            _botManager.Start();
        }
        static void Main(string[] args)
        {
            var bot = new TelegramBotClient(
                BotTokenResolver.GetToken(),
                new QueuedHttpClient(TimeSpan.FromSeconds(1))
                );
            var botManager = new BotManager(bot);

            botManager.ConfigureServices((servicesWrap) =>
            {
                servicesWrap.AddMvc(new MvcOptions()
                {
                    //Useful for debugging.
                    CheckEqualsRouteInfo = true
                });

                //Logging service example with NLog you can see in IRO.Tests.Telegram.
            });

            botManager.ConfigureBuilder(builder =>
            {
                builder.UseDevEceptionMessage();
                builder.UseOldUpdatesIgnoring();
                builder.UseMvc(mvcBuilder =>
                {
                    //Write /debug to see info about routing.
                    mvcBuilder.UseDebugInfo();

                    mvcBuilder.MapRouteAction(
                        async(actionCtx) =>
                    {
                        await actionCtx.UpdateContext.SendTextMessageAsync("Bot commands works.");
                    },
                        template: "/help"
                        );
                });
            });

            //Default implemention use standart ITelegramBotClient polling.
            //You can add webhooks implemention using Telegram.Bot.AspNetPipeline.WebhookSupport or
            //write your own IUpdatesReceiver.
            botManager.Setup();
            botManager.Start();

            Console.WriteLine("Bot initialized.");
            while (true)
            {
                Console.ReadLine();
            }

            botManager.Dispose();
        }
        static void Main2(string[] args)
        {
            var bot        = new TelegramBotClient("<token>");
            var botManager = new BotManager(bot);

            botManager.ConfigureServices((servicesWrap) =>
            {
                servicesWrap.AddMvc();
            });
            botManager.ConfigureBuilder(builder =>
            {
                builder.UseMvc();
            });
            botManager.Start();
        }
        public void Run(BotManager botManager, bool isDebug)
        {
            botManager.ConfigureServices((servicesWrap) =>
            {
                LoggerStarter.InitLogger(servicesWrap);
            });

            botManager.ConfigureBuilder((builder) =>
            {
                builder.AddBotExtGlobalValidator(async(upd, origCtx) =>
                {
                    if (upd.Message?.Text.StartsWith("/") == true)
                    {
                        return(UpdateValidatorResult.AbortWaiter);
                    }
                    return(UpdateValidatorResult.Valid);
                });
                builder.Use(async(ctx, next) =>
                {
                    if (ctx.Message?.Text == null)
                    {
                        await ctx.SendTextMessageAsync("Not text message.");
                        ctx.ForceExit();
                        return;
                    }

                    var ctxTrimmedText = ctx.Message.Text.Trim();
                    Message msg        = null;
                    if (ctxTrimmedText.StartsWith("/help"))
                    {
                        await ctx.SendTextMessageAsync("Commands:\n" +
                                                       "/current_user_reply\n" +
                                                       "/current_user\n" +
                                                       "/any_user\n" +
                                                       "/any_user_reply");
                        ctx.Processed();
                    }
                    else if (ctxTrimmedText.StartsWith("/any_user_reply"))
                    {
                        await ctx.SendTextMessageAsync("Reply to bot to process message.");
                        msg = await ctx.BotExt.ReadMessageAsync(ReadCallbackFromType.AnyUserReply);
                    }
                    else if (ctxTrimmedText.StartsWith("/current_user_reply"))
                    {
                        await ctx.SendTextMessageAsync("Reply to bot to process message.");
                        msg = await ctx.BotExt.ReadMessageAsync(ReadCallbackFromType.CurrentUserReply);
                    }
                    else if (ctxTrimmedText.StartsWith("/current_user"))
                    {
                        msg = await ctx.BotExt.ReadMessageAsync();
                    }
                    else if (ctxTrimmedText.StartsWith("/any_user"))
                    {
                        msg = await ctx.BotExt.ReadMessageAsync(ReadCallbackFromType.AnyUser);
                    }

                    if (msg != null)
                    {
                        ctx.Processed();
                        var msgText = msg.Text;
                        await ctx.SendTextMessageAsync($"Command : '{ctxTrimmedText}'.\n" +
                                                       $"Awaited msg: '{msgText}'.");
                    }


                    await next();
                });
                builder.Use(async(ctx, next) =>
                {
                    //if (!ctx.IsProcessed)
                    //    await ctx.SendTextMessageAsync($"Not processed '{ctx.Message.Text}'.");
                    await next();
                });

                builder.UseExceptionHandler(async(ctx, ex) =>
                {
                    return(false);
                });
                builder.UseDevEceptionMessage();
            });

            botManager.Start();
        }