Beispiel #1
0
        protected override async Task OnStartAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // if the OnStart call doesn't have the locale info in the activity, we don't take it as a startConversation call
            //     if (!string.IsNullOrWhiteSpace(dc.Context.Activity.Locale))
            //    {
            //        await StartConversation(dc);

//                _conversationStarted = true;
//         }

            var onboardingState = await _onboardingState.GetAsync(dc.Context, () => new OnboardingState());

            var view = new MainResponses();
            await view.ReplyWith(dc.Context, MainResponses.ResponseIds.Intro);

            var allowAnonymousAccess = false;

            if (_services.SkillConfigurations.TryGetValue("calendarSkill", out ISkillConfiguration skill))
            {
                if (skill.Properties.TryGetValue("allowAnonymousAccess", out object allowObject))
                {
                    bool.TryParse(allowObject as string, out allowAnonymousAccess);
                }
            }

            if (string.IsNullOrEmpty(onboardingState.Name) && !allowAnonymousAccess)
            {
                // This is the first time the user is interacting with the bot, so gather onboarding information.
                await dc.BeginDialogAsync(nameof(OnboardingDialog));
            }
        }
Beispiel #2
0
        protected virtual async Task <InterruptionAction> OnHelp(DialogContext dc)
        {
            var view = new MainResponses();
            await view.ReplyWith(dc.Context, MainResponses.ResponseIds.Help);

            // Signal the conversation was interrupted and should immediately continue
            return(InterruptionAction.MessageSentToUser);
        }
Beispiel #3
0
        protected override async Task OnStartAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var onboardingState = await _onboardingState.GetAsync(dc.Context, () => new OnboardingState());

            var view = new MainResponses();
            await view.ReplyWith(dc.Context, MainResponses.Intro);

            if (string.IsNullOrEmpty(onboardingState.Name))
            {
                // This is the first time the user is interacting with the bot, so gather onboarding information.
                await dc.BeginDialogAsync(nameof(OnboardingDialog));
            }
        }
Beispiel #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? throw new Exception("Please configure your bot file path in appsettings.json."), botFileSecret);

            // Use Application Insights
            services.AddBotApplicationInsights(botConfig);

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var languageModels            = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var skills                    = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            List <SkillEvent> skillEvents = null;
            var skillEventsConfig         = Configuration.GetSection(SkillEventsConfigName);

            if (skillEventsConfig != null)
            {
                skillEvents = skillEventsConfig.Get <List <SkillEvent> >();
            }

            var connectedServices = new BotServices(botConfig, languageModels, skills, skillEvents);

            services.AddSingleton(sp => connectedServices);

            var defaultLocale = Configuration.GetSection("defaultLocale").Get <string>();

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

            services.AddSingleton(dataStore);
            services.AddSingleton(userState);
            services.AddSingleton(conversationState);
            services.AddSingleton(proactiveState);
            services.AddSingleton(new BotStateSet(userState, conversationState));

            var environment = _isProduction ? "production" : "development";
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment);

            if (!(service is EndpointService endpointService))
            {
                throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
            }

            services.AddSingleton(endpointService);

            // Add the bot with options
            services.AddBot <VirtualAssistant>(options =>
            {
                // Load the connected services from .bot file.
                options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                // Telemetry Middleware (logs activity messages in Application Insights)
                var sp = services.BuildServiceProvider();
                var telemetryClient   = sp.GetService <IBotTelemetryClient>();
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                options.Middleware.Add(appInsightsLogger);

                // Catches any errors that occur during a conversation turn and logs them to AppInsights.
                options.OnTurnError = async(context, exception) =>
                {
                    CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                    var responseBuilder          = new MainResponses();
                    await responseBuilder.ReplyWith(context, MainResponses.ResponseIds.Error);
                    await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Virtual Assistant Error: {exception.Message} | {exception.StackTrace}"));
                    telemetryClient.TrackExceptionEx(exception, context.Activity);
                };

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                options.Middleware.Add(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                options.Middleware.Add(new ShowTypingMiddleware());
                options.Middleware.Add(new SetLocaleMiddleware(defaultLocale ?? "en-us"));
                options.Middleware.Add(new EventDebuggerMiddleware());
                options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState));
                options.Middleware.Add(new ProactiveStateMiddleware(proactiveState));

                //// Translator is an optional component for scenarios when an Assistant needs to work beyond native language support
                // var translatorKey = Configuration.GetValue<string>("translatorKey");
                // if (!string.IsNullOrEmpty(translatorKey))
                // {
                //     options.Middleware.Add(new TranslationMiddleware(new string[] { "en", "fr", "it", "de", "es" }, translatorKey, false));
                // }
                // else
                // {
                //     throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting.");
                // }
            });
        }
