public async Task Legal(IDialogContext context, LuisResult result) { context.SendTypingAcitivity(); LegalDocuments.RetrieveLegalDocuments(); context.SendTypingAcitivity(); var itms = LegalDocuments.Legaldocuments; itms = itms.Where(cc => cc.OnPreservationHold).ToList(); var res = "There are " + itms.Count() + " documents are on preservation hold"; var attch = ResultCard.GetThumbnailCard( "Legal Cases", res, "Click below link to go the Sharepoint portal for Legal Cases", new CardImage(url: "http://technoinfotech.com/images/legal-hold-technoarchive.png"), new CardAction(ActionTypes.OpenUrl, "Learn More", value: "https://m365x844754.sharepoint.com/sites/ChrevronBot/Shared%20Documents/Forms/AllItems.aspx")); IMessageActivity msg = context.MakeMessage(); msg.Attachments.Add(attch); await context.PostAsync(msg); msg = context.MakeMessage(); ResultCard card = new ResultCard(); card.RenderLegalDocuments(msg, itms); await context.PostAsync(msg); context.Wait(this.MessageReceived); }
private void CustomSearch(IDialogContext context, string text) { var subscriptionKey = System.Configuration.ConfigurationManager.AppSettings["BingCustomSearchKey"]; var customConfigId = System.Configuration.ConfigurationManager.AppSettings["BingConfigId"]; var searchTerm = text; var url = "https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?" + "q=" + searchTerm + "&customconfig=" + customConfigId; var client = new HttpClient(); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); var httpResponseMessage = client.GetAsync(url).Result; var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result; BingCustomSearchResponse response = JsonConvert.DeserializeObject <BingCustomSearchResponse>(responseContent); ResultCard resultCard = new ResultCard(); IMessageActivity msg = context.MakeMessage(); msg.SuggestedActions = ResultCard.GetSuggestedActions(); resultCard.CustomCard(msg, response.webPages); context.PostAsync(msg); }
private async Task DoYouWantMoreQna(IDialogContext context, IAwaitable <IMessageActivity> result) { var response = await result; if (response.Text.Equals(issueResolved)) { await this.IssueResolved(context); return; } await context.SendTypingAcitivity(); ResultCard resultCard = new ResultCard(); await resultCard.PostAsyncWithConvertToOptionsCard(context, "Do you have answers to all the questions displayed earlier", new string[] { "Start Interactive Session" }); context.Wait(StartInteractiveQuestion); //ResultCard resultCard = new ResultCard(); //await resultCard.PostAsyncWithConvertToOptionsCard(context, "We have suggested possible options", issueSolvedCardAction); //context.Wait(this.Completed); }
public ActionResult DeleteConfirmed(int id) { ResultCard resultCard = db.ResultCards.Find(id); db.ResultCards.Remove(resultCard); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task InitialUserQuery(IDialogContext context, IAwaitable <IMessageActivity> argument) { var response = await argument; await context.SendTypingAcitivity(); context.PrivateConversationData.SetValue(StateConstants.Topic, response.Text); var rk = LuisFetcher.GetAnswers(response.Text.ToString()).Result; await context.SendTypingAcitivity(); var selectedIntent = topOnCallTopics.FirstOrDefault(cc => cc.Equals(rk.TopScoringIntent.IntentIntent) && rk.TopScoringIntent.Score > Constants.MaxLUIScore); context.PrivateConversationData.SetValue(StateConstants.IntentQuery, response.Text); if (selectedIntent != null) { context.PrivateConversationData.SetValue(StateConstants.Intent, selectedIntent); var re = context.MakeMessage(); re.Text = "BElow are some of the related topics"; var qnAResults = QnAMaker.QnAFetchter.GetAnswers("#System get #" + selectedIntent + " bot synonyms").Result; await context.SendTypingAcitivity(); ResultCard resultCard = new ResultCard(); resultCard.CustomQnACard(re, qnAResults); await context.PostAsync(re); context.Wait(HandleBotSynonyms); } else if (selectedIntent == null && rk.TopScoringIntent.IntentIntent.Equals("greeting") && rk.TopScoringIntent.Score > Constants.MaxLUIScore) { PersonalityChatOptions personalityChatOptions = new PersonalityChatOptions(string.Empty, PersonalityChatPersona.Professional); PersonalityChatService personalityChatService = new PersonalityChatService(personalityChatOptions); var PersonalityChatResults = Task.FromResult <PersonalityChatResults>(await personalityChatService.QueryServiceAsync(rk.Query)); string botOutput = PersonalityChatResults?.Result.ScenarioList?.FirstOrDefault()?.Responses?.FirstOrDefault() ?? ""; if (!string.IsNullOrEmpty(botOutput)) { await context.PostAsync(botOutput); var reply = context.MakeMessage(); reply.Attachments = new List <Attachment>(); reply.Attachments.Add(ResultCard.ShowGreetingCard()); var k = QnAMaker.QnAFetchter.GetAnswers("Get Bot Options").Result; await context.PostAsync(reply); } else { await context.SendTypingAcitivity(); await this.HandleBotSynonyms(context, argument); } } else { response.Text = others; await this.HandleBotSynonyms(context, argument); } }
public async Task InitializeFord(IDialogContext context, IAwaitable <IMessageActivity> argument) { var response = await argument; var rk = LuisFetcher.GetAnswers(response.Text.ToString()).Result; await context.SendTypingAcitivity(); switch (rk.TopScoringIntent.IntentIntent) { case "FordSiteInfo": var answer = QnAMaker.QnAFetchter.GetAnswers("whats this site?"). Result.Answers[0].AnswerAnswer; MediaUrl mediaUrl = new MediaUrl("https://marczak.io/images/botseries-rich-cards/CreatingBot.mp4"); await context.PostAsync(answer); //var k = ResultCard.GetVideoCard("Welcome to Leadership Learning Site", "", "Ford HR ", mediaUrl); //var reply = context.MakeMessage(); //reply.Attachments = new List<Attachment>(); //reply.Attachments.Add(k); //await context.PostAsync(reply); context.Done("competed"); break; case "FordCurrentAffair": answer = QnAMaker.QnAFetchter.GetAnswers("Whats cooking?"). Result.Answers[0].AnswerAnswer; await context.PostAsync(answer); ResultCard result = new ResultCard(); var reply = context.MakeMessage(); reply.Text = "Would you like to learn more?"; reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "yes", "no" }); await context.PostAsync(reply); context.Wait(handleSiteInfo); break; case "FordModels": ResultCard resultCard = new ResultCard(); reply = context.MakeMessage(); resultCard.ConvertToOptionsCard(reply, new[] { "Critical Thinking", "Design Thinking", "System Thinking" }, new[] { "http://syedamrullahravepoc.azurewebsites.net/content/criticalthinking.png", "http://syedamrullahravepoc.azurewebsites.net/content/designthinking.png", "http://syedamrullahravepoc.azurewebsites.net/content/systemthinking.png" }); await context.PostAsync(reply); context.Wait(FordModelSelection); break; case "FordTraining": result = new ResultCard(); reply = context.MakeMessage(); reply.Text = "If training was to be made available what would be your preference be:"; reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "Webex Training", "Class Room" }); await context.PostAsync(reply); context.Wait(handleLocationTraining); break; default: break; } }
private Activity HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels // Note: Add introduction here: IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity; if (iConversationUpdated != null) { ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl)); foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty <ChannelAccount>()) { // if the bot is added, then if (member.Id == iConversationUpdated.Recipient.Id) { var reply = ((Activity)iConversationUpdated).CreateReply(); reply.Attachments = new List <Attachment>(); reply.Attachments.Add(ResultCard.ShowGreetingCard()); var k = QnAMaker.QnAFetchter.GetAnswers("Get Bot Options").Result; //reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(k.Answers[0].AnswerAnswer.Split(',')); connector.Conversations.ReplyToActivityAsync(reply); } } } } } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { } return(null); }
public async Task None(IDialogContext context, LuisResult result) { context.SendTypingAcitivity(); string message = $"Sorry, I did not understand {result.Query}. Here are few options."; IMessageActivity msg = context.MakeMessage(); msg.Text = message; msg.SuggestedActions = ResultCard.GetSuggestedActions(); await context.PostAsync(msg); }
public async Task Help(IDialogContext context, LuisResult result) { context.SendTypingAcitivity(); var feedback = ((Activity)context.Activity).CreateReply("Hi! Try asking me questions on Litigation cases, Legal or Internal investigation or select below options"); feedback.SuggestedActions = ResultCard.GetSuggestedActions(); await context.PostAsync(feedback); context.Wait(this.MessageReceived); }
public ActionResult Edit([Bind(Include = "ID,Name,REG_NO,Father_Name,Semester,University,Department,Program,SGPA,CGPA")] ResultCard resultCard) { if (ModelState.IsValid) { db.Entry(resultCard).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(resultCard)); }
private async Task DisplayFeedback(IDialogContext context) { ResultCard resultCard = new ResultCard(); var reply = context.MakeMessage(); reply.Attachments = new List <Attachment>(); reply.Attachments.Add(resultCard.FeedBack()); await context.PostAsync(reply); context.Done("Completed Conversation"); }
private async Task DisplayFeedback(IDialogContext context, IAwaitable <object> result) { ResultCard resultCard = new ResultCard(); var reply = context.MakeMessage(); reply.Attachments = new List <Attachment>(); reply.Attachments.Add(resultCard.FeedBack()); await context.PostAsync(reply); context.Wait(HandleFeedback); }
//-----------------------------------------------Displaying Info //this is called from the session manager, during the GatherInfo() public void DisplayResultCards() { RectTransform[] spacingArray = new RectTransform[SessionManager.instance.sessionProfiles.Count]; for (int i = 0; i < SessionManager.instance.sessionProfiles.Count; i++) { GameObject resultCard = (GameObject)Instantiate(resultCard_Prefab, Vector3.zero, Quaternion.identity); ResultCard temp = resultCard.GetComponent <ResultCard>(); spacingArray [i] = temp.gameObject.GetComponent <RectTransform> (); temp.InitializeResultCard(SessionManager.instance.sessionProfiles[i]); } SpaceResultCards(spacingArray); }
private void AddScoreCard() { Vector2 startPos = Skin.GetConfigStartPosition(Config, Sections[0], "ScoreCardStartPos"); Anchor anchor = GetSkinnablePropertyAnchor("ScoreCardAnchor"); scorecard = new ResultCard(startPos, anchor); int offsetX = GetSkinnablePropertyInt("ScoreCardX"); int offsetY = GetSkinnablePropertyInt("ScoreCardY"); scorecard.Move(offsetX, offsetY); }
public override bool RemoveCard(ResultCard resultCard) { if (resultCard == ResultCard.RejectCard) { CancelJob(); } if (resultCard == ResultCard.GoodCard) { Eject(); } return(true); }
// Build a custom carousel reply with a card for each search result // The card displays a thumbnail image of the document and a brief text excerpt private Activity BuildResultsReply(IList <SearchResult> results, string query, bool crypt_found) { // create a reply var reply = activity.CreateReply(); reply.Attachments = new List <Attachment>(); foreach (var result in results) { // get enrichment data from search result (and parse the JSON data) var enriched = JObject.Parse((string)result.Document["enriched"]); // all results should have thumbnail images, but just in case, look before leaping if (enriched.TryGetValue("/document/normalized_images/*/imageStoreUri", out var images)) { // Get URI of thumbnail of first content page. // If the document has multiple pages, first page is an identification form // and so the second page is the first page of interest; use its thumbnail var thumbs = new List <string>(images.Values <string>()); var picurl = thumbs[thumbs.Count > 1 ? 1 : 0]; // get valid URL of original document (combine path and token) var document = enriched["/document"]; var filename = document["metadata_storage_path"].Value <string>(); var token = document["metadata_storage_sas_token"].Value <string>(); var docurl = $"{filename}?{token}"; logger.LogTrace($"HOOVERBOT {turnid} added search result to response: {docurl}"); // Get the text from the document. This includes OCR'd printed and // handwritten text, people recognized in photos, and more. // As with the image, try to get the second page's text if it's multi-page var text = enriched["/document/finalText"].Value <string>(); if (thumbs.Count > 1) { var sep = "[image: image1.tif]"; var page2 = text.IndexOf(sep); text = page2 > 0 ? text.Substring(page2 + sep.Length) : text; } // create card for this search result and attach it to the reply var card = new ResultCard(picurl, text, docurl); reply.Attachments.Add(card.ToAttachment()); } } DescribeResultsReply(reply, query, crypt_found); AddDigDeeperButton(reply, query); logger.LogTrace($"HOOVERBOT {turnid} added text={reply.Text} and speak={reply.Speak}"); return(reply); }
// GET: ResultCards/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } ResultCard resultCard = db.ResultCards.Find(id); if (resultCard == null) { return(HttpNotFound()); } return(View(resultCard)); }
private async Task CompleteTraining(IDialogContext context, IAwaitable <IMessageActivity> result) { var response = await result; if (response.Text.Equals("Morning")) { ResultCard resultCard = new ResultCard(); var reply = context.MakeMessage(); reply.Text = FordResources.TrainingRequest; await context.PostAsync(reply); context.Wait(DisplayFeedback); } else { await context.PostAsync("training in evening is not supported"); context.Done("completed"); } }
private async Task handleLocationTraining(IDialogContext context, IAwaitable <IMessageActivity> result) { var response = await result; if (response.Text.Equals("Webex Training")) { var reply = context.MakeMessage(); reply.Text = "Got it, which time would you prefer?"; reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "Morning", "Evening" }); await context.PostAsync(reply); context.Wait(CompleteTraining); } else { await context.PostAsync("This type of training is not supported"); context.Done("completed"); } }
private async Task StartInteractiveQuestion(IDialogContext context, IAwaitable <IMessageActivity> result) { var questionairre = QnAMaker.QnAFetchter.GetAnswers("#System #InteractiveQuestionsDisplay #" + context.PrivateConversationData.GetValue <string>(StateConstants.TopicSynonym)).Result.Answers[0].AnswerAnswer; if (context.PrivateConversationData.ContainsKey(StateConstants.TopicSynonymInteractiveQuestion)) { var l = context.PrivateConversationData.GetValue <string>(StateConstants.TopicSynonymInteractiveQuestion); //questionairre -l; var res = questionairre.Replace(l, string.Empty).Split(new string[] { StateConstants.QuestionairreSeparator }, StringSplitOptions.RemoveEmptyEntries); if (res == null || res.Length == 0) { ResultCard resultCard = new ResultCard(); await context.PostAsync("THANK YOU FOR YOUR TIME, BASED ON YOUR ANSWERS I CAN SUGGEST YOU THE BELOW SOLUTION"); var intentQueryAnswer = QnAMaker.QnAFetchter. GetAnswers(context.PrivateConversationData.GetValue <string>(StateConstants.IntentQuery)).Result.Answers[0].AnswerAnswer; await context.PostAsync(intentQueryAnswer); await resultCard.PostAsyncWithConvertToOptionsCard(context, "We have suggested possible options", issueSolvedCardAction); context.Wait(this.Completed); return; } context.PrivateConversationData.SetValue <string>(StateConstants.TopicSynonymInteractiveQuestion, l + StateConstants.QuestionairreSeparator + res[0]); await context.PostAsync(res[0]); context.Wait(StartInteractiveQuestion); } else { await context.PostAsync("Starting interactive session"); var k = questionairre.Split(new string[] { StateConstants.QuestionairreSeparator }, StringSplitOptions.RemoveEmptyEntries); context.PrivateConversationData.SetValue <string>(StateConstants.TopicSynonymInteractiveQuestion, k[0]); await context.PostAsync(k[0]); context.Wait(StartInteractiveQuestion); } }
private async Task FordModelSelection(IDialogContext context, IAwaitable <IMessageActivity> result) { var response = await result; if (response.Text.Equals("Design Thinking")) { ResultCard resultCard = new ResultCard(); var reply = context.MakeMessage(); reply.Text = "Okay thanks, how would you like to complete this learning:"; reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "Bite Size Content", "Online Training Program" }); await context.PostAsync(reply); context.Wait(HandleModelTrainingComplete); } else { await context.PostAsync("This type of model thinking is not supported"); context.Done("completed"); } }
public async Task HandleBotSynonyms(IDialogContext context, IAwaitable <IMessageActivity> argument) { var response = await argument; await context.SendTypingAcitivity(); if (!response.Text.Equals(others)) { var k = QnAMaker.QnAFetchter.GetAnswers("#System #Synonyms #ProbingQuestionsDisplay #" + response.Text).Result; if (k.Answers != null && k.Answers[0].Score > Constants.MaxQNAScore) { context.PrivateConversationData.SetValue <string>(StateConstants.TopicSynonym, response.Text); await context.PostAsync(k.Answers[0].AnswerAnswer); } else { await this.DoYouWantMoreQna(context, argument); return; } } else { var k = QnAMaker.QnAFetchter.GetAnswers((context.PrivateConversationData.GetValue <string>(StateConstants.IntentQuery))).Result; if (k.Answers != null && k.Answers[0].Score > Constants.MaxQNAScore) { await context.PostAsync(k.Answers[0].AnswerAnswer); } else { await this.DoYouWantMoreQna(context, argument); return; } } ResultCard resultCard = new ResultCard(); await resultCard.PostAsyncWithConvertToOptionsCard(context, "Did this help you?", issueSolvedCardAction); context.Wait(this.DoYouWantMoreQna); }
public async Task Litigation(IDialogContext context, LuisResult result) { EntityRecommendation LitigationFromDate, LitigationToDate; var res = result.Entities[0].Entity.ToLower() .Replace(" ", "").Replace("between", "").Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries); DateTime fromDate = Convert.ToDateTime(res[0]), toDate = Convert.ToDateTime(res[1]); context.SendTypingAcitivity(); LitigationDocument.RetrieveLitigation(); context.SendTypingAcitivity(); var itms = LitigationDocument.LitigationDocuments; var results = itms.Where(cc => cc.ActiveCase && (cc.DateTracking >= fromDate && cc.DateTracking <= toDate)); var dt = "There are " + results.Count() + " active litigation cases"; var attch = ResultCard.GetThumbnailCard( "Litigation cases", dt, "Click below link to go the Sharepoint portal for Litigation Case", new CardImage(url: "http://www.ipwatchdog.com/wp-content/uploads/2016/01/litigation-red-335.jpg"), new CardAction(ActionTypes.OpenUrl, "Learn more", value: "https://m365x844754.sharepoint.com/sites/ChrevronBot/LitigationCases/Forms/AllItems.aspx")); IMessageActivity msg = context.MakeMessage(); msg.Attachments.Add(attch); await context.PostAsync(msg); msg = context.MakeMessage(); ResultCard card = new ResultCard(); card.RenderLitigationDocuments(msg, itms); await context.PostAsync(msg); context.Wait(this.MessageReceived); }
private async Task handleSiteInfo(IDialogContext context, IAwaitable <IMessageActivity> result) { var response = await result; if (response.Text.Equals("no")) { await context.PostAsync("Is there anything else I can help you with?"); context.Done("completed"); } else { var answer = QnAMaker.QnAFetchter.GetAnswers("Do The Right Thing"). Result.Answers[0].AnswerAnswer; await context.PostAsync(answer); var reply = context.MakeMessage(); reply.Text = "We hope you have enjoyed the learning?"; reply.SuggestedActions = ResultCard.GetSuggestedQnAActions(new[] { "yes", "no" }); await context.PostAsync(reply); context.Wait(DisplayFeedback); } }
public async Task InternalInvestigation(IDialogContext context, LuisResult result) { EntityRecommendation obj = null; result.TryFindEntity("builtin.number", out obj); context.SendTypingAcitivity(); InternalInvestigationDocument.RetrieveInvestigation(); context.SendTypingAcitivity(); var itms = InternalInvestigationDocument.InternalInvestigationDocuments; itms = itms.Where(cc => cc.YearOfInternalInvestigation == Convert.ToInt32(obj.Entity)).ToList(); var res = "There are " + itms.Count() + " substantiated internal investigation cases"; await context.PostAsync(res); var attch = ResultCard.GetThumbnailCard( "Internal Investigation Cases", res, "Click below link to go the Sharepoint portal for Internal Investigation Case", new CardImage(url: "http://compliancestrategists.com/csblog/wp-content/uploads/2016/10/Investigation-300x195.jpg"), new CardAction(ActionTypes.OpenUrl, "Learn more", value: " https://m365x844754.sharepoint.com/sites/ChrevronBot/Lists/Internal%20Investigation%20Case%20Tracking/AllItems.aspx")); IMessageActivity msg = context.MakeMessage(); msg.Attachments.Add(attch); await context.PostAsync(msg); msg = context.MakeMessage(); ResultCard card = new ResultCard(); card.RenderInternalDocuments(msg, itms); await context.PostAsync(msg); context.Wait(this.MessageReceived); }
void OnResultCardPulled(Character targetCharacter, ResultCard card) { }
public async Task StartAsync(IDialogContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } // Create the connector client which will be used to make requests for roster and conversation data. var connectorClient = new ConnectorClient(new Uri(context.Activity.ServiceUrl)); // Fetch members of this conversation and data from the current conversation. var members = await connectorClient.Conversations.GetConversationMembersAsync(context.Activity.Conversation.Id); var channelData = context.Activity.GetChannelData <TeamsChannelData>(); var bot = context.Activity.Recipient; // Create the match and initial results. var matchResults = members.Select(member => new MatchResult { User = member, Choice = Choices.None }); var match = new Match { SessionId = Guid.NewGuid(), Results = matchResults.ToArray() }; // Build the result card message var resultCard = new ResultCard(match.Results); var resultMessage = context.MakeMessage(); resultMessage.Attachments.Add(resultCard.ToAttachment()); // Keep track of this message so that we can update it later. var resource = await connectorClient.Conversations.ReplyToActivityAsync((Activity)resultMessage); match.MessageId = resource.Id; context.ConversationData.SetValue(match.SessionId.ToString(), match); // For each member, create the conversation and send the greetings message foreach (var member in members) { // Build the 1:1 conversation parameters var parameters = new ConversationParameters { Bot = bot, Members = new ChannelAccount[] { member }, ChannelData = new TeamsChannelData { Tenant = channelData.Tenant } }; // Create the conversation. If the bot has never talked to the user before this conversation will not exist; this ensures that the conversation exists. var conversationResource = await connectorClient.Conversations.CreateConversationAsync(parameters); // Create and send the response message. var message = Activity.CreateMessageActivity(); message.From = bot; message.Conversation = new ConversationAccount(id: conversationResource.Id); // Ensure that the match card has the conversation Id and the session Id to be able to pull up and update the appropriate data later. var matchCard = new MatchCard(context.Activity.Conversation.Id, match.SessionId); message.Attachments.Add(matchCard.ToAttachment()); await connectorClient.Conversations.SendToConversationAsync((Activity)message); } context.Done <object>(null); }
// Start is called before the first frame update public void Show(ResultCard events) { resultCard += events; targetPos = new Vector2(0, 0); }
public void Init(ResultCard resultCard) { this.resultCard = resultCard; }
/// <summary> /// Every conversation turn for our Echo Bot will call this method. /// There are no dialogs used, since it's "single turn" processing, meaning a single /// request and response. /// </summary> /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed /// for processing this conversation turn. </param> /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns> /// <seealso cref="BotStateSet"/> /// <seealso cref="ConversationState"/> /// <seealso cref="IMiddleware"/> public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken) { var type = activity.Type; context = turnContext; activity = context.Activity; // add bot's ID to greeted set so we don't greet it (no harm in doing it eeach time) greeted.Add(activity.Recipient.Id); if (type == ActivityTypes.Message) { // respond to greetings and social niceties var question = activity.Text.ToLower(); if (question.Contains("welcome")) { SendSpeechReply(Thanks); return; } if (question.Contains("hello")) { SendSpeechReply(Hello); return; } if (question.Contains("thank")) { SendSpeechReply(YoureWelcome); return; } question = activity.Text; // look for cryptomyms and send the definition of any found Regex words = new Regex(@"\b(\w+)\b", RegexOptions.Compiled); var crypt_found = false; foreach (Match match in words.Matches(question)) { var word = match.Groups[0].Value; var upperword = word.ToUpper(); if (cryptonyms.ContainsKey(upperword)) { question = new Regex("\\b" + word + "\\b").Replace(question, upperword); SendSpeechReply($"{upperword}: {cryptonyms[upperword]}", cryptonyms[upperword]); crypt_found = true; } } // transform the question into a query by stripping noise words from the front and back var frontwords = new Regex(@"^((a|an|am|with|hope|try[a-z]*|interest[a-z]+|mean[a-z]+|help|assist[a-z]*|find[a-z]*|look[a-z]*|seek[a-z]*|the|who|what|why|when|did|how|where|kill[a-z]*|assassin[a-z]*|is|um|uh|ah|and|now|has|have|had|are|were|was|out|does|please|can|will|you|show|tell|find|search|for|me|i|us|for|look|would|like|want|to|see|in|know|documents?|files?|pictures?|photos?|images?|of|on|more|results|about) +)+", RegexOptions.IgnoreCase); var query = question.Substring(frontwords.Match(question).Length); query = query.TrimEnd(".?!,;:".ToCharArray()); if (query.EndsWith(" mean") || query.EndsWith(" means")) { query = query.Substring(0, query.Length - 5); } else if (query.EndsWith(" is")) { query = query.Substring(0, query.Length - 3); } query = query.Trim(); // initiate the search var parameters = new SearchParameters() { Top = MaxResults }; // get top n results var search = searchClient.Documents.SearchAsync(query, parameters); // send typing indicator while we wait for search to complete do { SendTypingIndicator(); } while (!search.Wait(2000)); var results = search.Result.Results; SendTypingIndicator(); // create a reply var reply = activity.CreateReply(); reply.Attachments = new List <Attachment>(); foreach (var result in results) { // get enrichment data from search result (and parse the JSON data) var enriched = JObject.Parse((string)result.Document["enriched"]); // all results should have thumbnail images, but just in case, look before leaping if (enriched.TryGetValue("/document/normalized_images/*/imageStoreUri", out var images)) { // get URI of thumbnail of first content page. // if the document has multiple pages, first page is an ID form // the second page is the first page of interest var thumbs = new List <string>(images.Values <string>()); var picurl = thumbs[thumbs.Count > 1 ? 1 : 0]; // get valid URL of original document (combine path and token) var document = enriched["/document"]; var filename = document["metadata_storage_path"].Value <string>(); var token = document["metadata_storage_sas_token"].Value <string>(); var docurl = $"{filename}?{token}"; // get the text from the document. this includes OCR'd printed and // handwritten text, people recognized in photos, and more // As with the image, try to get the second page's text if it's multi-page var text = enriched["/document/finalText"].Value <string>(); if (thumbs.Count > 1) { var sep = "[image: image1.tif]"; var page2 = text.IndexOf(sep); text = page2 > 0 ? text.Substring(page2 + sep.Length) : text; } // create card for this search result and attach it to the reply var card = new ResultCard(picurl, text, docurl); reply.Attachments.Add(card.ToAttachment()); } } // Add message describing results, if any if (reply.Attachments.Count == 0) { reply.Text = $"I'm sorry, I can't find any documents matching \"{query}\""; } else { var documents = reply.Attachments.Count > 1 ? "some documents" : "a document"; reply.Text = $"I found {documents} about \"{query}\" you may be interested in."; reply.Speak = $"I found {documents} you may be interested in."; if (crypt_found) { reply.Speak = "Also, " + reply.Speak; } reply.AttachmentLayout = AttachmentLayoutTypes.Carousel; // add "Dig Deeper" button reply.SuggestedActions = new SuggestedActions() { Actions = new List <CardAction>() { new CardAction() { Title = "Dig Deeper", Type = ActionTypes.OpenUrl, Value = searchUrl + System.Uri.EscapeDataString(query), }, }, }; } // send the reply if we have search results or we didn't find a cryptonym if (reply.Attachments.Count > 1 || !crypt_found) { context.SendActivityAsync(reply); } } // Send initial greeting // Each user in the chat (including the bot) is added via a ConversationUpdate message // Check each user to make sure it's not the bot before greeting, and only greet each user else if (type == ActivityTypes.ConversationUpdate) // || type == ActivityTypes.Event) { if (activity.MembersAdded != null) { foreach (var member in activity.MembersAdded) { if (!greeted.Contains(member.Id)) { context.SendActivityAsync(Greeting); greeted.Add(member.Id); break; } } } } }