public static IMessageActivity ShowFindArticleCards(ITurnContext context, LocaleTemplateManager localeTemplateEngineManager, dynamic data, bool isFindingFavorite = false) { var response = context.Activity.CreateReply(); var articles = data as List <NewsArticle>; if (articles.Any()) { Activity articleResponse = null; if (isFindingFavorite) { articleResponse = localeTemplateEngineManager.GenerateActivityForLocale(FavoriteTopicsResponses.ShowFavoriteTopics, new { Count = articles.Count, Article = articles[0] }); } else { articleResponse = localeTemplateEngineManager.GenerateActivityForLocale(FindArticlesResponses.ShowArticles, new { Count = articles.Count, Article = articles[0] }); } response.Text = articleResponse.Text; response.Speak = articleResponse.Speak; response.Attachments = new List <Attachment>(); response.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (var item in articles) { var card = new ThumbnailCard() { Title = item.Name, Subtitle = item.DatePublished, Text = item.Description, Images = item?.Image?.Thumbnail?.ContentUrl != null ? new List <CardImage>() { new CardImage(item.Image.Thumbnail.ContentUrl), } : null, Buttons = new List <CardAction>() { new CardAction(ActionTypes.OpenUrl, title: localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.ReadMore).Text, value: item.Url) }, }.ToAttachment(); response.Attachments.Add(card); } } else { if (isFindingFavorite) { response = localeTemplateEngineManager.GenerateActivityForLocale(FavoriteTopicsResponses.NoFavoriteTopics); } else { response = localeTemplateEngineManager.GenerateActivityForLocale(FindArticlesResponses.NoArticles); } } return(response); }
public static IMessageActivity SendIntroCard(ITurnContext turnContext, LocaleTemplateManager localeTemplateEngineManager) { var response = turnContext.Activity.CreateReply(); response.Attachments = new List <Attachment>() { new HeroCard() { Title = localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.INTRO_TITLE).Text, Text = localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.INTRO_TEXT).Text }.ToAttachment() }; return(response); }
private async Task <DialogTurnResult> GetAndSendActionResultAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var state = await StateAccessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken); var musicSetting = new MusicSetting() { Name = state.ControlActionName }; if (musicSetting.Name == ControlActions.AdjustVolume) { musicSetting.Value = state.VolumeDirection; } if (musicSetting.Name != null) { await SendControlSettingEventActivityAsync(stepContext, musicSetting, cancellationToken); } else { await stepContext.Context.SendActivityAsync(LocaleTemplateManager.GenerateActivityForLocale(MainResponses.NoResultstMessage), cancellationToken); } // End dialog return(await stepContext.EndDialogAsync(cancellationToken : cancellationToken)); }
public async Task <DialogTurnResult> ProcessSettingAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken = default(CancellationToken)) { var state = await StateAccessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken); if (state.ControlActionName == ControlActions.AdjustVolume && state.VolumeDirection == null) { var options = new PromptOptions() { Choices = new List <Choice>() { new Choice() { Value = LocaleTemplateManager.GenerateActivityForLocale(ControlSettingsResponses.VolumeUpSelection).Text }, new Choice() { Value = LocaleTemplateManager.GenerateActivityForLocale(ControlSettingsResponses.VolumeDownSelection).Text }, new Choice() { Value = LocaleTemplateManager.GenerateActivityForLocale(ControlSettingsResponses.VolumeMuteSelection).Text } }, Prompt = LocaleTemplateManager.GenerateActivityForLocale(ControlSettingsResponses.VolumeDirectionSelection) }; return(await stepContext.PromptAsync(WaterfallDialogName.SettingValueSelectionPrompt, options, cancellationToken : cancellationToken)); } return(await stepContext.NextAsync(cancellationToken : cancellationToken)); }
protected override QnAMakerDialog TryCreateQnADialog(string knowledgebaseId, CognitiveModelSet cognitiveModels) { if (!cognitiveModels.QnAConfiguration.TryGetValue(knowledgebaseId, out QnAMakerEndpoint qnaEndpoint) || qnaEndpoint == null) { throw new Exception($"Could not find QnA Maker knowledge base configuration with id: {knowledgebaseId}."); } // QnAMaker dialog already present on the stack? if (Dialogs.Find(knowledgebaseId) == null) { // Return a QnAMaker dialog using our Http Mock return(new QnAMakerDialog( knowledgeBaseId: qnaEndpoint.KnowledgeBaseId, endpointKey: qnaEndpoint.EndpointKey, hostName: qnaEndpoint.Host, noAnswer: _templateManager.GenerateActivityForLocale("UnsupportedMessage"), httpClient: new HttpClient(_mockHttpHandler)) { Id = knowledgebaseId }); } else { return(null); } }
public DefaultAdapter( BotSettings settings, ICredentialProvider credentialProvider, IChannelProvider channelProvider, LocaleTemplateManager templateFile, ConversationState conversationState, TelemetryInitializerMiddleware telemetryMiddleware, IBotTelemetryClient telemetryClient, ProactiveState proactiveState) : base(credentialProvider, channelProvider) { OnTurnError = async(turnContext, exception) => { await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Exception Message: {exception.Message}, Stack: {exception.StackTrace}")); await turnContext.SendActivityAsync(templateFile.GenerateActivityForLocale("ErrorMessage", settings.DefaultLocale)); telemetryClient.TrackException(exception); }; Use(telemetryMiddleware); // Uncomment the following line for local development without Azure Storage // Use(new TranscriptLoggerMiddleware(new MemoryTranscriptStore())); Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container))); Use(new ShowTypingMiddleware()); Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us")); Use(new EventDebuggerMiddleware()); Use(new SetSpeakMiddleware()); // SAMPLE: Proactive notifications Use(new ProactiveStateMiddleware(proactiveState)); }
public static Activity GenerateActivity(this LocaleTemplateManager manager, string templateId, IEnumerable <Card> cards, IDictionary <string, object> tokens = null, string attachmentLayout = "carousel") { if (string.IsNullOrEmpty(templateId)) { templateId = CardsOnly; } var input = new { Data = tokens, Cards = cards.Select((card) => { return(Convert(card)); }).ToArray(), Layout = attachmentLayout, }; try { return(manager.GenerateActivityForLocale(templateId, input)); } catch (Exception ex) { var result = Activity.CreateMessageActivity(); result.Text = ex.Message; return((Activity)result); } }
public static Activity GenerateActivity(this LocaleTemplateManager manager, string templateId, Card card, IDictionary <string, object> tokens = null, string containerName = null, IEnumerable <Card> containerItems = null) { throw new Exception("1. create *Containee.json which only keeps containee's body;2. in the container, write ${if(Cards==null,'',join(foreach(Cards,Card,CreateStringNoContainer(Card.Name,Card.Data)),','))}"); if (string.IsNullOrEmpty(templateId)) { templateId = CardsOnly; } var input = new { Data = tokens, Cards = new CardExt[] { Convert(card, containerItems: containerItems) }, }; try { return(manager.GenerateActivityForLocale(templateId, input)); } catch (Exception ex) { var result = Activity.CreateMessageActivity(); result.Text = ex.Message; return((Activity)result); } }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { var userProfile = await _userProfileState.GetAsync(turnContext, () => new UserProfileState(), cancellationToken); if (string.IsNullOrEmpty(userProfile.Name)) { // Send new user intro card. await turnContext.SendActivityAsync(_templateManager.GenerateActivityForLocale("NewUserIntroCard", userProfile), cancellationToken); } else { // Send returning user intro card. await turnContext.SendActivityAsync(_templateManager.GenerateActivityForLocale("ReturningUserIntroCard", userProfile), cancellationToken); } await _dialog.RunAsync(turnContext, _dialogStateAccessor, cancellationToken); }
public void GetResponseWithLanguageGeneration_English() { var defaultCulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-us"); // Generate English response using LG with data dynamic data = new JObject(); data.Name = "Darren"; var response = localeTemplateEngineManager.GenerateActivityForLocale("HaveNameMessage", data); // Retrieve possible responses directly from the correct template to validate logic var possibleResponses = Templates.ParseFile(localeLgFiles["en"]).ExpandTemplate("HaveNameMessage", data); Assert.IsTrue(possibleResponses.Contains(response.Text)); CultureInfo.CurrentUICulture = defaultCulture; }
public static IMessageActivity SendHelpCard(ITurnContext turnContext, LocaleTemplateManager localeTemplateEngineManager) { var response = turnContext.Activity.CreateReply(); response.Attachments = new List <Attachment> { new HeroCard() { Title = localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.HELP_TITLE).Text, Text = localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.HELP_TEXT).Text, Buttons = new List <CardAction>() { new CardAction(type: ActionTypes.ImBack, title: "Test", value: "Hello"), new CardAction(type: ActionTypes.OpenUrl, title: "Learn More", value: "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0"), }, }.ToAttachment() }; return(response); }
public static Activity ShowTrendingCards(ITurnContext context, LocaleTemplateManager localeTemplateEngineManager, dynamic data) { var response = context.Activity.CreateReply(); var articles = data as List <NewsTopic>; if (articles.Any()) { var trendingResponse = localeTemplateEngineManager.GenerateActivityForLocale(FavoriteTopicsResponses.ShowFavoriteTopics, new { Count = articles.Count, Article = articles[0] }); response.Text = trendingResponse.Text; response.Speak = trendingResponse.Speak; response.Attachments = new List <Attachment>(); response.AttachmentLayout = AttachmentLayoutTypes.Carousel; foreach (var item in articles) { var card = new HeroCard() { Title = item.Name, Images = item?.Image?.Url != null ? new List <CardImage>() { new CardImage(item.Image.Url), } : null, Buttons = new List <CardAction>() { new CardAction(ActionTypes.OpenUrl, title: localeTemplateEngineManager.GenerateActivityForLocale(MainStrings.ReadMore).Text, value: item.WebSearchUrl) }, }.ToAttachment(); response.Attachments.Add(card); } } else { response = localeTemplateEngineManager.GenerateActivityForLocale(TrendingArticlesResponses.NoTrending); } return(response); }
// This method is called by any waterfall step that throws an exception to ensure consistency protected async Task HandleDialogExceptionsAsync(WaterfallStepContext sc, Exception ex, CancellationToken cancellationToken) { // send trace back to emulator var trace = new Activity(type: ActivityTypes.Trace, text: $"DialogException: {ex.Message}, StackTrace: {ex.StackTrace}"); await sc.Context.SendActivityAsync(trace, cancellationToken); // log exception TelemetryClient.TrackException(ex, new Dictionary <string, string> { { nameof(sc.ActiveDialog), sc.ActiveDialog?.Id } }); // send error message to bot user await sc.Context.SendActivityAsync(LocaleTemplateManager.GenerateActivityForLocale(SharedResponses.ErrorMessage), cancellationToken); }
public static Activity GenerateActivity(this LocaleTemplateManager manager, string templateId, Card card, object tokens = null, string containerName = null, IEnumerable <Card> containerItems = null) { var input = new { Data = tokens, Cards = new CardExt[] { Convert(card, containerItems: containerItems) }, }; try { return(manager.GenerateActivityForLocale(templateId, input)); } catch (Exception ex) { var result = Activity.CreateMessageActivity(); result.Text = ex.Message; return((Activity)result); } }
private async Task SendErrorMessageAsync(ITurnContext turnContext, Exception exception) { try { _telemetryClient.TrackException(exception); // Send a message to the user. await turnContext.SendActivityAsync(_templateEngine.GenerateActivityForLocale(RestaurantBookingSharedResponses.ErrorMessage)); // Send a trace activity, which will be displayed in the Bot Framework Emulator. // Note: we return the entire exception in the value property to help the developer; // this should not be done in production. await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError"); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught in SendErrorMessageAsync : {ex}"); } }
private async Task <DialogTurnResult> GetAndSendMusicResultAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var state = await StateAccessor.GetAsync(stepContext.Context, cancellationToken : cancellationToken); var status = false; // Get music api client IMusicService musicService = ServiceManager.InitMusicService(); // Extract query entity to search against Spotify for var searchQuery = state.Query; var genres = state.Genres; string searchItems = null; // Search music if given music info like artist/track/album/playlist or genres. Without info, we just get a recommendation album. if (!string.IsNullOrEmpty(searchQuery) || genres?.Count != 0) { searchItems = await musicService.SearchMusicAsync(searchQuery, genres); } else { searchItems = await musicService.GetNewAlbumReleasesAsync(); } if (!string.IsNullOrEmpty(searchItems)) { status = true; await SendOpenDefaultAppEventActivityAsync(stepContext, searchItems, cancellationToken); } else { await stepContext.Context.SendActivityAsync(LocaleTemplateManager.GenerateActivityForLocale(MainResponses.NoResultstMessage), cancellationToken); } // End dialog return(await stepContext.EndDialogAsync(new Models.ActionInfos.ActionResult() { ActionSuccess = status }, cancellationToken)); }
private async Task SendErrorMessageAsync(ITurnContext turnContext, Exception exception) { try { // Send a message to the user. CultureInfo.CurrentUICulture = new CultureInfo(turnContext.Activity.Locale ?? "en-us"); await turnContext.SendActivityAsync(_templateManager.GenerateActivityForLocale(MainStrings.ERROR)); await turnContext.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"News Skill Error: {exception.Message} | {exception.StackTrace}")); _telemetryClient.TrackException(exception); // Send a trace activity, which will be displayed in the Bot Framework Emulator. // Note: we return the entire exception in the value property to help the developer; // this should not be done in production. await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError"); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught in SendErrorMessageAsync : {ex}"); } }
// Runs on every turn of the conversation to check if the conversation should be interrupted. protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken) { DialogTurnResult interrupted = null; var activity = innerDc.Context.Activity; if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text)) { // Get connected LUIS result from turn state. var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralLuisResult); (var generalIntent, var generalScore) = generalResult.TopIntent(); if (generalScore > 0.5) { switch (generalIntent) { case GeneralLuis.Intent.Cancel: { await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("CancelledMessage"), cancellationToken); await innerDc.CancelAllDialogsAsync(cancellationToken); if (innerDc.Context.IsSkill()) { interrupted = await innerDc.EndDialogAsync(cancellationToken : cancellationToken); } else { interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken); } break; } case GeneralLuis.Intent.Help: { await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("HelpCard"), cancellationToken); await innerDc.RepromptDialogAsync(cancellationToken); interrupted = EndOfTurn; break; } case GeneralLuis.Intent.Logout: { // Log user out of all accounts. await LogUserOutAsync(innerDc, cancellationToken); await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("LogoutMessage"), cancellationToken); await innerDc.CancelAllDialogsAsync(cancellationToken); if (innerDc.Context.IsSkill()) { interrupted = await innerDc.EndDialogAsync(cancellationToken : cancellationToken); } else { interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken); } break; } } } } return(interrupted); }
public static string GetString(this LocaleTemplateManager manager, string templateId) { // Not use .Text in case text and speak are different return(manager.GenerateActivityForLocale(templateId).Text); }
public MainDialog( IServiceProvider serviceProvider, IBotTelemetryClient telemetryClient ) : base(nameof(MainDialog)) { _services = serviceProvider.GetService <BotServices>(); _settings = serviceProvider.GetService <BotSettings>(); _templateManager = serviceProvider.GetService <LocaleTemplateManager>(); _skillsConfig = serviceProvider.GetService <SkillsConfiguration>(); _feedbackOptions = serviceProvider.GetService <FeedbackOptions>(); TelemetryClient = telemetryClient; var userState = serviceProvider.GetService <UserState>(); _userProfileState = userState.CreateProperty <UserProfileState>(nameof(UserProfileState)); var conversationState = serviceProvider.GetService <ConversationState>(); _previousResponseAccessor = conversationState.CreateProperty <List <Activity> >(StateProperties.PreviousBotResponse); _feedbackAccessor = conversationState.CreateProperty <FeedbackRecord>(nameof(FeedbackRecord)); var steps = new List <WaterfallStep>() { OnboardingStepAsync, IntroStepAsync, RouteStepAsync, }; if (_feedbackOptions.FeedbackEnabled) { steps.Add(RequestFeedback); steps.Add(RequestFeedbackComment); steps.Add(ProcessFeedback); AddDialog(new TextPrompt(DialogIds.FeedbackPrompt)); AddDialog(new TextPrompt(DialogIds.FeedbackCommentPrompt)); } steps.Add(FinalStepAsync); AddDialog(new WaterfallDialog(nameof(MainDialog), steps)); AddDialog(new TextPrompt(DialogIds.NextActionPrompt)); InitialDialogId = nameof(MainDialog); // Register dialogs _onboardingDialog = serviceProvider.GetService <OnboardingDialog>(); _switchSkillDialog = serviceProvider.GetService <SwitchSkillDialog>(); AddDialog(_onboardingDialog); AddDialog(_switchSkillDialog); // Register a QnAMakerDialog for each registered knowledgebase and ensure localised responses are provided. var localizedServices = _services.GetCognitiveModels(); foreach (var knowledgebase in localizedServices.QnAConfiguration) { var qnaDialog = new QnAMakerDialog( knowledgeBaseId: knowledgebase.Value.KnowledgeBaseId, endpointKey: knowledgebase.Value.EndpointKey, hostName: knowledgebase.Value.Host, noAnswer: _templateManager.GenerateActivityForLocale("UnsupportedMessage"), activeLearningCardTitle: _templateManager.GenerateActivityForLocale("QnaMakerAdaptiveLearningCardTitle").Text, cardNoMatchText: _templateManager.GenerateActivityForLocale("QnaMakerNoMatchText").Text) { Id = knowledgebase.Key }; AddDialog(qnaDialog); } // Register skill dialogs var skillDialogs = serviceProvider.GetServices <SkillDialog>(); foreach (var dialog in skillDialogs) { AddDialog(dialog); } }
public static string GetString(this LocaleTemplateManager manager, string templateId) { return(manager.GenerateActivityForLocale(templateId + ".Text").Text); }
// Runs on every turn of the conversation to check if the conversation should be interrupted. protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken) { DialogTurnResult interrupted = null; var activity = innerDc.Context.Activity; if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text)) { // Get connected LUIS result from turn state. var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResult); (var generalIntent, var generalScore) = generalResult.TopIntent(); if (generalScore > 0.5) { switch (generalIntent) { case General.Intent.Cancel: { await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(EmailSharedResponses.CancellingMessage), cancellationToken); await innerDc.CancelAllDialogsAsync(cancellationToken); if (innerDc.Context.IsSkill()) { var state = await _stateAccessor.GetAsync(innerDc.Context, () => new EmailSkillState(), cancellationToken : cancellationToken); interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult(false) : null, cancellationToken : cancellationToken); } else { interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken); } break; } case General.Intent.Help: { await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(EmailMainResponses.HelpMessage), cancellationToken); await innerDc.RepromptDialogAsync(cancellationToken); interrupted = EndOfTurn; break; } case General.Intent.Logout: { // Log user out of all accounts. await LogUserOutAsync(innerDc, cancellationToken); await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(EmailMainResponses.LogOut), cancellationToken); await innerDc.CancelAllDialogsAsync(cancellationToken); if (innerDc.Context.IsSkill()) { var state = await _stateAccessor.GetAsync(innerDc.Context, () => new EmailSkillState(), cancellationToken : cancellationToken); interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult(false) : null, cancellationToken : cancellationToken); } else { interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken); } break; } } } } return(interrupted); }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { await turnContext.SendActivityAsync(_templateManager.GenerateActivityForLocale(ToDoMainResponses.ToDoWelcomeMessage), cancellationToken); await _dialog.RunAsync(turnContext, _dialogStateAccessor, cancellationToken); }
protected override async Task OnMembersAddedAsync(IList <ChannelAccount> membersAdded, ITurnContext <IConversationUpdateActivity> turnContext, CancellationToken cancellationToken) { await turnContext.SendActivityAsync(_templateEngine.GenerateActivityForLocale("IntroMessage"), cancellationToken); await _dialog.RunAsync(turnContext, _dialogStateAccessor, cancellationToken); }
/// <summary> /// Creates a QnAMaker dialog for the correct locale if it's not already present on the dialog stack. /// Virtual method enables test mock scenarios. /// </summary> /// <param name="knowledgebaseId">Knowledgebase Identifier.</param> /// <param name="cognitiveModels">CognitiveModelSet configuration information.</param> /// <returns>QnAMakerDialog instance.</returns> protected virtual QnAMakerDialog TryCreateQnADialog(string knowledgebaseId, CognitiveModelSet cognitiveModels) { if (!cognitiveModels.QnAConfiguration.TryGetValue(knowledgebaseId, out QnAMakerEndpoint qnaEndpoint) || qnaEndpoint == null) { throw new Exception($"Could not find QnA Maker knowledge base configuration with id: {knowledgebaseId}."); } // QnAMaker dialog already present on the stack? if (Dialogs.Find(knowledgebaseId) == null) { return(new QnAMakerDialog( knowledgeBaseId: qnaEndpoint.KnowledgeBaseId, endpointKey: qnaEndpoint.EndpointKey, hostName: qnaEndpoint.Host, noAnswer: _templateManager.GenerateActivityForLocale("UnsupportedMessage"), activeLearningCardTitle: _templateManager.GenerateActivityForLocale("QnaMakerAdaptiveLearningCardTitle").Text, cardNoMatchText: _templateManager.GenerateActivityForLocale("QnaMakerNoMatchText").Text) { Id = knowledgebaseId }); } else { return(null); } }
private async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken) { var interrupted = false; var activity = innerDc.Context.Activity; var userProfile = await _userProfileState.GetAsync(innerDc.Context, () => new UserProfileState()); var dialog = innerDc.ActiveDialog?.Id != null?innerDc.FindDialog(innerDc.ActiveDialog?.Id) : null; if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text)) { // Check if the active dialog is a skill for conditional interruption. var isSkill = dialog is SkillDialog; // Get Dispatch LUIS result from turn state. var dispatchResult = innerDc.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult); (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent(); // Check if we need to switch skills. if (isSkill && IsSkillIntent(dispatchIntent) && dispatchIntent.ToString() != dialog.Id && dispatchScore > 0.9) { EnhancedBotFrameworkSkill identifiedSkill; if (_skillsConfig.Skills.TryGetValue(dispatchIntent.ToString(), out identifiedSkill)) { var prompt = _templateManager.GenerateActivityForLocale("SkillSwitchPrompt", new { Skill = identifiedSkill.Name }); await innerDc.BeginDialogAsync(_switchSkillDialog.Id, new SwitchSkillDialogOptions(prompt, identifiedSkill)); interrupted = true; } else { throw new ArgumentException($"{dispatchIntent.ToString()} is not in the skills configuration"); } } if (dispatchIntent == DispatchLuis.Intent.l_General) { // Get connected LUIS result from turn state. var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralResult); (var generalIntent, var generalScore) = generalResult.TopIntent(); if (generalScore > 0.5) { switch (generalIntent) { case GeneralLuis.Intent.Cancel: { await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("CancelledMessage", userProfile)); await innerDc.CancelAllDialogsAsync(); await innerDc.BeginDialogAsync(InitialDialogId); interrupted = true; break; } case GeneralLuis.Intent.Escalate: { await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("EscalateMessage", userProfile)); await innerDc.RepromptDialogAsync(); interrupted = true; break; } case GeneralLuis.Intent.Help: { if (!isSkill) { // If current dialog is a skill, allow it to handle its own help intent. await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("HelpCard", userProfile)); await innerDc.RepromptDialogAsync(); interrupted = true; } break; } case GeneralLuis.Intent.Logout: { // Log user out of all accounts. await LogUserOut(innerDc); await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("LogoutMessage", userProfile)); await innerDc.CancelAllDialogsAsync(); await innerDc.BeginDialogAsync(InitialDialogId); interrupted = true; break; } case GeneralLuis.Intent.Repeat: { // Sends the activities since the last user message again. var previousResponse = await _previousResponseAccessor.GetAsync(innerDc.Context, () => new List <Activity>()); foreach (var response in previousResponse) { // Reset id of original activity so it can be processed by the channel. response.Id = string.Empty; await innerDc.Context.SendActivityAsync(response); } interrupted = true; break; } case GeneralLuis.Intent.StartOver: { await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("StartOverMessage", userProfile)); // Cancel all dialogs on the stack. await innerDc.CancelAllDialogsAsync(); await innerDc.BeginDialogAsync(InitialDialogId); interrupted = true; break; } case GeneralLuis.Intent.Stop: { // Use this intent to send an event to your device that can turn off the microphone in speech scenarios. break; } } } } } return(interrupted); }