public void ConfigureServices(IServiceCollection services)
        {
            //Usage of same ServiceCollection for telegram library and asp.net is bad idea.
            //At first I thought differently, but in practice this model was not very convenient if you need to use many bots on one server process.
            //More precisely, the problem is the common services collection between the bots themselves.
            //or use separate collections for asp and bots.
            //But in this example i use one collection to show how you can do it, because it's really can be difficult.
            //And i recommend to add bot library after all services, to override some settings in service collection.
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var token = BotTokenResolver.GetToken();
            var bot   = new Telegram.Bot.TelegramBotClient(token, new QueuedHttpClient(TimeSpan.FromSeconds(1)));

            _botManager = new BotManager(bot, services);

            //Invoked synchronous.
            _botManager.ConfigureServices((servicesWrap) =>
            {
                servicesWrap.AddMvc(new Telegram.Bot.AspNetPipeline.Mvc.Builder.MvcOptions()
                {
                    //Useful for debugging.
                    CheckEqualsRouteInfo = true
                });

                //Logging service example with NLog you can see in IRO.Tests.Telegram.
            });
        }
Beispiel #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            var token = BotTokenResolver.GetToken();
            var bot   = new Telegram.Bot.TelegramBotClient(
                token,
                new QueuedHttpClient(TimeSpan.FromSeconds(1))
                );

            _botManager = new BotManager(bot);

            //Invoked synchronous.
            _botManager.ConfigureServices((servicesWrap) =>
            {
                //Init our LiteDB.
                servicesWrap.Services.AddLiteDataAccessLayer();
                servicesWrap.Services.AddSingleton <IGameLogicService, GameLogicService>();

                servicesWrap.AddMvc(new Telegram.Bot.AspNetPipeline.Mvc.Builder.MvcOptions()
                {
                    //Useful for debugging.
                    CheckEqualsRouteInfo = true
                });
            });
        }
Beispiel #3
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);
        }
Beispiel #4
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();
        }
        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();
        }