예제 #1
0
        public async Task Vote(IDialogContext context, LuisResult result)
        {
            string message;

            if (!VoteHasBegun)
            {
                message = $"Voting hasn't started yet. Did you mean to say \"Call to vote\"?";
            }
            else
            {
                EntityRecommendation entityRecommendation = result.Entities.FirstOrDefault();
                string ballot = entityRecommendation?.Entity;
                if (string.IsNullOrEmpty(ballot))
                {
                    message = $"LUIS didn't get an entity out of {result.Query}.";
                }
                else
                {
                    if (Ballot.Instance == null)
                    {
                        Ballot.Instance = new Ballot(DataStore.Instance.GetSeconds().ToArray());
                    }
                    Ballot.Instance.Cast(User, ballot);
                    message =
                        $"{User}, I've received your vote. Feel free to recast your vote, only your last vote will be counted.";
                }
            }
            await context.PostAsync(message);

            context.Wait(MessageReceived);
        }
예제 #2
0
        public async Task Veto(IDialogContext context, LuisResult result)
        {
            bool task = await Task.Run(() => { Thread.Sleep(new TimeSpan(0, 5, 0)); return(true); });

            EntityRecommendation entityRecommendation = result.Entities.FirstOrDefault();
            string location = entityRecommendation?.Entity;
            string message;

            if (string.IsNullOrEmpty(location))
            {
                message = $"LUIS didn't get an entity out of {result.Query}.";
            }
            else
            {
                if (DataStore.Instance.CanVeto(User))
                {
                    DataStore.Instance.Veto(location, User);
                    message = $"{location} has been \"{DataStore.Instance.Status(location)}\".";
                }
                else
                {
                    message = $"{User} can't veto anymore";
                }
            }
            await context.PostAsync(message);

            context.Wait(MessageReceived);
        }
        public static DateTimeOffset?ToDateTime(this EntityRecommendation entity, TimeSpan?offset = null)
        {
            if (entity == null)
            {
                return(null);
            }
            //when you say July 20,
            //if today is July 30
            //  - LUIS returns two dates - July 20, 2016 & July 20, 2017
            //if today is July 10
            //  - LUIS returns two dates - july 20 2017 & July 20 2018
            //This looks like a bug in LUIS
            dynamic value = ((Newtonsoft.Json.Linq.JArray)entity.Resolution["values"])[0];

            var dt    = DateTime.Parse((string)value.value);
            var dtoff = offset.HasValue ? new DateTimeOffset(dt, offset.Value) : new DateTimeOffset(dt);

            var ret = ((Newtonsoft.Json.Linq.JArray)entity.Resolution["values"])
                      .Select(j => {
                var item = new DateTimeOffset(DateTime.Parse((string)j.Value <string>("value")), dtoff.Offset);
                return(item);
            })
                      .Where(d => d.Date >= DateTimeOffset.UtcNow.Add(dtoff.Offset).Date)
                      .OrderBy(t => t.Date)
                      .FirstOrDefault();

            //((Newtonsoft.Json.Linq.JArray)entity.Resolution["values"]).Where( v => DateTime.Parse((string)value.value).Date >= DateTimeOffset.Now.Add(dtoff.Offset)).OrderBy()
            //var dtoff = DateTimeOffset.Parse((string)value.value);


            return(ret);
        }
