/// <summary> /// Initializes a new instance of the <see cref="SupportBotService"/> class. /// </summary> /// <param name="services">A <see cref="BotServices"/> configured from the ".bot" file.</param> /// <param name="accessor">Show QnA Result Accessor.</param> public SupportBotService(BotServices services, ShowQnAResultAccessor accessor) { _services = services ?? throw new System.ArgumentNullException(nameof(services)); if (!_services.QnAServices.ContainsKey(QnAMakerKey)) { throw new System.ArgumentException($"Invalid configuration. Please check your '.bot' file for a QnA service named '{QnAMakerKey}'."); } if (Constants.EnableLuis && !_services.LuisServices.ContainsKey(LuisKey)) { throw new System.ArgumentException($"Invalid configuration. Please check your '.bot' file for a Luis service named '{LuisKey}'."); } _accessors = accessor ?? throw new System.ArgumentNullException(nameof(accessor)); dialogs = new DialogSet(_accessors.ConversationDialogState); var choicePrompt = new ChoicePrompt("choicePrompt"); choicePrompt.Style = ListStyle.SuggestedAction; choicePrompt.DefaultLocale = Culture.English; dialogs.Add(choicePrompt); dialogs.Add(new ChoicePrompt("cardPrompt")); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param> /// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/> public void ConfigureServices(IServiceCollection services) { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; Constants.PersonalityChatKey = Configuration.GetSection("personalityChatKey")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey); // Add Application Insights services.AddBotApplicationInsights(botConfig); // Initialize Bot Connected Services clients. var connectedServices = InitBotServices(botConfig); services.AddSingleton(sp => connectedServices); services.AddSingleton(sp => botConfig); services.AddBot <SupportBotService>(options => { services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. ({botConfig})")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == environment).FirstOrDefault(); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Creates a telemetryClient for OnTurnError handler var spTelemetry = services.BuildServiceProvider(); var telemetryClient = spTelemetry.GetService <IBotTelemetryClient>(); // Add TelemetryLoggerMiddleware (logs activity messages into Application Insights) var appInsightsLogger = new TelemetryLoggerMiddleware(telemetryClient, logUserName: true, logOriginalMessage: true); options.Middleware.Add(appInsightsLogger); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <SupportBotService>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(context, exception) => { telemetryClient.TrackException(exception); await context.SendActivityAsync("I don't have an answer for that. Try typing MENU to go back to the main menu"); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // //Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create Conversation State object. // The Conversation State object is where we persist anything at the conversation-scope. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); }); // Acessors created here are passed into the IBot - derived class on every turn. services.AddSingleton <ShowQnAResultAccessor>(sp => { var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } var conversationState = options.State.OfType <ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } // Create the custom QnAMaker accessor. var accessors = new ShowQnAResultAccessor(conversationState) { QnAResultState = conversationState.CreateProperty <ShowQnAResultState>(ShowQnAResultAccessor.QnAResultStateName), ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"), }; return(accessors); }); }