public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument) { var answer = await QnaHelper.IsQnA(argument); if (!string.IsNullOrEmpty(answer)) { await context.PostAsync(answer); context.Done(true); } else { context.Done(false); } }
public async Task NoneIntent(IDialogContext context, LuisResult result) { LogHelper.LogLuisResult(result, context.Activity, typeof(WasCyclistInjuredDialog).Name); var qnaResult = await QnaHelper.IsQnA(result.Query); if (!string.IsNullOrEmpty(qnaResult)) { await context.PostAsync(qnaResult); context.Done(true); } context.Done(false); }
public async Task NoneIntent(IDialogContext context, LuisResult result) { LogHelper.LogLuisResult(result, context.Activity, typeof(InjuredDialog).Name); var qnaResult = await QnaHelper.IsQnA(result.Query); if (!string.IsNullOrEmpty(qnaResult)) { await context.PostAsync(qnaResult); context.Done(true); } else { context.Call(new BasicInputTextDialog("Hva heter den som ble skadet?"), InjuredPersonNameDialogResumeAfter); } }
public async Task NoneIntent(IDialogContext context, LuisResult result) { LogHelper.LogLuisResult(result, context.Activity, typeof(RootLuisDialog).Name); var utterance = result.Query; // If not, check against QnA, if there is a hit, use it, if no, use AIML response var qnaResult = await QnaHelper.IsQnA(utterance); if (!string.IsNullOrEmpty(qnaResult)) { await context.PostAsync(qnaResult); } else { await context.PostAsync(await AimlHelper.GetResponseNorwegian(utterance)); } }
/// <summary> /// Resolves bot commands in channel. /// </summary> /// <param name="message">A message in a conversation.</param> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> /// <returns>A task that represents the work queued to execute.</returns> public async Task ResolveBotCommandInTeamChatAsync( IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { string text; // Check if the incoming request is from SME for updating the ticket status. if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues && !string.IsNullOrEmpty(((JObject)message.Value)["ticketId"]?.ToString())) { text = ChangeStatus ?? throw new ArgumentNullException(nameof(ChangeStatus)); } else { text = message.Text?.ToLower()?.Trim() ?? string.Empty; } try { switch (text) { case Constants.TeamTour: this.logger.LogInformation("Sending team tour card"); var teamTourCards = TourCarousel.GetTeamTourCards(this.appBaseUri); await turnContext.SendActivityAsync(MessageFactory.Carousel(teamTourCards)).ConfigureAwait(false); break; case ChangeStatus: this.logger.LogInformation($"Card submit in channel {message.Value?.ToString()}"); await this.conversationService.SendAdaptiveCardInTeamChatAsync(message, turnContext, cancellationToken).ConfigureAwait(false); return; case Constants.DeleteCommand: this.logger.LogInformation($"Delete card submit in channel {message.Value?.ToString()}"); await QnaHelper.DeleteQnaPair(turnContext, this.qnaServiceProvider, this.activityStorageProvider, this.logger, cancellationToken).ConfigureAwait(false); break; case Constants.NoCommand: return; default: this.logger.LogInformation("Unrecognized input in channel"); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedTeamInputCard.GetCard())).ConfigureAwait(false); break; } } catch (Exception ex) { // Check if expert user is trying to delete the question and knowledge base has not published yet. if (((ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest) { var knowledgeBaseId = await this.configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false); var hasPublished = await this.qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false); // Check if knowledge base has not published yet. if (!hasPublished) { var activity = (Activity)turnContext.Activity; var activityValue = ((JObject)activity.Value).ToObject <AdaptiveSubmitActionData>(); await turnContext.SendActivityAsync(MessageFactory.Text(string.Format(CultureInfo.InvariantCulture, Strings.WaitMessage, activityValue?.OriginalQuestion))).ConfigureAwait(false); this.logger.LogError(ex, $"Error processing message: {ex.Message}", SeverityLevel.Error); return; } } // Throw the error at calling place, if there is any generic exception which is not caught by above conditon. throw; } }
/// <summary> /// Validate the adaptive card fields while editing the question and answer pair. /// </summary> /// <param name="postedQnaPairEntity">Qna pair entity contains submitted card data.</param> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <returns>Envelope for Task Module Response.</returns> public async Task<TaskModuleResponse> EditQnAPairAsync( AdaptiveSubmitActionData postedQnaPairEntity, ITurnContext<IInvokeActivity> turnContext) { // Check if fields contains Html tags or Question and answer empty then return response with error message. if (Validators.IsContainsHtml(postedQnaPairEntity) || Validators.IsQnaFieldsNullOrEmpty(postedQnaPairEntity)) { // Returns the card with validation errors on add QnA task module. return await TaskModuleActivity.GetTaskModuleResponseAsync(MessagingExtensionQnaCard.AddQuestionForm(Validators.HtmlAndQnaEmptyValidation(postedQnaPairEntity), this.appBaseUri)).ConfigureAwait(false); } if (Validators.IsRichCard(postedQnaPairEntity)) { if (Validators.IsImageUrlInvalid(postedQnaPairEntity) || Validators.IsRedirectionUrlInvalid(postedQnaPairEntity)) { // Show the error message on task module response for edit QnA pair, if user has entered invalid image or redirection url. return await TaskModuleActivity.GetTaskModuleResponseAsync(MessagingExtensionQnaCard.AddQuestionForm(Validators.ValidateImageAndRedirectionUrls(postedQnaPairEntity), this.appBaseUri)).ConfigureAwait(false); } string combinedDescription = QnaHelper.BuildCombinedDescriptionAsync(postedQnaPairEntity); postedQnaPairEntity.IsRichCard = true; if (postedQnaPairEntity.UpdatedQuestion?.ToUpperInvariant().Trim() == postedQnaPairEntity.OriginalQuestion?.ToUpperInvariant().Trim()) { // Save the QnA pair, return the response and closes the task module. await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, combinedDescription).Result).ConfigureAwait(false); return default; } else { var hasQuestionExist = await this.qnaServiceProvider.QuestionExistsInKbAsync(postedQnaPairEntity.UpdatedQuestion).ConfigureAwait(false); if (hasQuestionExist) { // Shows the error message on task module, if question already exist. return await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, combinedDescription).Result).ConfigureAwait(false); } else { // Save the QnA pair, return the response and closes the task module. await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, combinedDescription).Result).ConfigureAwait(false); return default; } } } else { // Normal card section. if (postedQnaPairEntity.UpdatedQuestion?.ToUpperInvariant().Trim() == postedQnaPairEntity.OriginalQuestion?.ToUpperInvariant().Trim()) { // Save the QnA pair, return the response and closes the task module. await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, postedQnaPairEntity.Description).Result).ConfigureAwait(false); return default; } else { var hasQuestionExist = await this.qnaServiceProvider.QuestionExistsInKbAsync(postedQnaPairEntity.UpdatedQuestion).ConfigureAwait(false); if (hasQuestionExist) { // Shows the error message on task module, if question already exist. return await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, postedQnaPairEntity.Description).Result).ConfigureAwait(false); } else { // Save the QnA pair, return the response and closes the task module. await TaskModuleActivity.GetTaskModuleResponseAsync(this.CardResponseAsync( turnContext, postedQnaPairEntity, postedQnaPairEntity.Description).Result).ConfigureAwait(false); return default; } } } }
protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result) { var telemetry = new TelemetryClient(); try { var qnaAnswer = result?.Answers?.First()?.Answer;//store qnamaker result text and store it in qnaAnswer variable var qnaQuestions = result?.Answers?.First()?.Questions; var questions = new QnaEntity(); var userinput = new QnaHelper(); var myquestion = result; Activity reply = ((Activity)context.Activity).CreateReply(); if (qnaAnswer != null & qnaQuestions != null && qnaQuestions.Any()) { if (message.Text.ToString().ToLower().Contains("help") || message.Text.ToString().ToLower().Contains("ayuda")) { await context.PostAsync(QNABotSettings.prompt1); Task.Delay(2000); await context.PostAsync(QNABotSettings.prompt2); return; } if (qnaQuestions.Any()) { questions = QnaHelper.QNAConnection(qnaQuestions?.FirstOrDefault()); context.UserData.SetValue("questions", questions); } else { context.UserData.RemoveValue("questions"); } var score = result.Answers.OrderByDescending(i => i.Score).FirstOrDefault()?.Score; if (score != null) { score = score * 100; //Threshold 1 Path! 100% - 80% if (score <= (Convert.ToInt32(QNABotSettings.threshold1[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold1[1])) { f.Flags1++; if (qnaAnswer.Contains("||")) { var msg = context.MakeMessage(); var answers = qnaAnswer.Split("||".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); msg.Attachments.Add(await GetCardsAttachments(answers)); await context.PostAsync(msg); if (qnaAnswer.Contains(ConfigurationManager.AppSettings["HRHeroTitle"])) { showHRHeroCardFlag = false; } else { showHRHeroCardFlag = true; } } else { await context.PostAsync(qnaAnswer); } } //Threshold 2 Path!79 % -40 % else if (score <= (Convert.ToInt32(QNABotSettings.threshold2[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold2[1]))//79-40 { f.Flags2++; context.UserData.SetValue("firstCheck", "true"); showHRHeroCardFlag = true; var msg = ((Activity)context.Activity).CreateReply(QNABotSettings.accurateanswer); //for carousel var herocardlst = new List <HeroCard>(); if (questions != null && questions.answers != null && questions.answers.Any()) { foreach (var item in questions.answers.Where(i => i.metadata != null)) { //string TitleCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(); //System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase() //this is causing issues with Spanish language herocardlst.Add(new HeroCard { Title = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase((from b in item.metadata where b.name == CarouselSettings.carouseltitle select b.value).FirstOrDefault()), Subtitle = (from b in item.metadata where b.name == CarouselSettings.carouselsummary select b.value).FirstOrDefault(), Buttons = new List <CardAction>() { new CardAction(ActionTypes.PostBack, QNABotSettings.seedetails, value: item.questions?.FirstOrDefault()) }, }); } } msg.SuggestedActions = new SuggestedActions { Actions = CardActionDialogue.GetNoneoftheAbove() }; msg.AttachmentLayout = AttachmentLayoutTypes.Carousel; herocardlst.ForEach(i => msg.Attachments.Add(i.ToAttachment())); msg.AttachmentLayout = AttachmentLayoutTypes.Carousel; await context.PostAsync(msg); context.Wait(Noneoftheabovedialog); } //Threshold 3 Path!39 % -0 % else if (score < (Convert.ToInt32(QNABotSettings.threshold3[0]) + 0.99) && score >= Convert.ToInt32(QNABotSettings.threshold3[1])) //39-0 { var defaultMessage = ((Activity)context.Activity).CreateReply(QNABotSettings.sorrynextrelease); //Created a new Activity object which will prompt the user with a question – “Did you find what you need?” when the dialog starts defaultMessage.SuggestedActions = new SuggestedActions { Actions = CardActionDialogue.GetContactInfoCard() }; await context.PostAsync(defaultMessage); context.Wait(ChoiceMenuLogic); } } } else { var defaultMessage = ((Activity)context.Activity).CreateReply(QNABotSettings.sorrynextrelease);//Created a new Activity object which will prompt the user with a question – “Did you find what you need?” when the dialog starts defaultMessage.SuggestedActions = new SuggestedActions { Actions = CardActionDialogue.GetContactInfoCard() }; context.UserData.SetValue("firstCheck", "false"); await context.PostAsync(defaultMessage); context.Wait(ChoiceMenuLogic); } } catch (Exception) { throw; //telemetry.TrackEvent("QnA Dialog RespondFromQnAMakerResultAsync Exception", new Dictionary<string, string> { { "Exception", SimpleJson.SimpleJson.SerializeObject(ex) } }); } }