예제 #4
0
        private async Task After_NamePrompt(IDialogContext context, IAwaitable <string> result)
        {
            EntityRecommendation name;

            currentName = await result;
            if (currentName != null)
            {
                name = new EntityRecommendation(type: Entity_Communication_Name)
                {
                    Entity = currentName
                };
                var comm = new Communication()
                {
                    ContactName = currentName
                };
                contact = communicationByContact[comm.ContactName] = comm;

                PromptDialog.Text(context, After_NumberPrompt, $"**{currentName}** is the name of contact. What's the number ?");
            }
            else
            {
                PromptDialog.Text(context, After_NamePrompt, "Sorry, but I cannot understand the name. Could you please repeat that?");
                context.Wait(MessageReceived);
            }
        }
        private static JToken GetEntityValue(EntityRecommendation entity)
        {
            if (entity.Resolution == null)
            {
                return(entity.Entity);
            }

            if (entity.Type.StartsWith("builtin.datetimeV2."))
            {
                return(new JValue(entity.Resolution?.Values != null && entity.Resolution.Values.Count > 0
                            ? ((IDictionary <string, object>)((IList <object>)entity.Resolution.Values.First()).First())["timex"]
                            : entity.Resolution));
            }

            if (entity.Type.StartsWith("builtin.number"))
            {
                var value = (string)entity.Resolution.Values.First();
                return(long.TryParse(value, out var longVal) ?
                       new JValue(longVal) :
                       new JValue(double.Parse(value)));
            }

            return(entity.Resolution.Count > 1 ?
                   JObject.FromObject(entity.Resolution) :
                   entity.Resolution.ContainsKey("value") ?
                   (JToken)JObject.FromObject(entity.Resolution["value"]) :
                   JArray.FromObject(entity.Resolution["values"]));
        }
예제 #6
0
파일: LUIS.cs 프로젝트: zhiwang53/BotDemo
        public async Task DecreaseTemp(IDialogContext context, LuisResult result)
        {
            EntityRecommendation platenum;

            if (!result.TryFindEntity(ENTITY_PLATE, out platenum))
            {
                platenum = new EntityRecommendation(type: ENTITY_PLATE)
                {
                    Entity = string.Empty
                };
            }


            if (platenum != null)
            {
                plate = $" 京{platenum.Entity} ";
                await context.PostAsync(RESULT_RETURN1 + plate + RESULT_RETURN2);
            }
            else
            {
                await context.PostAsync("不能找到您的车辆信息");
            }

            context.Wait(MessageReceived);
        }
        public static string ResolveFood(EntityRecommendation entity)
        {
            var value = entity.Resolution["values"] as IEnumerable <object>;


            return((value.ToList())[0].ToString());
        }
예제 #8
0
        public async Task RateIntent(IDialogContext context, LuisResult result)
        {
            EntityRecommendation erLoanAMount = null;
            EntityRecommendation erTenure     = null;

            result.TryFindEntity("loanAmount", out erLoanAMount);
            result.TryFindEntity("tenure", out erTenure);
            if (result.Entities.Count == 1 && erLoanAMount != null && erLoanAMount.Type == "loanAmount")
            {
                loanAmount = float.Parse(erLoanAMount.Entity);
                await context.PostAsync($"Please tell us your tenure");
            }
            else if (result.Entities.Count == 1 && erTenure != null && erTenure.Type == "tenure")
            {
                tenure = float.Parse(erTenure.Entity);
                var installment = CalculateLoanInstallment(loanAmount, tenure);
                await context.PostAsync($"We calculated your monthly rate , it is " + installment.ToString());
            }

            //foreach (EntityRecommendation er in result.Entities)
            //{
            //    if (er != null)
            //    {
            //        object amount = 0;
            //        er.Resolution.TryGetValue("value", out amount);
            //    }
            //}



            //await context.PostAsync($"Please tell us your loan amount and tenure as comma separated");
        }
예제 #9
0
        private async Task <SearchMealRequest> GetSearchFoodRequest(IDialogContext context, LuisResult result)
        {
            SearchMealRequest searchMealRequest = new SearchMealRequest();

            EntityRecommendation foodEntityRecommendation = null;

            EntityRecommendation cityEntityRecommendation = null;


            if (result.TryFindEntity(EntityFood, out foodEntityRecommendation) && result.TryFindEntity(EntityLocation, out cityEntityRecommendation))
            {
                searchMealRequest.MealName = foodEntityRecommendation.Entity;

                searchMealRequest.Location = cityEntityRecommendation.Entity;

                string message = $"Hey! Give me second while I search for {searchMealRequest.MealName}. But first, let's confirm the location you provided me.";

                await context.PostAsync(message);
            }
            else
            {
                var errorMessage = $"Ooops! Something went your. Can you please try again. Type 'help' assistance and search tips.";

                await context.PostAsync(errorMessage);

                context.Wait(MessageReceived);
            }

            //GoogleLocationService locationService = new GoogleLocationService(GoogleApiKey);

            searchMealRequest.AddressesArray = _externalService.GetAddressesArray(searchMealRequest.Location);
            return(searchMealRequest);
        }