Beispiel #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

            // add background task queue
            services.AddSingleton <IBackgroundTaskQueue, BackgroundTaskQueue>();
            services.AddHostedService <QueuedHostedService>();

            // Load the connected services from .bot file.
            var botFilePath   = Configuration.GetSection("botFilePath")?.Value;
            var botFileSecret = Configuration.GetSection("botFileSecret")?.Value;
            var botConfig     = BotConfiguration.Load(botFilePath ?? throw new Exception("Please configure your bot file path in appsettings.json."), botFileSecret);

            // Use Application Insights
            services.AddBotApplicationInsights(botConfig);

            // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection.
            var languageModels            = Configuration.GetSection("languageModels").Get <Dictionary <string, Dictionary <string, string> > >();
            var skills                    = Configuration.GetSection("skills").Get <List <SkillDefinition> >();
            List <SkillEvent> skillEvents = null;
            var skillEventsConfig         = Configuration.GetSection(SkillEventsConfigName);

            if (skillEventsConfig != null)
            {
                skillEvents = skillEventsConfig.Get <List <SkillEvent> >();
            }

            var connectedServices = new BotServices(botConfig, languageModels, skills, skillEvents);

            services.AddSingleton(sp => connectedServices);

            var imageAssetLocation = Configuration.GetSection("imageAssetLocation").Get <string>();

            services.AddSingleton(sp => imageAssetLocation);

            var defaultLocale      = Configuration.GetSection("configuration").Get <string>();
            var supportedLanguages = languageModels.Select(l => l.Key).ToArray();
            var responseManager    = new ResponseManager(
                supportedLanguages,
                new MainDialogResponses());

            // Register bot responses for all supported languages.
            services.AddSingleton(sp => responseManager);

            // Initialize Bot State
            var cosmosDbService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.CosmosDB) ?? throw new Exception("Please configure your CosmosDb service in your .bot file.");
            var cosmosDb        = cosmosDbService as CosmosDbService;
            var cosmosOptions   = new CosmosDbStorageOptions()
            {
                CosmosDBEndpoint = new Uri(cosmosDb.Endpoint),
                AuthKey          = cosmosDb.Key,
                CollectionId     = cosmosDb.Collection,
                DatabaseId       = cosmosDb.Database,
            };
            var dataStore         = new CosmosDbStorage(cosmosOptions);
            var userState         = new UserState(dataStore);
            var conversationState = new ConversationState(dataStore);
            var proactiveState    = new ProactiveState(dataStore);

            services.AddSingleton(dataStore);
            services.AddSingleton(userState);
            services.AddSingleton(conversationState);
            services.AddSingleton(proactiveState);
            services.AddSingleton(new BotStateSet(userState, conversationState));

            var environment = _isProduction ? "production" : "development";
            var service     = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.Endpoint && s.Name == environment);

            if (!(service is EndpointService endpointService))
            {
                throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
            }

            services.AddSingleton(endpointService);

            services.AddSingleton <IBot, VirtualAssistant>();

            // HttpContext required for path resolution
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Add the http adapter to enable MVC style bot API
            services.AddSingleton <IBotFrameworkHttpAdapter>((sp) =>
            {
                var credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);

                var telemetryClient         = sp.GetService <IBotTelemetryClient>();
                var botFrameworkHttpAdapter = new BotFrameworkHttpAdapter(credentialProvider)
                {
                    OnTurnError = async(context, exception) =>
                    {
                        CultureInfo.CurrentUICulture = new CultureInfo(context.Activity.Locale);
                        var responseBuilder          = new MainResponses();
                        await responseBuilder.ReplyWith(context, MainResponses.ResponseIds.Error);
                        await context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Virtual Assistant Error: {exception.Message} | {exception.StackTrace}"));
                        telemetryClient.TrackExceptionEx(exception, context.Activity);
                    }
                };

                // Telemetry Middleware (logs activity messages in Application Insights)
                var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true);
                botFrameworkHttpAdapter.Use(appInsightsLogger);

                // Transcript Middleware (saves conversation history in a standard format)
                var storageService       = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.BlobStorage) ?? throw new Exception("Please configure your Azure Storage service in your .bot file.");
                var blobStorage          = storageService as BlobStorageService;
                var transcriptStore      = new AzureBlobTranscriptStore(blobStorage.ConnectionString, blobStorage.Container);
                var transcriptMiddleware = new TranscriptLoggerMiddleware(transcriptStore);
                botFrameworkHttpAdapter.Use(transcriptMiddleware);

                // Typing Middleware (automatically shows typing when the bot is responding/working)
                botFrameworkHttpAdapter.Use(new ShowTypingMiddleware());
                botFrameworkHttpAdapter.Use(new SetLocaleMiddleware(defaultLocale ?? "en-us"));
                botFrameworkHttpAdapter.Use(new EventDebuggerMiddleware());
                botFrameworkHttpAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));
                botFrameworkHttpAdapter.Use(new ProactiveStateMiddleware(proactiveState));

                return(botFrameworkHttpAdapter);
            });
        }