Пример #1
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var context       = builder.GetContext();
            var configuration = context.Configuration;
            var services      = builder.Services;
            var hostname      = configuration.GetValue <string>("WEBSITE_HOSTNAME");

            // Adaptive component registration
            ComponentRegistration.Add(new DialogsComponentRegistration());
            ComponentRegistration.Add(new DeclarativeComponentRegistration());
            ComponentRegistration.Add(new AdaptiveComponentRegistration());
            ComponentRegistration.Add(new LanguageGenerationComponentRegistration());
            ComponentRegistration.Add(new LucyComponentRegistration());

            services.AddLogging();
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddSingleton(sp => new AuthenticationConfiguration {
                ClaimsValidator = new AllowedCallersClaimsValidator(configuration)
            });
            services.AddSingleton <IStorage>((s) => new BlobsStorage(configuration.GetValue <string>("AzureWebJobsStorage"), configuration.GetValue <string>("BotId").ToLower()));
            services.AddSingleton <UserState>(s => new UserState(s.GetService <IStorage>()));
            services.AddSingleton <ConversationState>(s => new ConversationState(s.GetService <IStorage>()));
            services.AddSingleton <QueueStorage>((s) => (QueueStorage) new AzureQueueStorage(configuration.GetValue <string>("AzureWebJobsStorage"), "activities"));

            // skill support
            // Register the skills client and skills request handler.
            services.AddSingleton <SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            services.AddHttpClient <SkillHttpClient>();
            services.AddSingleton <SkillHandler>();

            // bot framework adapter defintion
            services.AddSingleton <BotFrameworkHttpAdapter>(s =>
            {
                // create botframework adapter for processing conversations with users.
                var adapter = new BotFrameworkHttpAdapter(s.GetService <ICredentialProvider>(), s.GetService <AuthenticationConfiguration>())
                              .Use(new RegisterClassMiddleware <IConfiguration>(s.GetService <IConfiguration>()))
                              .UseStorage(s.GetService <IStorage>())
                              .UseBotState(s.GetService <UserState>(), s.GetService <ConversationState>())
                              //.Use(new TranscriptLoggerMiddleware(s.GetService<ITranscriptStore>()))
                              .Use(new RegisterClassMiddleware <QueueStorage>(s.GetService <QueueStorage>()));

                if (hostname.StartsWith("localhost") && int.TryParse(hostname.Split(':')[1], out var port))
                {
                    adapter.UseDebugger(port + 1000);
                }

                adapter.OnTurnError = async(turnContext, exception) =>
                {
                    var log = s.GetService <ILogger>();
                    var conversationState = turnContext.TurnState.Get <ConversationState>();
                    await conversationState.ClearStateAsync(turnContext).ConfigureAwait(false);
                    await conversationState.SaveChangesAsync(turnContext).ConfigureAwait(false);

                    try
                    {
                        await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError");
                        await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false);
                    }
                    catch (Exception err)
                    {
                        log?.LogError(err, err.Message);
                    }

                    log?.LogError(exception, exception.Message);
                };

                return((BotFrameworkHttpAdapter)adapter);
            });
            services.AddSingleton <BotAdapter>(s => (BotAdapter)s.GetService <BotFrameworkHttpAdapter>());
            services.AddSingleton <IBotFrameworkHttpAdapter>(s => (IBotFrameworkHttpAdapter)s.GetService <BotFrameworkHttpAdapter>());


            // bot
            services.AddSingleton <IBot>((s) =>
            {
                // create bot using resourceexplorer and .dialog file
                var config = s.GetService <IConfiguration>();
                string rootDialogFolder = "LucyBot";
                string rootDialog       = "LucyBot.dialog";
                string rootPath         = GetDialogsFolder(config, context.ApplicationRootPath, rootDialogFolder);
                var resourceExplorer    = new ResourceExplorer()
                                          .AddFolder(rootPath);

                var bot = new Bot()
                          .UseResourceExplorer(resourceExplorer)
                          .UseLanguageGeneration();

                bot.InitialTurnState.Set <BotFrameworkClient>(s.GetService <SkillHttpClient>());
                bot.InitialTurnState.Set(s.GetService <SkillConversationIdFactoryBase>());
                bot.InitialTurnState.Set <BotAdapter>(s.GetService <BotAdapter>());
                bot.InitialTurnState.Add(s.GetService <QueueStorage>());
                // bot.InitialTurnState.Add(s.GetService<ITranscriptStore>());

                bot.RootDialog            = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource(rootDialog));
                resourceExplorer.Changed += (sender, e) =>
                {
                    Console.WriteLine("Resources changed, reloading...");
                    bot.RootDialog = resourceExplorer.LoadType <AdaptiveDialog>(resourceExplorer.GetResource(rootDialog));
                };
                return((IBot)bot);
            });
        }