예제 #10
0
        private static async Task <SearchMealsByDistance> GetMealByDistanceRequest(IDialogContext context, LuisResult result)
        {
            SearchMealsByDistance mealByDistance = new SearchMealsByDistance();



            EntityRecommendation foodEntityRecommendation = null;

            EntityRecommendation locationEntityRecommendation = null;

            EntityRecommendation priceEntityRecommendation = null;



            EntityRecommendation distanceEntityRecommendation = null;



            if (result.TryFindEntity(EntityDistance, out distanceEntityRecommendation))
            {
                int miles = 0;
                //Double.TryParse(priceEntityRecommendation.Entity, out price);
                Int32.TryParse(distanceEntityRecommendation.Entity.ToString(), out miles);
                mealByDistance.Distance = miles;
            }

            if (result.TryFindEntity(EntityCurrency, out priceEntityRecommendation))
            {
                decimal price = 0;
                //Double.TryParse(priceEntityRecommendation.Entity, out price);
                Decimal.TryParse(priceEntityRecommendation.Resolution["value"].ToString(), out price);
                mealByDistance.Price = price;
            }

            string welcomeMessage = null;

            if (mealByDistance.Price == null || !mealByDistance.Price.HasValue)
            {
                welcomeMessage = $"Give me a second while I look for next meal within {mealByDistance.Distance} miles.";
            }
            else
            {
                welcomeMessage = $"Give me a second while I look for next meal within {mealByDistance.Distance} under  ${mealByDistance.Price}.";
            }

            if (result.TryFindEntity(EntityLocation, out locationEntityRecommendation))
            {
                mealByDistance.Location = locationEntityRecommendation.Entity;
            }


            if (result.TryFindEntity(EntityFood, out foodEntityRecommendation))
            {
                mealByDistance.MealName = foodEntityRecommendation.Entity;
            }

            await context.PostAsync(welcomeMessage);

            return(mealByDistance);
        }
예제 #11
0
        public async Task ShowBalance(IDialogContext context, LuisResult result)
        {
            PostbankClient client = new PostbankClient("Hackathon5", "test12345");

            try
            {
                client = await client.GetAccountInformationAsnyc();

                EntityRecommendation ent = null;
                if (result.TryFindEntity("AccountNumber", out ent))
                {
                    var account = client.IDInfo.accounts.Where(i => i.iban.ToLower() == ent.Entity).First();
                    await context.PostAsync($"The balance for your {account.productDescription} account with IBAN {account.iban} is {account.amount} {account.currency}.");
                }
                else
                {
                    await context.PostAsync($"For what account do you want to display your balance? You have got {client.IDInfo.accounts.Count} account(s) with the following IBAN:");

                    foreach (var item in client.IDInfo.accounts)
                    {
                        await context.PostAsync(item.iban);
                    }
                    await context.PostAsync("Which account do you want to use?");
                }
            }
            catch (Exception ex)
            {
                await context.PostAsync($"I am sorry. :( There has been some problems in getting your account information. Please try again later. The error message is {ex.Message}.");
            }
            finally
            {
                context.Wait(MessageReceived);
            }
        }
