public static AliceResponse Reply(this AliceRequest req, ResponseCard card, string text = "") { var response = req.Reply(text); response.Response.Card = card; return(response); }
public static AliceResponse Reply(this AliceRequest req, ResponseCard card) { var response = req.Reply(card.Title); response.Response.Card = card; return(response); }
// Handle message activity in 1:1 chat private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues) { this.telemetryClient.TrackTrace("Card submit in 1:1 chat"); await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken); return; } string text = (message.Text ?? string.Empty).Trim().ToLower(); switch (text) { case AskAnExpert: this.telemetryClient.TrackTrace("Sending user ask an expert card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard())); break; case ShareFeedback: this.telemetryClient.TrackTrace("Sending user feedback card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard())); break; case TakeATour: this.telemetryClient.TrackTrace("Sending user tour card"); var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri); await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards)); break; default: this.telemetryClient.TrackTrace("Sending input to QnAMaker"); var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken); if (queryResult != null) { string answer = this.ReplaceWildCard(message, turnContext, queryResult.Answer); await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], answer, queryResult.Source, text))); } else { await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))); } // Save conversation var saveConversations = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.SaveConversations); if (bool.Parse(saveConversations)) { var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken); ConversationEntity newConversation = await this.CreateConversationAsync(message, queryResult, userDetails); } break; } }
// Đã fix public ResponseCard GetResponseCard(string code) { ResponseCard responseCard; List <ResponeCardCreateTicketMonth> listCard; using (DB db = new DB(code)) { string sql = "select s.Identify, s.ID, case s.Using when 1 then N'Đang sử dụng' else N'Đã khóa' end as Using, p.Name, case ISNULL(t.ID, 'NULL') when 'NULL' then N'Chưa tạo' else N'Đã tạo' end as TicketMonth, (select top 1 amount from part where id = type) as Amount from SmartCard s left join (select t.ID from TicketMonth t, (select ID, MAX(RowID) as 'RowID' from TicketMonth group by ID) tt where t.RowID = tt.RowID and t.Status in (0,1,3)) t on s.ID = t.ID, Part p where s.Type = p.ID order by s.Identify"; listCard = db.Database.SqlQuery <ResponeCardCreateTicketMonth>(sql).ToList(); string sqlString = @"select * from ( (select count(identify) as total, (select top 1 name from part where id = type) as typename, type, (case using when 'True' then N'Dùng' else N'Không dùng' end) as isusing,using from smartcard group by [type], using ) union (select count(identify) as total, N'Tổng thẻ đang dùng' as typename, -1 as type, N'Dùng' as isusing, 1 as using from smartcard where using = 1) union (select count(identify) as total, N'Tổng thẻ không dùng' as typename, -2 as type, N'Không Dùng' as isusing, 1 as using from smartcard where using = 0) union (select count(identify) as total, N'Tổng thẻ' as typename, -3 as type, N'Dùng & Không' as isusing, 1 as using from smartcard )) a order by type asc"; var statistical = db.Database.SqlQuery <Statistical>(sqlString).ToList(); responseCard = new ResponseCard() { ListCard = listCard, Statistical = statistical }; } return(responseCard); }
private ResponseCard BuildResponseCard(int version) { ResponseCard responseCard = new ResponseCard() { contentType = "application/vnd.amazonaws.card.generic", version = version }; return(responseCard); }
// Handle message activity in 1:1 chat private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues) { this.telemetryClient.TrackTrace("Card submit in 1:1 chat"); await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken); return; } string text = (message.Text ?? string.Empty).Trim().ToLower(); if (text.Equals(Resource.ResourceManager.GetString("AskAnExpertDisplayText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase)) { this.telemetryClient.TrackTrace("Sending user ask an expert card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard())); } else if (text.Equals(Resource.ResourceManager.GetString("ShareFeedbackDisplayText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase)) { this.telemetryClient.TrackTrace("Sending user feedback card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard())); } else if (text.Equals(Resource.ResourceManager.GetString("TakeATourButtonText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase)) { this.telemetryClient.TrackTrace("Sending user tour card"); var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri); await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards)); } else { this.telemetryClient.TrackTrace("Sending input to QnAMaker"); var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken); if (queryResult != null) { this.telemetryClient.TrackTrace("Sending user QnAMaker card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], queryResult.Answer, text))); } else { var tileList = await this.MatchTagsWithMessageAsync(text); if (tileList != null) { this.telemetryClient.TrackTrace("Sending user tags card"); await turnContext.SendActivityAsync(SuggestedLinkCard.GetTagsCarouselCards(text, tileList, Resource.CustomMessage)); } else { this.telemetryClient.TrackTrace("Sending user with no matched tags result"); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text, Resource.NoMatchedTagsMessage))); } } } }
public void AddCollectedResponse(Response response) { ResponseCard cardInstance = ObjectPoolService.Instance.AcquireInstance <ResponseCard>(_responseCardPrefab.gameObject); cardInstance.transform.SetParent(_responseCardContainer, false); cardInstance.Response = response; _collectedResponses.Add(cardInstance); if (_highlightedResponseIndex == -1) { SetHighlightedResponse(0); } }
public int UseHighlightedResponse() { if (_highlightedResponseIndex == -1) { return(-20); } ResponseCard highlighted = _collectedResponses[_highlightedResponseIndex]; int usedPoints = highlighted.Response.Points; ClearCollectedResponses(); ClearAvailableResponses(); _isHighlightingResponses = false; // TODO: Stop glowing _fullGlowDelay = -1; return(usedPoints); }
private Card MapResponseToCard(ResponseCard response) { return(new Card { Id = response.Id, Amber = response.Amber, Armor = response.Armor, CardNumber = response.CardNumber, CardText = response.CardText, CardTitle = response.CardTitle, CardType = response.CardType, Expansion = response.Expansion, FlavorText = response.FlavorText, FrontImage = response.FrontImage, House = response.House, Rarity = response.Rarity, Power = response.Power, Traits = response.Traits, IsMaverick = response.IsMaverick }); }
public ResponseCard Statistical(string code) { string sqlString = @"select * from ( (select count(identify) as total, (select top 1 name from part where id = type) as typename, type, (case using when 'True' then N'Dùng' else N'Không dùng' end) as isusing,using from smartcard group by [type], using ) union (select count(identify) as total, N'Tổng thẻ đang dùng' as typename, -1 as type, N'Dùng' as isusing, 1 as using from smartcard where using = 1) union (select count(identify) as total, N'Tổng thẻ không dùng' as typename, -2 as type, N'Không Dùng' as isusing, 1 as using from smartcard where using = 0) union (select count(identify) as total, N'Tổng thẻ' as typename, -3 as type, N'Dùng & Không' as isusing, 1 as using from smartcard )) a order by type asc"; ResponseCard reponsestatistical; using (DB db = new DB(code)) { var statistical = db.Database.SqlQuery <Statistical>(sqlString).ToList(); reponsestatistical = new ResponseCard { ListCard = null, Statistical = statistical }; } return(reponsestatistical); }
/// <summary> /// Get the reply to a question asked by end user. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="message">Text message.</param> /// <returns>A task that represents the work queued to execute.</returns> private async Task GetQuestionAnswerReplyAsync( ITurnContext <IMessageActivity> turnContext, IMessageActivity message) { string text = message.Text?.ToLower()?.Trim() ?? string.Empty; try { var queryResult = new QnASearchResultList(); ResponseCardPayload payload = new ResponseCardPayload(); if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null)) { payload = ((JObject)message.Value).ToObject <ResponseCardPayload>(); } queryResult = await this.qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false); if (queryResult.Answers.First().Id != -1) { var answerData = queryResult.Answers.First(); AnswerModel answerModel = new AnswerModel(); if (Validators.IsValidJSON(answerData.Answer)) { answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer); } if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl)) { await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData))).ConfigureAwait(false); } else { await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, this.appBaseUri, payload))).ConfigureAwait(false); } } else { await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); } } catch (Exception ex) { // Check if knowledge base is empty and has not published yet when end user is asking a question to bot. 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) { this.logger.LogError(ex, "Error while fetching the qna pair: knowledge base may be empty or it has not published yet."); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); return; } } // Throw the error at calling place, if there is any generic exception which is not caught. throw; } }
/// <summary> /// Get the reply to a question asked by end user. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="message">Text message.</param> /// <returns>A task that represents the work queued to execute.</returns> public async Task GetReplyToQnAAsync( ITurnContext<IMessageActivity> turnContext, IMessageActivity message) { string text = message.Text?.ToLower()?.Trim() ?? string.Empty; try { var queryResult = new QnASearchResultList(); ResponseCardPayload payload = new ResponseCardPayload(); if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null)) { payload = ((JObject)message.Value).ToObject<ResponseCardPayload>(); } queryResult = await this.qnaServiceProvider.GenerateAnswerAsync(question: text, isTestKnowledgeBase: false, payload.PreviousQuestions?.Last().Id.ToString(), payload.PreviousQuestions?.Last().Questions.First()).ConfigureAwait(false); bool answerFound = false; foreach (QnASearchResult answerData in queryResult.Answers) { bool isContextOnly = answerData.Context?.IsContextOnly ?? false; if (answerData.Id != -1 && ((!isContextOnly && payload.PreviousQuestions == null) || (isContextOnly && payload.PreviousQuestions != null))) { // This is the expected answer await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, this.appBaseUri, payload))).ConfigureAwait(false); answerFound = true; break; } } if (!answerFound) { await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); } } catch (Exception ex) { // Check if knowledge base is empty and has not published yet when end user is asking a question to bot. if (((ErrorResponseException)ex).Response.StatusCode == System.Net.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) { this.logger.LogError(ex, "Error while fetching the qna pair: knowledge base may be empty or it has not published yet."); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); return; } } // Throw the error at calling place, if there is any generic exception which is not caught. throw; } }
// Handle message activity in 1:1 chat private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues) { this.telemetryClient.TrackTrace("Card submit in 1:1 chat"); await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken); return; } string text = (message.Text ?? string.Empty).Trim().ToLower(); this.telemetryClient.TrackTrace($"Se ha enviado esta solicitud: {text}"); switch (text) { case AskAnExpert: this.telemetryClient.TrackTrace("Sending user ask an expert card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard())); break; case ShareFeedback: this.telemetryClient.TrackTrace("Sending user feedback card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard())); break; case TakeATour: this.telemetryClient.TrackTrace("Sending user tour card"); var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri); await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards)); break; case WelcomeMsg: this.telemetryClient.TrackTrace("The user as required the Welcome screen"); var welcomeText = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.WelcomeMessageText); var userWelcomeCardAttachment = WelcomeCard.GetCard(welcomeText); var userWelcomeCardAttachment2 = WelcomeCardPreguntas.GetCard(Resource.WelcomeTeamCardContent); await turnContext.SendActivityAsync(MessageFactory.Attachment(userWelcomeCardAttachment)); await turnContext.SendActivityAsync(MessageFactory.Attachment(userWelcomeCardAttachment2)); break; default: this.telemetryClient.TrackTrace("Sending input to QnAMaker"); var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken); if (queryResult != null) { this.telemetryClient.TrackTrace("Sending user QnAMaker card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], queryResult.Answer, text))); } else { var tileList = await this.MatchTagsWithMessageAsync(text); if (tileList != null) { this.telemetryClient.TrackTrace("Sending user tags card"); await turnContext.SendActivityAsync(SuggestedLinkCard.GetTagsCarouselCards(text, tileList, Resource.CustomMessage)); } else { this.telemetryClient.TrackTrace("Sending user with no matched tags result"); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text, Resource.NoMatchedTagsMessage))); } } break; } }
protected override OutputModel <QuizSlotType> ProcessIntent() { string fulfillmentState = null; string dialogActionType = Constants.DIALOG_ACTION_TYPE_ELICIT; string intentName = InputModel.CurrentIntent.Name; var slots = InputModel.CurrentIntent.Slots; string slotToElicit = InputModel.CurrentIntent.Slots.GetSlotToElicit(); string responseMessage = String.Empty; string quizOrder = slots.QuizOrder == null ? String.Empty : slots.QuizOrder.ToLower(); string quizProgression = slots.QuizProgression == null ? String.Empty : slots.QuizProgression.ToLower(); ResponseCard responseCard = null; if (slotToElicit == nameof(QuizSlotType.DeckName)) { responseMessage = "What is the name of the flash card deck you'd like to be quizzed on?"; var allDecks = Dal.GetAllDecks(InputModel.UserID); if (allDecks != null && allDecks.Any()) { responseMessage = String.Format("{0} {1}", responseMessage, DeckUtilitites.CreateDeckInformationMessage(allDecks)); } } else if (slotToElicit == nameof(QuizSlotType.QuizOrder)) { var allDecks = Dal.GetAllDecks(InputModel.UserID); Deck quizDeck = allDecks?.FirstOrDefault(deck => deck.DeckName == slots.DeckName); if (allDecks != null && quizDeck != null) { responseMessage = "Would you liked to be quizzed in an in order or random fashion?"; responseCard = BuildOrderResponseCard(1); quizDeck.Cards = quizDeck.GetNonDeletedCards(); quizDeck.ResetDeck(); Dal.UpdateDeck(quizDeck); } else { responseMessage = "You don't have a deck with that name!"; } } else if (slotToElicit == nameof(QuizSlotType.QuizProgression)) { Card currentCard = null; bool deleteCurrent = false; bool quizOver = false; var deck = Dal.GetDeck(InputModel.UserID, slots.DeckName); if (!deck.Cards.Any()) { responseMessage = "The deck you selected does not contain any cards!"; } //If quiz hasn't started, set random property and call GetNextCard, always. //Otherwise, use the value of the QuizProgressionSlot else if (!deck.IsQuizStarted) { deck.IsQuizRandom = quizOrder.Equals(Constants.QuizOrder.Random.ToString().ToLower()); currentCard = deck.GetNextCard(); } else { if (quizProgression == Constants.QuizProgression.Next.ToString().ToLower()) { currentCard = deck.GetNextCard(); } else if (quizProgression == Constants.QuizProgression.Previous.ToString().ToLower()) { currentCard = deck.GetPreviousCard(); } else if (quizProgression == Constants.QuizProgression.Skip.ToString().ToLower()) { currentCard = deck.SkipCurrentCardAndGetNext(); } else if (quizProgression == Constants.QuizProgression.Delete.ToString().ToLower()) { currentCard = deck.GetCurrentCard(); deleteCurrent = true; } else if (quizProgression == Constants.QuizProgression.Stop.ToString().ToLower()) { quizOver = true; } } if (currentCard == null) { quizOver = true; } else if (deleteCurrent) { currentCard.IsDeleted = true; currentCard = deck.GetNextCard(); } if (currentCard != null) { slots.QuizProgression = null; slotToElicit = slots.GetSlotToElicit(); var quizCardStatus = currentCard.GetCardStatus(); //responseMessage = String.Format("Here is the {0} of the card.", quizCardStatus.ToString().ToLower()); responseMessage = currentCard.GetCardDataBasedOnStatus(); responseCard = BuildProgressionResponseCard(2, currentCard.GetCardDataBasedOnStatus()); Dal.UpdateDeck(deck); } else { quizOver = true; } if (quizOver) { if (responseMessage == String.Empty) { responseMessage = "The quiz has ended!"; } slotToElicit = null; dialogActionType = Constants.DIALOG_ACTION_TYPE_CLOSE; fulfillmentState = Constants.FULLFILLMENT_STATE_FULFILLED; intentName = null; slots = null; } } var outputModel = new OutputModel <QuizSlotType>(); outputModel.dialogAction.fulfillmentState = fulfillmentState; outputModel.dialogAction.type = dialogActionType; outputModel.dialogAction.slots = slots; outputModel.dialogAction.message.content = responseMessage; outputModel.dialogAction.message.contentType = Constants.RESPONSE_CONTENT_TYPE; outputModel.dialogAction.slotToElicit = slotToElicit; outputModel.dialogAction.intentName = intentName; outputModel.dialogAction.responseCard = responseCard; return(outputModel); }
/// <summary> /// Get the reply to a question asked by end user. /// </summary> /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param> /// <param name="message">Text message.</param> /// <returns>A task that represents the work queued to execute.</returns> private async Task GetQuestionAnswerReplyAsync( ITurnContext turnContext, IMessageActivity message) { string text = message.Text?.ToLower()?.Trim() ?? string.Empty; try { var queryResult = new QnASearchResultList(); ResponseCardPayload payload = new ResponseCardPayload(); if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null)) { payload = ((JObject)message.Value).ToObject <ResponseCardPayload>(); } queryResult = await _qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false); if (queryResult.Answers.First().Id != -1) { var answerData = queryResult.Answers.First(); payload.QnaPairId = answerData.Id ?? -1; AnswerModel answerModel = new AnswerModel(); if (Validators.IsValidJSON(answerData.Answer)) { answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer); } if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl)) { await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData, payload.QnaPairId))).ConfigureAwait(false); } else { await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, _appBaseUri, payload))).ConfigureAwait(false); } _telemetryClient.TrackEvent( FaqPlusPlusBot.EVENT_ANSWERED_QUESTION_SINGLE, new Dictionary <string, string> { { "QuestionId", payload.QnaPairId.ToString() }, { "QuestionAnswered", queryResult.Answers[0].Questions[0] }, { "QuestionAsked", text }, { "UserName", turnContext.Activity.From.Name }, { "UserAadId", turnContext.Activity.From?.AadObjectId ?? "" }, { "Product", _options.ProductName }, }); } else { await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); } } catch (Exception ex) { // Check if knowledge base is empty and has not published yet when end user is asking a question to bot. if (((Azure.CognitiveServices.Knowledge.QnAMaker.Models.ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest) { var knowledgeBaseId = await _configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false); var hasPublished = await _qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false); // Check if knowledge base has not published yet. if (!hasPublished) { this._telemetryClient.TrackException(ex, new Dictionary <string, string> { { "message", "Error while fetching the qna pair: knowledge base may be empty or it has not published yet." }, }); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false); return; } } // Throw the error at calling place, if there is any generic exception which is not caught. throw; } }
// Handle message activity in 1:1 chat private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues) { this.telemetryClient.TrackTrace("Card submit in 1:1 chat"); await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken); return; } string text = (message.Text ?? string.Empty).Trim().ToLower(); switch (text) { case AskAnExpert: this.telemetryClient.TrackTrace("Mandando tarjeta pregunta a un experto al usuario"); await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard())); break; case ShareFeedback: this.telemetryClient.TrackTrace("Sending user feedback card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard())); break; case TakeATour: this.telemetryClient.TrackTrace("Sending user tour card"); var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri); await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards)); break; default: this.telemetryClient.TrackTrace("Sending input to QnAMaker"); var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken); if (queryResult != null) { this.telemetryClient.TrackTrace("Sending user QnAMaker card"); await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], queryResult.Answer, text))); } else { var tileList = await this.MatchTagsWithMessageAsync(text); if (tileList != null) { this.telemetryClient.TrackTrace("Sending user tags card"); await turnContext.SendActivityAsync(SuggestedLinkCard.GetTagsCarouselCards(text, tileList, Resource.CustomMessage)); } else { this.telemetryClient.TrackTrace("Sending user with no matched tags result"); await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text, Resource.NoMatchedTagsMessage))); } } break; } }
/// <summary> /// Method that gets fired when a message comes in. /// </summary> /// <param name="turnContext">The current turn.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>Returns a unit of execution.</returns> protected override async Task OnMessageActivityAsync( ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (turnContext is null) { throw new ArgumentNullException(nameof(turnContext)); } if (turnContext.Activity.Text == "Take a tour") { this.telemetryClient.TrackTrace($"Called command: {turnContext.Activity.Text}"); await this.calcChatBot.SendTourCarouselCard(turnContext, cancellationToken).ConfigureAwait(false); } else { var incomingTextArray = turnContext.Activity.Text.Split(' '); var command = incomingTextArray[0]; var commandInputList = incomingTextArray[1]; Attachment responseAttachment = null; switch (command) { case "sum": case "add": var sum = this.arithmetic.CalculateSum(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithIntResult(sum, command); break; case "difference": case "minus": var diff = this.arithmetic.CalculateDifference(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithIntResult(diff, command); break; case "multiplication": case "product": var product = this.arithmetic.CalculateProduct(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithIntResult(product, command); break; case "division": case "quotient": var quotient = this.arithmetic.CalculateQuotient(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(quotient, command); break; case "mean": case "average": var mean = this.statistics.CalculateMean(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(mean, command); break; case "median": case "middle of the list": var median = this.statistics.CalculateMedian(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(median, command); break; case "range": var range = this.statistics.CalculateRange(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(range, command); break; case "variance": var variance = this.statistics.CalculateVariance(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(variance, command); break; case "mode": var modeList = this.statistics.CalculateMode(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithIntArrayResult(modeList, command); break; case "standard deviation": var stdDev = this.statistics.CalculateStandardDeviation(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(stdDev, command); break; case "geometric mean": var geometricMean = this.statistics.CalculateGeometricMean(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDecimalResult(geometricMean, command); break; case "quadratic roots": var quadRoots = this.geometrics.CalculateQuadraticRoots(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithStringResult(quadRoots, command); break; case "discriminant": var discriminant = this.geometrics.CalculateDiscriminant(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithIntResult(discriminant, command); break; case "midpoint": var midpoint = this.geometrics.CalculateMidpoint(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithStringResult(midpoint, command); break; case "distance": var distance = this.geometrics.CalculateDistance(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithDoubleResult(distance, command); break; case "pythagorean triple": var pythagoreanTriple = this.geometrics.CalculatePythagoreanTriple(commandInputList, turnContext, cancellationToken); responseAttachment = ResponseCard.GetCardWithStringResult(pythagoreanTriple, command); break; default: await turnContext.SendActivityAsync(MessageFactory.Text(Resources.CannotPickUpCommandText), cancellationToken).ConfigureAwait(false); break; } await turnContext.SendActivityAsync(MessageFactory.Attachment(responseAttachment), cancellationToken).ConfigureAwait(false); } }