public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { // Get LUIS Intent var msg = await result; var LUISResp = await LUIS.PUserInput(msg.Text); switch (LUISResp.topScoringIntent.intent) { case LUISIntents.USERASKABOUTCROWDSOURCE: ConversationCrowd.resumeReference = new ConversationReference(context.Activity.Id, context.Activity.From, context.Activity.Recipient, context.Activity.Conversation, context.Activity.ChannelId, context.Activity.ServiceUrl); ConversationCrowd.Resume().GetAwaiter(); break; case LUISIntents.USERASKABOUTDEVELOPER: await context.PostAsync(LUISIntents.USERASKABOUTDEVELOPER); break; case LUISIntents.USERHAVENEWIDEA: await context.PostAsync(LUISIntents.USERHAVENEWIDEA); break; default: await context.PostAsync("Null intent received"); break; } }
public async Task <LUIS> QueryLUIS(string msg) { LUIS LUISResult = new LUIS(); var LUISQuery = Uri.EscapeDataString(msg); using (HttpClient client = new HttpClient()) { string LUIS_Url = LUISConfig.Value.Url; string LUIS_Subscription_Key = LUISConfig.Value.Key; string requestURI = String.Format("{0}&subscription-key={1}&q={2}", LUIS_Url, LUIS_Subscription_Key, LUISQuery); HttpResponseMessage httpMsg = await client.GetAsync(requestURI); if (httpMsg.IsSuccessStatusCode) { var JsonDataResponse = await httpMsg.Content.ReadAsStringAsync(); LUISResult = JsonConvert.DeserializeObject <LUIS>(JsonDataResponse); } LUISResult.query = requestURI; } return(LUISResult); }
public async Task RejectIntent(IDialogContext context, LuisResult result) { LUIS lui = await QueryLUIS(result.Query); string luiResult = determineNavigationRoute(lui); context.Wait(MessageReceived); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message) { //await Conversation.SendAsync(activity, () => new Dialogs.RootDialog()); //return activity.CreateReply($""+activity.Text); string botresp = ""; Rootobject obj = await LUIS.GetEntityFromLUIS(activity.Text); if (obj.intents[0].score > 0.5 && obj.intents[0].intent != "None" && obj.intents.Length > 0) { switch (obj.intents[0].intent) { case "Greeting": { botresp = "Hello, Welcome to AAR service!"; break; } case "Goodbye": { botresp = "Thanks, have a good day!"; break; } case "Registration": { foreach (var entity in obj.entities) { if (entity.entity == "electronics") { botresp += " You can not take " + entity.entity + " course at this time. first you need to take prerequisite course which is Fundamentals of circuit.\n"; } else { botresp += " you can take " + entity.entity + " at this time.\n"; } } break; } case "Course schedule": { botresp = "Yes, you have class today"; break; } case "Identity": { botresp = "I’m chatbot and I’ll be an acadamic assistant for you :)"; break; } } } else { botresp = "Sorry, I am not getting you..."; } activity.Text = botresp; await Conversation.SendAsync(activity, () => new Dialogs.RootDialog()); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
//LUIS API public IEnumerator LUISModelCall(string inputText) { string result; //Checks if the authorization is already been done if (!string.IsNullOrEmpty(inputText)) { //First detect language StartCoroutine(DetectTextLanguage(inputText)); yield return(new WaitForSeconds(6)); Debug.Log("Language detected..."); WWWForm form = new WWWForm(); if (string.IsNullOrEmpty(detectedLanguageCode)) { Debug.Log("Detected language is empty!"); } else { switch (detectedLanguageCode) { case "en": //API Request string uri_en = LUIS_ENDPOINT + "apps/" + LUIS_EN_MODEL_APPID + "?subscription-key=" + LUIS_SUBSCRIPTION_KEY_EN + "&timezoneOffset=0&verbose=true&q=" + inputText; WWW web_en = new WWW(uri_en); while (!web_en.isDone) { yield return(web_en); } //Saves the result result = web_en.text; Debug.Log("LUIS response: " + result); break; case "it": //API Request string uri_it = LUIS_ENDPOINT + "apps/" + LUIS_IT_MODEL_APPID + "?subscription-key=" + LUIS_SUBSCRIPTION_KEY_IT + "&timezoneOffset=0&verbose=true&q=" + inputText; WWW web_it = new WWW(uri_it); while (!web_it.isDone) { yield return(web_it); } //Saves the result result = web_it.text; LUIS luis_response = JsonUtility.FromJson <LUIS>(result); Debug.Log("LUIS response: " + luis_response.topScoringIntent); break; } } } }
public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; await context.PostAsync($"checking ..."); string policyKey = string.Empty; //Send and recive from LUIS here PolicyLUIS userRequest = await LUIS.ProcessuserInput(message.Text); policyKey = await new PolicyActionManager().GetActionToPerform(userRequest); //policyKey = "leave"; await PrepareResponse(context, policyKey); }
private string determineNavigationRoute(LUIS lui) { if (lui != null) { if (lui.entities[0].type == "ReservationBot") { return("ReservationBot"); } else if (lui.entities[0].type == "FormBot") { return("FormBot"); } else if (lui.entities[0].type == "Back") { return("Back"); } } return("Sorry I couldn't proces your request."); }
public ActionResult SmartInteract(string q, string device) { Response.AppendHeader("Access-Control-Allow-Origin", "*"); if (device == null) { device = "alexa"; } LuisManager luis = new LuisManager(); LUIS intent = luis.ExtractIntent(q); NewsBotManager newsBot = new NewsBotManager(); return(new JsonResult { Data = newsBot.GetNewsLinesByIntent(intent, device), JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "application/json" }); }
private static async Task <LUIS> GetEntityFromLUIS(string Query) { Query = Uri.EscapeDataString(Query); LUIS Data = new LUIS(); using (HttpClient client = new HttpClient()) { string RequestURI = modelURL + "&q=" + Query; HttpResponseMessage msg = await client.GetAsync(RequestURI); if (msg.IsSuccessStatusCode) { var JsonDataResponse = await msg.Content.ReadAsStringAsync(); Data = JsonConvert.DeserializeObject <LUIS>(JsonDataResponse); } } return(Data); }
public async Task SendMessage(string message) { string encodedMsg = HtmlEncoder.Default.Encode(message); LUIS LUISObj = await LUISService.QueryLUIS(encodedMsg); string topIntent = LUISObj.topScoringIntent.intent; Chat chat = connectedChats[Context.ConnectionId]; if (chat.state == ChatState.waitForQuestion) { switch (topIntent) { case "Greetings": await Clients.Caller.SendAsync("ReceiveMessage", "Hallo!"); return; case "GetInfoAboutContiniousDelivery": await Clients.Caller.SendAsync("ReceiveMessage", "Continious Delivery... info info info... "); return; } } // sandy wist geen antwoord, via LUIS // verwerkt het inkomend bericht, en geeft een status terug ReceivedMessage rState = handleChatStateAndData(message, topIntent, chat); // get response, misschien wel uit een database.. string[] response = getResponse(rState); // reply for (int i = 0; i < response.Length; i++) { await Clients.Caller.SendAsync("ReceiveMessage", response[i]); } // voert eventuele tasks uit die nodig zijn aan de hand van de status van het ontvangen bericht await handleTasksAndSetNewState(rState, chat); }
public string trainLUIS() { List <LUISResponse> result = new List <LUISResponse>(); string LUISAppId = ConfigurationManager.AppSettings["LUISAppId"]; string LUISAppKey = ConfigurationManager.AppSettings["LUISAppKey"]; string LUISMaxCharacters = ConfigurationManager.AppSettings["LUISMaxCharacters"]; Trace.TraceInformation("LUISAppID: " + LUISAppId); Trace.TraceInformation("LUISAppKey: " + LUISAppKey); Trace.TraceInformation("LUISMaxCharacters: " + LUISMaxCharacters); //Recoger los valores de las variables y crear la clase LUIS _luis = new LUIS(LUISAppId, LUISAppKey, int.Parse(LUISMaxCharacters)); //Connect to Media Assets storage account string MediaAssetsStorageAccountName = ConfigurationManager.AppSettings["MediaAssetsStorageAccountName"]; string MediaAssetsStorageAccountKey = ConfigurationManager.AppSettings["MediaAssetsStorageAccountKey"]; string containerName = ConfigurationManager.AppSettings["TrainingTextsStorageContainer"]; string storageAccountConnectionString = "DefaultEndpointsProtocol=https;AccountName=" + MediaAssetsStorageAccountName + ";AccountKey=" + MediaAssetsStorageAccountKey; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccountConnectionString); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(containerName); string text = ""; foreach (Uri blob in getTrainingBlobsFromStorageAccount()) { text = readBlobFileAsText(container, blob); result.Add(_luis.makeLUISCallFromText(text)); } ViewData["LUISResponses"] = result; //return RedirectToAction("Index"); return("Controller says: Entrenado"); }
// GET: Luis public ActionResult Index() { string LUISAppId = ConfigurationManager.AppSettings["LUISAppId"]; string LUISAppKey = ConfigurationManager.AppSettings["LUISAppKey"]; string LUISMaxCharacters = ConfigurationManager.AppSettings["LUISMaxCharacters"]; Trace.TraceInformation("LUISAppID: " + LUISAppId); Trace.TraceInformation("LUISAppKey: " + LUISAppKey); Trace.TraceInformation("LUISMaxCharacters: " + LUISMaxCharacters); ViewBag.LUISAppId = LUISAppId; ViewBag.BlobList = getTrainingBlobsFromStorageAccount(); //Recoger los valores de las variables y crear la clase LUIS _luis = new LUIS(LUISAppId, LUISAppKey, int.Parse(LUISMaxCharacters)); return(View()); }
public async Task <ActionResult> Index(string searchString) { Query Return = new Query(); try { if (searchString != null) { LUIS objLUISResult = await QueryLUIS(searchString); foreach (var item in objLUISResult.entities) { if (item.type == "Student Name::First Name") { Return.FirstName = item.entity; } if (item.type == "Student Name::Last Name") { Return.LastName = item.entity; } if (item.type == "Class") { Return.Class = item.entity; } if (item.type == "Period") { Return.Period = item.entity; } } } return(View(Return)); } catch (Exception ex) { ModelState.AddModelError(string.Empty, "Error: " + ex); return(View(Return)); } }
public static async Task <LUIS> QueryLUIS(string Query) { LUIS LUISResult = new LUIS(); var LUISQuery = Uri.EscapeDataString(Query); using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { // Get key values from the web.config string LUIS_Url = WebConfigurationManager.AppSettings["LUISUrl"]; string LUIS_Subscription_Key = WebConfigurationManager.AppSettings["LUISSubscriptionKey"]; string RequestURI = String.Format("{0}?subscription-key={1}&q={2}", LUIS_Url, LUIS_Subscription_Key, LUISQuery); System.Net.Http.HttpResponseMessage msg = await client.GetAsync(RequestURI); if (msg.IsSuccessStatusCode) { var JsonDataResponse = await msg.Content.ReadAsStringAsync(); LUISResult = JsonConvert.DeserializeObject <LUIS>(JsonDataResponse); } } return(LUISResult); }
private static async Task <LUIS> QueryLUIS(string Query) { LUIS LUISResult = new LUIS(); var LUISQuery = Uri.EscapeDataString(Query); using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { // Get key values from the web.config string LUIS_Url = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/21a37abf-f032-413a-9ebe-5b709bdfd4ed"; string LUIS_Subscription_Key = "34a7147d5534422aa6ddc32f312e2f28"; string RequestURI = String.Format("{0}?subscription-key={1}&q={2}", LUIS_Url, LUIS_Subscription_Key, LUISQuery); Console.WriteLine(RequestURI); System.Net.Http.HttpResponseMessage msg = await client.GetAsync(RequestURI); if (msg.IsSuccessStatusCode) { var JsonDataResponse = await msg.Content.ReadAsStringAsync(); LUISResult = JsonConvert.DeserializeObject <LUIS>(JsonDataResponse); } } return(LUISResult); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // calculate something for us to return int length = (activity.Text ?? string.Empty).Length; // return reply to the user LUIS luis = await GetEntityFromLUIS(activity.Text); string sIntent = luis.intents[0].intent; Activity reply = activity.CreateReply(sIntent); //Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters"); await connector.Conversations.ReplyToActivityAsync(reply); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
public async Task ConfirmationIntent(IDialogContext context, LuisResult result) { LUIS lui = await QueryLUIS(result.Query); string luiResult = determineNavigationRoute(lui); if (luiResult == "ReservationBot") { await context.PostAsync("Would you like to navigate to the ReservationBot? http://localhost:57078/Home/Reservation"); } else if (luiResult == "FormBot") { await context.PostAsync("Would you like to navigate to the FormBot? http://luisdocumentdb.azurewebsites.net/Home/Form"); } else if (luiResult == "Back") { await context.PostAsync("Going back http://luisdocumentdb.azurewebsites.net/Home/Index"); } else { await context.PostAsync(luiResult); } context.Wait(MessageReceived); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Activity reply = null; if (activity.Type == ActivityTypes.Message) { //Here, i'm using LuisDialog await Conversation.SendAsync(activity, () => new BotDialog()); //Here, a very classic way string Response = String.Empty; try { LuisResponse _luisResponse = await LUIS.GetLuisResponse(activity.Text); if (_luisResponse.intents.Count() > 0) { switch (_luisResponse.intents[0].intent) { case "Greetings": Response = "Hi there !"; break; case "Weather": var entities = _luisResponse.entities?.Count() ?? 0; Response = entities > 0 ? await OpenWeather.GetWeather(_luisResponse?.entities?[0]?.entity) : "If you're asking about weather, please enter a valid city name"; break; default: Response = "Sorry, I am not getting you..."; break; } } else { Response = "Sorry, I am not getting you..."; } } catch (Exception ex) { Response = ex.Message; } // return our reply to the user reply = activity.CreateReply(Response); } else { reply = HandleSystemMessage(activity); } if (reply != null) { await connector.Conversations.ReplyToActivityAsync(reply); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument) { var message = await argument; //await context.PostAsync("You said: " + message.Text); string input = message.Text; //Activity reply; string displayString = ""; channel = message.ChannelId; uid = message.From.Id; if (!RegisterCheck) { RegisterCheck = true; user = DB_Operation.queryUserInfo(channel, uid); if (user != null) { IsRegister = true; } } if (input.ToLower() == "register") { var userForm = new FormDialog <FormUserInfo>(new FormUserInfo(), FormUserInfo.BuildForm, FormOptions.PromptInStart); context.Call <FormUserInfo>(userForm, UserFormComplete); } else { INTENT userIntent; HashSet <string> keywords = LUIS.getNP(input, out userIntent); //if (Reaction.isLookingForPerson(input)) if (userIntent == INTENT.FindUser) { await context.PostAsync("Let me check..."); //HashSet<string> keywords; //Dictionary<Person, double> user_list = Reaction.LookingForPerson(input, out keywords); if (keywords.Count == 0) { displayString += "Sorry, I can not understand your query. Do you meant to find a user with specific skill? You can try to ask me: \"Who knows *skill1, skill2, ...*\"."; } else { Dictionary <Person, double> user_list = QueryInterface.queryUser(keywords); if (user_list.Count == 0) { displayString += "Sorry, I could not find any appropriate user for your query \"" + input + "\""; } else { displayString += "I find serveral users who might help you with"; foreach (var keyword in keywords) { displayString += " " + keyword; } displayString += ":"; foreach (Person p in user_list.Keys) { displayString += "\n"; displayString += string.Format("* [{1}]({0})", p.homepageurl, p.userLogin); } } } } //else if (Reaction.isLookingForProject(input)) else if (userIntent == INTENT.FindProject) { await context.PostAsync("Let me check..."); //HashSet<string> keywords; //Dictionary<Project, double> project_list = Reaction.LookingForProject(input,out keywords); if (keywords.Count == 0) { displayString += "Sorry, I can not understand your query. Do you meant to find a project on specific techs? You can try to ask me: \"Find project about *tech1, tech2, ...*\"."; } else { Dictionary <Project, double> project_list = QueryInterface.queryProject(keywords); if (project_list.Count == 0) { displayString += "Sorry, I could not find any appropriate project for your query \"." + input + "\""; } else { displayString += "I find serveral projects about"; foreach (var keyword in keywords) { displayString += " " + keyword; } displayString += ":"; foreach (Project p in project_list.Keys) { displayString += "\n"; displayString += string.Format("* [{1}]({0})", p.projectUrl, p.projectName); } } } } //else if (Reaction.isLookingForTeam(input)) else if (userIntent == INTENT.FindTeam) { await context.PostAsync("Let me check..."); //HashSet<Tuple<Person, string>> records = Reaction.LookingForTeam(input); if (keywords.Count == 0) { displayString += "Sorry, I can not understand your query. Do you meant to find a team of users to cover specific skills? You can try to ask me: \"Find a team covers skill of *skill1, skill2, ...*\"."; } else { HashSet <Tuple <Person, string> > records = QueryInterface.queryTeam(keywords); if (records.Count == 0) { displayString += "Sorry, I could not find any team according to your requirement \"." + input + "\""; } else { displayString += "I find a team consists of following users according to your requirement:\n\n"; displayString += "**People**\t\t**Skills**"; foreach (Tuple <Person, string> t in records) { displayString += "\n\n"; displayString += string.Format("* [{2}]({0})\t\t{1}", t.Item1.userLogin, t.Item2, t.Item1.homepageurl); } } } } else { displayString = "I'm a bot to help you find people or project with specific technological skills on GitHub easily. [More Channel](http://collabotframework.azurewebsites.net)"; displayString += "\n\n You can start with: \n"; displayString += "* \"Who knows *skill1, skill2, ...*\"\n"; displayString += "* \"Find project about *tech1, tech2, ...*\"\n"; displayString += "* \"Find a team covers skills of *skill1, skill2, ...*\""; displayString += "\n\n Say *register* to let me serve you better!"; //int length = (activity.Text ?? string.Empty).Length; //Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters <br/> Test new line"); } await context.PostAsync(displayString); System.Diagnostics.Trace.TraceInformation("Reply: [markdown]{0}", displayString); context.Wait(MessageReceivedAsync); } }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { if (activity.Type == ActivityTypes.Message) { if (ProdSearch.Dialogs.ProdSearch_KeywordDialog.getcheck()) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); string strLuisKey = ConfigurationManager.AppSettings["LUISAPIKey"].ToString(); string strLuisAppId = ConfigurationManager.AppSettings["LUISAppId"].ToString(); string strMessage = HttpUtility.UrlEncode(activity.Text); string strLuisUrl = $"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/{strLuisAppId}?subscription-key={strLuisKey}&verbose=true&timezoneOffset=0&q={strMessage}"; // 收到文字訊息後,往LUIS送 WebRequest request = WebRequest.Create(strLuisUrl); HttpWebResponse hwresponse = (HttpWebResponse)request.GetResponse(); Stream dataStream = hwresponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string json = reader.ReadToEnd(); LUIS objLUISRes = JsonConvert.DeserializeObject <LUIS>(json); string strReply = "無法識別的內容"; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setLuisKWCheck_true(); if (objLUISRes.intents.Count > 0) { string strIntent = objLUISRes.intents[0].intent; if (strIntent.Equals("搜尋壽險")) { strReply = "將進行搜尋壽險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("壽險"); } else if (strIntent.Equals("搜尋投資型保險")) { strReply = "將進行搜尋投資型保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("投資"); } else if (strIntent.Equals("搜尋年金保險")) { strReply = "將進行搜尋年金保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("年金"); } else if (strIntent.Equals("搜尋小額終老保險")) { strReply = "將進行搜尋小額終老保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("小額終老"); } else if (strIntent.Equals("搜尋實物給付型保險")) { strReply = "將進行搜尋實物給付型保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("實物給付"); } else if (strIntent.Equals("搜尋長照")) { strReply = "將進行搜尋長照..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("長照專區"); } else if (strIntent.Equals("搜尋大男子保險")) { strReply = "將進行搜尋大男子保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("大男子保險"); } else if (strIntent.Equals("搜尋生死合險")) { strReply = "將進行搜尋生死合險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("生死合險"); } else if (strIntent.Equals("搜尋HER大女子保險")) { strReply = "將進行搜尋HER大女子保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("HER大女子保險"); } else if (strIntent.Equals("搜尋OIU保險")) { strReply = "將進行搜尋OIU保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("OIU專區"); } else if (strIntent.Equals("搜尋利變壽")) { strReply = "將進行搜尋利變壽..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("利變壽"); } else if (strIntent.Equals("搜尋展新人生保險")) { strReply = "將進行搜尋展新人生保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("展新人生"); } else if (strIntent.Equals("搜尋意外傷害險")) { strReply = "將進行搜尋意外傷害險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("意外傷害"); } else if (strIntent.Equals("搜尋活力系列保險")) { strReply = "將進行搜尋活力系列保險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("活力系列"); } else if (strIntent.Equals("搜尋醫療險")) { strReply = "將進行搜尋醫療險..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setKeyword("醫療"); } else { strReply = "無法識別的內容,請重新輸入..."; ProdSearch.Dialogs.ProdSearch_KeywordDialog.setLuisKWCheck_false(); } } Activity reply = activity.CreateReply(strReply); await connector.Conversations.ReplyToActivityAsync(reply); ProdSearch.Dialogs.ProdSearch_KeywordDialog.setcheck(); } else if (true) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); string strLuisKey = ConfigurationManager.AppSettings["LUISAPIKey"].ToString(); string strLuisAppId = ConfigurationManager.AppSettings["LUISAppId"].ToString(); string strMessage = HttpUtility.UrlEncode(activity.Text); string strLuisUrl = $"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/{strLuisAppId}?subscription-key={strLuisKey}&verbose=true&timezoneOffset=0&q={strMessage}"; // 收到文字訊息後,往LUIS送 WebRequest request = WebRequest.Create(strLuisUrl); HttpWebResponse hwresponse = (HttpWebResponse)request.GetResponse(); Stream dataStream = hwresponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string json = reader.ReadToEnd(); LUIS objLUISRes = JsonConvert.DeserializeObject <LUIS>(json); //string strReply = "無法識別的內容"; if (objLUISRes.intents.Count > 0) { string strIntent = objLUISRes.intents[0].intent; if (strIntent.Equals("回首頁選單")) { RootDialog.SetBack2home(true); } } //Activity reply = activity.CreateReply(strReply); //await connector.Conversations.ReplyToActivityAsync(reply); } await Conversation.SendAsync(activity, () => new Dialogs.RootDialog()); } else { HandleSystemMessage(activity); } var response = Request.CreateResponse(HttpStatusCode.OK); return(response); }