예제 #12
0
        public bool SearchEmail(EntityRecommendation adressEmail)
        {
            NpgsqlConnection connection = new NpgsqlConnection(conn);

            connection.Open();
            string        address = adressEmail.Entity;
            NpgsqlCommand command = new NpgsqlCommand("Select  count(*) from saveemail where addres=@email", connection);

            command.Parameters.AddWithValue("@email", address);
            try
            {
                Int32 count = Convert.ToInt32(command.ExecuteScalar());
                if (count < 1)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public static bool TryGetRange(this EntityRecommendation entity, out Range range)
        {
            range = default(Range);

            if (entity.Type.EndsWith("range"))
            {
                var values = GetDateTimeValues(entity);

                if (values != null)
                {
                    range = new Range();
                    if (values.ContainsKey("start"))
                    {
                        range.Start = values["start"].ToString();
                    }
                    if (values.ContainsKey("end"))
                    {
                        range.End = values["end"].ToString();
                    }
                }
                return(true);
            }

            return(false);
        }
예제 #14
0
        private async Task After_TitlePrompt(IDialogContext context, IAwaitable <string> result)
        {
            EntityRecommendation title;

            tituloActual = await result;

            if (tituloActual != null)
            {
                title = new EntityRecommendation(type: EntidadTituloNota)
                {
                    Entity = tituloActual
                };
            }
            else
            {
                title = new EntityRecommendation(type: EntidadTituloNota)
                {
                    Entity = TituloNota
                };
            }

            var nota = new Nota()
            {
                Titulo = title.Entity
            };

            notaNueva = this.ListaNotas[nota.Titulo] = nota;

            PromptDialog.Text(context, After_TextPrompt, "¿Cuál es el contenido de tu nota?");
        }
예제 #15
0
        public async Task FindArticlesIntentHandlerAsync(IDialogContext context, IAwaitable <IMessageActivity> activity, LuisResult result)
        {
            EntityRecommendation entityRecommendation = null;

            // get the entity from the query
            var query = result.TryFindEntity(JFKFilesBOTStrings.ArticlesEntityTopic, out entityRecommendation) ? entityRecommendation.Entity : result.Query;

            // let's do a bing search
            var bingSearch = await this.bingSearchService.FindArticles(query);

            // check for any errors
            if (bingSearch.statusCode != null && bingSearch.statusCode != "200")
            {
                await context.PostAsync(string.Format("Sorry something went wrong: {0}", bingSearch.message));
            }
            else if (bingSearch.webPages != null && bingSearch.webPages.value.Length > 0)
            {
                // get the result
                var searchresult = this.PrepareSearchResult(query, bingSearch.webPages.value[0]);

                // build the markdown text
                var summaryText = $"### [{searchresult.Tile}]({searchresult.Url})\n{searchresult.Snippet}\n\n";
                summaryText += $"*{string.Format(Strings.PowerBy, $"[Bing™](https://www.bing.com/search/?q={searchresult.Query} site:wikipedia.org)")}*";

                // post result
                await context.PostAsync(string.Format(Strings.SearchTopicTypeMessage));

                await context.PostAsync(summaryText);
            }
            else
            {
                await context.PostAsync("Sorry something went wrong!");
            }
        }
예제 #16
0
        /// <summary>
        /// provide a query string with entities removed.
        /// This is not currently used.
        /// The purpose was to help isolate the subject text that
        /// the user is interested in searching for.
        /// For now, the user should put double quotes around
        /// the subject text for searching.
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string StripEntities(LuisResult result)
        {
            char[] Remaining = result.Query.ToCharArray();
            try
            {
                int n = result.Entities.Count;
                for (int i = 0; i < n; i++)
                {
                    EntityRecommendation er = result.Entities[i];
                    if (er.StartIndex != null)
                    {
                        for (int j = (int)er.StartIndex; j <= (int)er.EndIndex; j++)
                        {
                            Remaining[j] = ' ';
                        }
                    }
                }
            }
            catch (System.Exception)
            {
            }
            string s = CharArrayToString(Remaining);

            return(s);
        }
예제 #17
0
파일: RecipeDialog.cs 프로젝트: Fanuer/HIS
        private RecipeSearchViewModel CreateSearchModel(LuisResult result)
        {
            EntityRecommendation recipeName;

            if (!result.TryFindEntity(Entity_Recipename, out recipeName))
            {
                recipeName = new EntityRecommendation(type: Entity_Recipename)
                {
                    Entity = ""
                };
            }

            IList <EntityRecommendation> ingrediants;

            if (!result.TryFindEntity(Entity_Ingrediant, out ingrediants))
            {
                ingrediants = new List <EntityRecommendation>();
            }

            IList <EntityRecommendation> tags;

            if (!result.TryFindEntity(Entity_Tag, out tags))
            {
                tags = new List <EntityRecommendation>();
            }

            var searchModel = new RecipeSearchViewModel()
            {
                Tags        = tags.Where(x => !String.IsNullOrWhiteSpace(x.Entity)).Select(x => x.Entity.Replace(" ", "")).ToList(),
                Ingrediants = ingrediants.Where(x => !String.IsNullOrWhiteSpace(x.Entity)).Select(x => x.Entity.Replace(" ", "")).ToList(),
                Name        = recipeName.Entity
            };

            return(searchModel);
        }
예제 #18
0
        //  Creates a new note using the user's response to the prompt for a title
        private async Task After_TitlePrompt(IDialogContext context, IAwaitable <string> result)
        {
            EntityRecommendation title;

            // Set the title to the user's response
            currentTitle = await result;
            if (currentTitle != null)
            {
                title = new EntityRecommendation(type: Entity_Note_Title)
                {
                    Entity = currentTitle
                };
            }
            else
            {
                // Use the default note title
                title = new EntityRecommendation(type: Entity_Note_Title)
                {
                    Entity = DefaultNoteTitle
                };
            }

            // Create a new note object
            var note = new Note()
            {
                Title = title.Entity
            };

            // Add the new note to the list of notes and also save it in order to add text to it later
            noteToCreate = this.noteByTitle[note.Title] = note;

            // Prompt the user for what they want to say in the note
            PromptDialog.Text(context, After_TextPrompt, "What do you want to say in your note?");
        }
        public async Task Life(IDialogContext context, LuisResult result)
        {
            if (result.TopScoringIntent == null)
            {
                await None(context, result);

                return;
            }

            EntityRecommendation accountEntity = null;

            if (result.TryFindEntity("問句", out accountEntity))
            {
                if (result.TryFindEntity("時段::早上", out accountEntity))
                {
                    await context.PostAsync($"早上 吃手手");
                }
                else if (result.TryFindEntity("時段::中午", out accountEntity))
                {
                    await context.PostAsync($"中午 吃別人的手手");
                }
                else if (result.TryFindEntity("時段::晚上", out accountEntity))
                {
                    await context.PostAsync($"晚上 吃滿漢大餐");
                }
            }

            context.Wait(this.MessageReceived);
        }
예제 #20
0
        public async Task GetOrder(IDialogContext context, LuisResult result)
        {
            EntityRecommendation entity = result.Entities[0];
            string order = entity.Entity;

            context.Done(order);
        }
예제 #21
0
        public async Task GetWeatherData(IDialogContext context, LuisResult result)
        {
            EntityRecommendation location;

            if (!result.TryFindEntity("Location", out location) && !result.TryFindEntity("builtin.geography.city", out location))
            {
                PromptDialog.Text(context,
                                  SelectCity,
                                  "In which city do you want to know the weather forecast?");
            }
            else
            {
                context.UserData.SetValue("Location", location.Entity);
            }
            EntityRecommendation date;

            if (!result.TryFindEntity("builtin.datetime.date", out date) && !result.TryFindEntity("$datetime", out date))
            {
                date = new EntityRecommendation {
                    Type = "builtin.datetime.date", Resolution = new Dictionary <string, string> {
                        { "date", DateTime.Now.ToShortDateString().Replace(".", "-") }
                    }
                };
            }
            context.UserData.SetValue("Date", date.Resolution.FirstOrDefault().Value);
            if (location != null)
            {
                await GetWeatherForecast(context, result);
            }
        }
예제 #22
0
        private DateTime GetDate(List <EntityRecommendation> entities)
        {
            // Find the date the user specified
            EntityRecommendation dateEntity = null;
            DateTime             date       = new DateTime();

            if (entities.Any((entity) => entity.Type == luisDate))
            {
                dateEntity = entities.Where((entity) => entity.Type == luisDate).First();
                DateTime.TryParse(dateEntity.Entity, out date);
                // The user said something like "tomorrow" or "in two months"
                if (date.ToString() == defaultDate)
                {
                    DateTime.TryParse(dateEntity.Resolution.Values.FirstOrDefault(), out date);
                }
                // If the date is still the default date, the user said a month name like "May"
                if (date.ToString() == defaultDate)
                {
                    // Right now the date looks like "XXXX-04", we only want the month number so trim the rest
                    var trimMonth = dateEntity.Resolution.Values.FirstOrDefault().Remove(0, 5);
                    // Make the date the first of the month that the user entered
                    date = new DateTime(DateTime.UtcNow.Year, Int32.Parse(trimMonth), 1);
                }
                // If the user enters a date in the future, but doesn't specify the year it will be assumed to be this year
                // Because travel happens in the future not the past, add a year to account for this
                if (date < DateTime.UtcNow)
                {
                    date = date.AddYears(1);
                }
            }

            return(date);
        }
예제 #23
0
        public async Task ListInventory(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Looking for the lyrics for you...");

            string message = "";

            if (result.Entities.Count != 0)
            {
                EntityRecommendation ArtistEntity     = new EntityRecommendation();
                EntityRecommendation TrackTitleEntity = new EntityRecommendation();
                var test1 = result.TryFindEntity("Artist", out ArtistEntity);
                var test2 = result.TryFindEntity("TrackTitle", out TrackTitleEntity);

                string artist = "", keyword = "";
                if (test1)
                {
                    artist = ArtistEntity.Entity;
                }
                if (test2)
                {
                    keyword = TrackTitleEntity.Entity;
                }

                message = await GetLyrics(keyword, artist);

                await context.PostAsync(message);
            }
            else
            {
                await context.PostAsync("Sorry - couldn't find any lyrics for you");
            }

            context.Wait(MessageReceived);
        }
예제 #24
0
        private static JToken GetEntityValue(EntityRecommendation entity)
        {
            if (entity.Resolution == null)
            {
                return(entity.Entity);
            }

            if (entity.Type.StartsWith("builtin.datetimeV2."))
            {
                if (entity.Resolution?.Values == null || entity.Resolution.Values.Count == 0)
                {
                    return(JArray.FromObject(entity.Resolution));
                }

                var resolutionValues = (IEnumerable <object>)entity.Resolution.Values.First();
                var timexes          = resolutionValues.Select(value => ((IDictionary <string, object>)value)["timex"]);
                var distinctTimexes  = timexes.Distinct();
                return(JArray.FromObject(distinctTimexes));
            }

            if (entity.Type.StartsWith("builtin.number") || entity.Type.StartsWith("builtin.ordinal"))
            {
                var value = (string)entity.Resolution.Values.First();
                return(long.TryParse(value, out var longVal) ?
                       new JValue(longVal) :
                       new JValue(double.Parse(value)));
            }

            return(entity.Resolution.Count > 1 ?
                   JObject.FromObject(entity.Resolution) :
                   entity.Resolution.ContainsKey("value") ?
                   (JToken)JObject.FromObject(entity.Resolution["value"]) :
                   JArray.FromObject(entity.Resolution["values"]));
        }
예제 #25
0
        private static string GetTimeValueFromLuisResult(LuisResult result)
        {
            EntityRecommendation timeEntity = result.Entities.Where(e => e.Type == "builtin.datetimeV2.datetime").FirstOrDefault();
            var time = (((timeEntity?.Resolution?["values"]) as List <object>)?.FirstOrDefault() as Dictionary <string, object>)?["value"];

            return(time?.ToString());
        }
예제 #26
0
        private static string ExtractNormalizedEntityName(EntityRecommendation entity)
        {
            // Type::Role -> Role
            var type = entity.Type.Split(':').Last();

            if (type.StartsWith("builtin.datetimeV2."))
            {
                type = "datetime";
            }

            if (type.StartsWith("builtin.currency"))
            {
                type = "money";
            }

            if (type.StartsWith("builtin."))
            {
                type = type.Substring(8);
            }

            if (!string.IsNullOrWhiteSpace(entity.Role))
            {
                type = entity.Role;
            }

            return(type.Replace('.', '_').Replace(' ', '_'));
        }
        private static IEnumerable <T> GetRecommendationValues <T>(EntityRecommendation recommendation, string key)
        {
            List <object> resolutionList = (List <object>)recommendation.Resolution["values"];
            IEnumerable <Dictionary <string, object> > resolutionDictionaries = resolutionList.Cast <Dictionary <string, object> >();

            return(resolutionDictionaries.Select(resolutionDictionary => (T)Convert.ChangeType(resolutionDictionary[key], typeof(T))));
        }
예제 #28
0
        private async Task AfterGetMissingEntityFromUserAsync(IDialogContext context, IAwaitable <string> result)
        {
            string userInput = await result;

            // Vamos acrescentar a entidade faltante no objeto de LuisResult, restaura ele aqui
            LuisResult luisResult = context.UserData.GetValue <LuisResult>(UserDataKeys.LuisResult);

            // Também precisamos saber o tipo da entidade a ser obtida
            string entityToGet = context.UserData.GetValue <string>(UserDataKeys.EntityToGet);

            // Criamos a entidade com base no input do usuário, só vamos adicionar aqui o que interessa
            EntityRecommendation entityToAdd = new EntityRecommendation
            {
                Type   = entityToGet,
                Entity = userInput
            };

            // Adicionamos na coleção de entidades do LUIS
            var entities = new List <EntityRecommendation>(luisResult.Entities);

            entities.Add(entityToAdd);
            luisResult.Entities = entities;

            // E chamamos novamente o método IntentOrderFood, onde o LuisResult será revalidado
            await IntentOrderFood(context, luisResult);
        }
예제 #29
0
        public async Task FindAmount(IDialogContext context, LuisResult result)
        {
            IntentName = "BetValue";

            // Check if team Entity has been captured by the LUIS model
            EntityRecommendation team;

            if (!result.TryFindEntity(Entity_Team, out team))
            {
                team = new EntityRecommendation(type: Entity_Team)
                {
                    Entity = DefaultTeam
                };
                chatResponse = chatResponse + $"I didn't recognise a team. ";
            }

            // Check if date Entity has been captured by the LUIS model
            EntityRecommendation date;

            if (!result.TryFindEntity(Entity_Date, out date))
            {
                date = new EntityRecommendation(type: Entity_Date)
                {
                    Entity = DefaultDate
                };
                chatResponse = chatResponse + $"I'm not sure which year you want? ";
            }

            // Check if either of the Entities were not recognised
            if ((team.Entity == DefaultTeam) || (date.Entity == DefaultDate))
            {
                await context.PostAsync(chatResponse + $"Please ask me again.");

                // Wait for Bot input
                context.Wait(MessageReceived);
            }
            else
            {
                // Generate API URL string
                string api_request  = string.Join("/", IntentName, team.Entity, date.Entity);
                string api_response = "Computer says no!";
                // Send partial URL to the API
                api_response = await GetBQResult(api_request);

                // Check if response is an error
                if (api_response == "Error" || api_response == null || api_response == "")
                {
                    // Output to Bot
                    await context.PostAsync("I did not understand your request.");
                }
                else
                {
                    // Output to Bot
                    await context.PostAsync(api_response + " was gambled on " + team.Entity + " in " + date.Entity + ".");
                }
                // Wait for Bot input
                context.Wait(MessageReceived);
            }
        }
예제 #30
0
        private string getvalue(EntityRecommendation x)
        {
            IDictionary <string, object> s = x.Resolution;
            JArray ss = s["values"] as JArray;
            string t  = ss[0].ToString();

            return(t);
        }