/// <summary> /// Initializes a new instance of the <see cref="AdaptiveCardsHelpBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public AdaptiveCardsHelpBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory) { _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); Dialogs.Add(new DesignCardDialog()); }
/// <summary> /// Initializes a new instance of the <see cref="BasicBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); }
/// <summary> /// Initializes a new instance of the <see cref="BasicBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory) { _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); _passwordresetStateAccessor = _userState.CreateProperty <PasswordResetState>(nameof(PasswordResetState)); _ticketstatusStateAccessor = _userState.CreateProperty <TicketStatusState>(nameof(TicketStatusState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); Dialogs.Add(new PasswordResetDialog(_passwordresetStateAccessor, loggerFactory)); Dialogs.Add(new TicketStatusDialog(_ticketstatusStateAccessor, loggerFactory)); }
/// <summary> /// Initializes a new instance of the <see cref="BasicBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory) { _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); _prologEngine = new PrologEngine(persistentCommandHistory: false); _prologEngine.Consult("db.pl"); _prologBookService = new PrologBookService(_prologEngine); }
/// <summary> /// Initializes a new instance of the <see cref="BasicBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory) { _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _qnaStateAccessor = _userState.CreateProperty <QnABotState>(nameof(QnABotState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } laLigaBL = new LaLigaBL(); luisServiceV3 = new LuisServiceV3(); qnAServiceHelper = new QnAServiceHelper(); Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); }
/// <summary> /// Initializes a new instance of the <see cref="BasicBot"/> class. /// </summary> /// <param name="botServices">Bot services.</param> /// <param name="accessors">Bot State Accessors.</param> public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory, IConfiguration configuration) { _configuration = configuration; // Initialize our QnA Service _qnaService = new QnAService(_configuration); // Initialize required services and other info _services = services ?? throw new ArgumentNullException(nameof(services)); _userState = userState ?? throw new ArgumentNullException(nameof(userState)); _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState)); _dialogStateAccessor = _conversationState.CreateProperty <DialogState>(nameof(DialogState)); // Verify LUIS configuration. if (!_services.LuisServices.ContainsKey(LuisConfiguration)) { throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`."); } Dialogs = new DialogSet(_dialogStateAccessor); Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory)); }
/// <summary> /// Initialize the bot's references to external services. /// For example, Application Insights and QnaMaker services /// are created here. These external services are configured /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file). /// </summary> /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param> /// <returns>A <see cref="BotConfiguration"/> representing client objects to access external services the bot uses.</returns> /// <seealso cref="BotConfiguration"/> /// <seealso cref="QnAMaker"/> /// <seealso cref="TelemetryClient"/> private static BotServices InitBotServices(BotConfiguration config) { TelemetryClient telemetryClient = null; var qnaServices = new Dictionary <string, QnAMaker>(); foreach (var service in config.Services) { switch (service.Type) { case ServiceTypes.QnA: { // Create a QnA Maker that is initialized and suitable for passing // into the IBot-derived class (QnABot). // In this case, we're creating a custom class (wrapping the original // QnAMaker client) that logs the results of QnA Maker into Application // Insights for future anaysis. var qna = (QnAMakerService)service; if (qna == null) { throw new InvalidOperationException("The QnA service is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(qna.KbId)) { throw new InvalidOperationException("The QnA KnowledgeBaseId ('kbId') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(qna.EndpointKey)) { throw new InvalidOperationException("The QnA EndpointKey ('endpointKey') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(qna.Hostname)) { throw new InvalidOperationException("The QnA Host ('hostname') is required to run this sample. Please update your '.bot' file."); } var qnaEndpoint = new QnAMakerEndpoint() { KnowledgeBaseId = qna.KbId, EndpointKey = qna.EndpointKey, Host = qna.Hostname, }; var qnaMaker = new MyAppInsightsQnAMaker(qnaEndpoint, null, logUserName: false, logOriginalMessage: false); qnaServices.Add(qna.Name, qnaMaker); break; } case ServiceTypes.AppInsights: { var appInsights = (AppInsightsService)service; if (appInsights == null) { throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey)) { throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample. Please update your '.bot' file."); } var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey); telemetryClient = new TelemetryClient(telemetryConfig); telemetryClient.InstrumentationKey = appInsights.InstrumentationKey; break; } } } var connectedServices = new BotServices(telemetryClient, qnaServices); return(connectedServices); }
/** * Constructor. * * @param {BotConfiguration} bot configuration * @param {ConversationState} conversationState * @param {StatePropertyAccessor} accessor for user profile property * @param {StatePropertyAccessor} accessor for on turn property * @param {StatePropertyAccessor} accessor for reservation property */ public WhoAreYouDialog( BotServices botServices, ConversationState conversationState, IStatePropertyAccessor <UserProfile> userProfileAccessor, IStatePropertyAccessor <OnTurnProperty> onTurnAccessor, IStatePropertyAccessor <ReservationProperty> reservationAccessor) : base(Name) { if (botServices == null) { throw new ArgumentNullException(nameof(botServices)); } if (conversationState == null) { throw new ArgumentNullException(nameof(conversationState)); } UserProfileAccessor = userProfileAccessor ?? throw new ArgumentNullException(nameof(userProfileAccessor)); // keep accessors for the steps to consume OnTurnAccessor = onTurnAccessor ?? throw new ArgumentNullException(nameof(onTurnAccessor)); // add dialogs var waterfallSteps = new WaterfallStep[] { AskForUserNameAsync, GreetUserAsync, }; AddDialog(new WaterfallDialog( dialogStart, waterfallSteps)); var turnCounterAccessor = conversationState.CreateProperty <CounterState>("turnCounter"); // Add get user name prompt. AddDialog(new GetUserNamePrompt( askUserNamePrompt, botServices, userProfileAccessor, conversationState, onTurnAccessor, turnCounterAccessor, async(promptContext, cancellationToken) => { var userProfile = await userProfileAccessor.GetAsync(promptContext.Context).ConfigureAwait(false); var counter = await turnCounterAccessor.GetAsync(promptContext.Context).ConfigureAwait(false); // Prompt validator // Examine if we have a user name and validate it. if (userProfile != null && userProfile.UserName != null) { // We can only accept user names that up to two words. if (userProfile.UserName.Split(" ").Length > 2) { await promptContext.Context.SendActivityAsync("Sorry, I can only accept two words for a name."); await promptContext.Context.SendActivityAsync("You can always say 'My name is <your name>' to introduce yourself to me."); await userProfileAccessor.SetAsync(promptContext.Context, new UserProfile("Human")).ConfigureAwait(false); // set updated turn counter await turnCounterAccessor.SetAsync(promptContext.Context, counter).ConfigureAwait(false); return(false); } else { // capitalize user name userProfile.UserName = char.ToUpper(userProfile.UserName[0]) + userProfile.UserName.Substring(1); // Create user profile and set it to state. await userProfileAccessor.SetAsync(promptContext.Context, userProfile).ConfigureAwait(false); return(true); } } return(false); })); // this dialog is interruptable, add interruptionDispatcherDialog AddDialog(new InterruptionDispatcher(onTurnAccessor, conversationState, userProfileAccessor, botServices)); // when user decides to abandon this dialog, we need to confirm user action - add confirmation prompt AddDialog(new ConfirmPrompt(confirmCancelPrompt)); }
public QnADialog(BotServices services, IStatePropertyAccessor <UserProfile> userProfileAccessor, string dialogId = null) : base(Name) { _services = services ?? throw new ArgumentNullException(nameof(services)); _userProfileAccessor = userProfileAccessor ?? throw new ArgumentNullException(nameof(userProfileAccessor)); }
/// <summary> /// Initialize the bot's references to external services. /// /// For example, Application Insights and LUIS services /// are created here. These external services are configured /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file). /// </summary> /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param> /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns> /// <seealso cref="BotConfiguration"/> /// <seealso cref="LuisRecognizer"/> private static BotServices InitBotServices(BotConfiguration config) { TelemetryClient telemetryClient = null; var luisServices = new Dictionary<string, LuisRecognizer>(); foreach (var service in config.Services) { switch (service.Type) { case ServiceTypes.Luis: { var luis = (LuisService)service; if (luis == null) { throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AppId)) { throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AuthoringKey)) { throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.SubscriptionKey)) { throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.Region)) { throw new InvalidOperationException("The Region ('region') is required to run this sample. Please update your '.bot' file."); } var app = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint()); var recognizer = new MyAppInsightLuisRecognizer(app); luisServices.Add(LuisBot.LuisKey, recognizer); break; } case ServiceTypes.AppInsights: { var appInsights = (AppInsightsService)service; if (appInsights == null) { throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey)) { throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample. Please update your '.bot' file."); } var telemetryConfig = new TelemetryConfiguration(appInsights.InstrumentationKey); telemetryClient = new TelemetryClient(telemetryConfig) { InstrumentationKey = appInsights.InstrumentationKey, }; break; } } } var connectedServices = new BotServices(telemetryClient, luisServices); return connectedServices; }
/// <summary> /// Initialize the bot's references to external services. /// /// For example, Application Insights and LUIS services /// are created here. These external services are configured /// using the <see cref="BotConfiguration"/> class (based on the contents of your ".bot" file). /// </summary> /// <param name="config">The <see cref="BotConfiguration"/> object based on your ".bot" file.</param> /// <returns>A <see cref="BotServices"/> representing client objects to access external services the bot uses.</returns> /// <seealso cref="BotConfiguration"/> /// <seealso cref="LuisRecognizer"/> private static BotServices InitBotServices(BotConfiguration config) { var luisServices = new Dictionary <string, TelemetryLuisRecognizer>(); foreach (var service in config.Services) { switch (service.Type) { case ServiceTypes.Luis: { var luis = (LuisService)service; if (luis == null) { throw new InvalidOperationException("The Luis service is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AppId)) { throw new InvalidOperationException("The Luis Model Application Id ('appId') is required to run this sample. Please update your '.bot' file."); } if (string.IsNullOrWhiteSpace(luis.AuthoringKey)) { throw new InvalidOperationException("The Luis Authoring Key ('authoringKey') is required to run this sample. Please update your '.bot' file."); } // CAUTION: Authoring key is used in this example as it is appropriate for prototyping. // When implimenting for deployment/production, assign and use a subscription key instead of an authoring key. // if (string.IsNullOrWhiteSpace(luis.SubscriptionKey)) // { // throw new InvalidOperationException("The Subscription Key ('subscriptionKey') is required to run this sample. Please update your '.bot' file."); // } if (string.IsNullOrWhiteSpace(luis.Region)) { throw new InvalidOperationException("The Region ('region') is required to run this sample. Please update your '.bot' file."); } var app = new LuisApplication(luis.AppId, luis.AuthoringKey, luis.GetEndpoint()); var recognizer = new TelemetryLuisRecognizer(app); luisServices.Add(LuisBot.LuisKey, recognizer); break; } case ServiceTypes.AppInsights: { var appInsights = (AppInsightsService)service; if (appInsights == null) { throw new InvalidOperationException("The Application Insights is not configured correctly in your '.bot' file."); } if (string.IsNullOrWhiteSpace(appInsights.InstrumentationKey)) { throw new InvalidOperationException("The Application Insights Instrumentation Key ('instrumentationKey') is required to run this sample. Please update your '.bot' file."); } break; } } } var connectedServices = new BotServices(luisServices); return(connectedServices); }
/// <summary> /// Initializes a new instance of the <see cref="GreetingDialog"/> class. /// </summary> /// <param name="botServices">Connected services used in processing.</param> /// <param name="botState">The <see cref="UserState"/> for storing properties at user-scope.</param> /// <param name="botServices"></param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> that enables logging and tracing.</param> public BlockchainDialog(IStatePropertyAccessor <BlockchainState> userProfileStateAccessor, BotServices botServices, ILoggerFactory loggerFactory) : base(nameof(BlockchainDialog)) { _botServices = botServices; UserProfileAccessor = userProfileStateAccessor ?? throw new ArgumentNullException(nameof(userProfileStateAccessor)); // Add control flow dialogs WaterfallStep[] waterfallSteps = new WaterfallStep[] { DisplayMarketplaceStateStepAsync, }; AddDialog(new WaterfallDialog(ProfileDialog, waterfallSteps)); }
// Initializes a new instance of the "WelcomeUserBot" class. public WelcomeUserBot(UserState userState, IMailService mailService, AppSettings appSetting, StateService stateService, BotServices botServices)//, IAppServices appServices { _userState = userState; this.mailService = mailService; //_appServices = appServices; _appSetting = appSetting; _stateService = stateService ?? throw new System.ArgumentNullException(nameof(stateService)); _botServices = botServices ?? throw new System.ArgumentNullException(nameof(stateService)); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> specifies the contract for a collection of service descriptors.</param> /// <seealso cref="!:https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection"/> /// <seealso cref="!:https://docs.microsoft.com/en-us/azure/bot-service/bot-service-manage-channels?view=azure-bot-service-4.0"/> public void ConfigureServices(IServiceCollection services) { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\nlp-with-luis.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. ({botConfig})")); // Initialize Bot Connected Services clients. var connectedServices = new BotServices(botConfig); services.AddSingleton(sp => connectedServices); services.AddSingleton(sp => botConfig); services.AddBot <LuisBot>(options => { // 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 logger for the application to use. ILogger logger = _loggerFactory.CreateLogger <LuisBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync($"Sorry, it looks like something went wrong : {exception}."); }; // 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); }); }
public ChitChatDialog(BotServices botServices, IStatePropertyAccessor <UserProfile> userProfileAccessor) : base(botServices, userProfileAccessor, nameof(ChitChatDialog)) { _botServices = botServices ?? throw new ArgumentNullException(nameof(botServices)); _userProfileAccessor = userProfileAccessor; }
public BookTableDialog(BotServices services, IStatePropertyAccessor <ReservationProperty> reservationsAccessor, IStatePropertyAccessor <OnTurnProperty> onTurnAccessor, IStatePropertyAccessor <UserProfile> userProfileAccessor, ConversationState conversationState) : base(Name) { _services = services ?? throw new ArgumentNullException(nameof(services)); ReservationsAccessor = reservationsAccessor ?? throw new ArgumentNullException(nameof(reservationsAccessor)); OnTurnAccessor = onTurnAccessor ?? throw new ArgumentNullException(nameof(onTurnAccessor)); UserProfileAccessor = userProfileAccessor ?? throw new ArgumentNullException(nameof(userProfileAccessor)); // create accessors for child dialogs GetLocDialogAccessor = conversationState.CreateProperty <DialogState>(GetLocationDialogState); ConfirmDialogAccessor = conversationState.CreateProperty <DialogState>(ConfirmDialogState); // add dialogs // Water fall book table dialog var waterfallSteps = new WaterfallStep[] { GetAllRequiredPropertiesAsync, BookTableAsync, }; AddDialog(new WaterfallDialog(BookTableWaterfall, waterfallSteps)); // Get location, date, time & party size prompt. AddDialog(new GetLocationDateTimePartySizePrompt( GetLocationDateTimePartySizePrompt, services, reservationsAccessor, onTurnAccessor, userProfileAccessor, async(promptValidatorContext, cancellationToken) => { // Validation and prompting logic. // Get reservation property. var newReservation = await reservationsAccessor.GetAsync(promptValidatorContext.Context, () => new ReservationProperty()); // If we have a valid reservation, end this prompt. // Otherwise, get LG based on what's available in reservation property if (newReservation.HaveCompleteReservation()) { if (!newReservation.ReservationConfirmed) { if (newReservation.NeedsChange == true) { await promptValidatorContext.Context.SendActivityAsync("What would you like to change ?"); } else { // Greet user with name if we have the user profile set. var userProfile = await userProfileAccessor.GetAsync(promptValidatorContext.Context, () => null); if (userProfile != null && !string.IsNullOrWhiteSpace(userProfile.UserName)) { await promptValidatorContext.Context.SendActivityAsync($"Alright {userProfile.UserName} I have a table for {newReservation.ConfirmationReadOut()}"); } else { await promptValidatorContext.Context.SendActivityAsync($"Ok. I have a table for {newReservation.ConfirmationReadOut()}"); } await promptValidatorContext.Context.SendActivityAsync(MessageFactory.SuggestedActions(new List <string> { "Yes", "No" }, "Should I go ahead and book the table?")); } } else { // Have complete reservation. return(true); } } else { // Readout what has been understood already. var groundedPropertiesReadout = newReservation.GetGroundedPropertiesReadOut(); if (string.IsNullOrWhiteSpace(groundedPropertiesReadout)) { await promptValidatorContext.Context.SendActivityAsync(groundedPropertiesReadout); } } // ask user for missing information await promptValidatorContext.Context.SendActivityAsync(newReservation.GetMissingPropertyReadOut()); return(false); })); // This dialog is interruptable. So add interruptionDispatcherDialog. AddDialog(new InterruptionDispatcher(onTurnAccessor, conversationState, userProfileAccessor, services)); // When user decides to abandon this dialog, we need to confirm user action. Add confirmation prompt. AddDialog(new ConfirmPrompt(ConfirmCancelPrompt)); }
public void ConfigureServices(IServiceCollection services) { var botFileSecret = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", botFileSecret); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException("The .bot config file could not be loaded.")); // Initializes your bot service clients and adds a singleton that your Bot can access through dependency injection. var connectedServices = new BotServices(botConfig); services.AddSingleton(sp => connectedServices); // Memory Storage 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/ // Un-comment the following lines to use Azure Blob Storage // Storage configuration name or ID from the .bot file. // const string storageConfigurationId = "2"; // 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 = "botstate"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create and add conversation state. var conversationState = new ConversationState(dataStore); var userState = new UserState(dataStore); services.AddSingleton(dataStore); services.AddSingleton(userState); services.AddSingleton(conversationState); services.AddSingleton(new BotStateSet(userState, conversationState)); services.AddBot <BasicBot>(options => { // Load the connected services from .bot file. 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}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Catches any errors that occur during a conversation turn and logs them to currently // configured ILogger. ILogger logger = _loggerFactory.CreateLogger <BasicBot>(); options.OnTurnError = async(context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // 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); // Content Moderation Middleware (analyzes incoming messages for inappropriate content including PII, profanity, etc.) var moderatorService = botConfig.Services.FirstOrDefault(s => s.Name == ContentModeratorMiddleware.ServiceName); if (moderatorService != null) { var moderator = moderatorService as GenericService; var moderatorKey = moderator.Configuration["subscriptionKey"]; var moderatorRegion = moderator.Configuration["region"]; var moderatorMiddleware = new ContentModeratorMiddleware(moderatorKey, moderatorRegion); options.Middleware.Add(moderatorMiddleware); } // Typing Middleware (automatically shows typing when the bot is responding/working) var typingMiddleware = new ShowTypingMiddleware(); options.Middleware.Add(typingMiddleware); options.Middleware.Add(new AutoSaveStateMiddleware(userState, conversationState)); }); }