Beispiel #1
0
        /// <summary>
        /// Process the response to present to the user.
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <string> ProcessResponse(Luis model)
        {
            string response = "";

            if (model.dialog != null)
            {
                if (model.dialog.status == "Question")
                {
                    response = model.dialog.prompt;
                }
            }
            else if (model.entities.Any())
            {
                var entity       = model.entities.FirstOrDefault();
                var resultFromDb = await entityManager.GetEntity(entity.entity);

                if (resultFromDb != null)
                {
                    response = resultFromDb.details;
                }
                else
                {
                    var url = "http://www.bing.com/search?q=" + model.query;
                    response = "My system don't have an answer for that but please try here: " + url;
                }
            }
            return(response);
        }
Beispiel #2
0
        //--------------------
        private static async Task <Luis> GetEntityFromLUIS(string query)
        {
            string entity = "nzd";

            query = Uri.EscapeDataString(query);
            CurrencyBotLUIS Data = new CurrencyBotLUIS();

            CurrencyBotLUIS.RootObject rootObject = new CurrencyBotLUIS.RootObject();
            using (HttpClient client = new HttpClient())
            {
                //string RequestURI = "https://api.projectoxford.ai/luis/v1/application?id=7f626790-38d6-4143-9d46-fe85c56a9016&subscription-key=09f80de609fa4698ab4fe5249321d165&q=" + query;
                string RequestURI       = "https://api.projectoxford.ai/luis/v2.0/apps/aacc4141-2867-46e4-889f-092bd124c14e?subscription-key=a3e835abd182441b93a1f3c40b8309aa&verbose=true&q=" + query;
                HttpResponseMessage msg = await client.GetAsync(RequestURI);

                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse = await msg.Content.ReadAsStringAsync();

                    Data       = JsonConvert.DeserializeObject <CurrencyBotLUIS>(JsonDataResponse);
                    rootObject = JsonConvert.DeserializeObject <CurrencyBotLUIS.RootObject>(JsonDataResponse);
                }
            }
            //rootObject = JsonConvert.DeserializeObject<WeatherObject.RootObject>(x); topScoringIntent
            string intent = rootObject.topScoringIntent.intent;
            double score  = rootObject.topScoringIntent.score;
            bool   found  = false;

            if (intent.ToLower().Contains("currencyconvert") && score >= 0.6)
            {
                intent = "currencyconvert";
                if (rootObject.entities.Count > 0)
                {
                    entity = rootObject.entities[0].entity;
                }
                else
                {
                    entity = "error";
                }
                found = true;
            }
            if (intent.ToLower().Contains("carbranch") && score >= 0.6)
            {
                intent = "carbranch";
                found  = true;
            }
            if (intent.ToLower().Contains("customeradd") && score >= 0.6)
            {
                intent = "customeradd";
                found  = true;
            }
            if (!found)
            {
                intent = "";
            }
            Luis result = new Luis();

            result.intent = intent;
            result.entity = entity;
            return(result);
        }
Beispiel #3
0
        private static async Task <Activity> GetLuisResponse(Activity message)
        {
            Activity resposta     = new Activity();
            var      luisResponse = await Luis.GetResponse(message.Text); //Call LUIS Service

            if (luisResponse != null)
            {
                var intent = new Intent();
                var entity = new Serialization.Entity();

                string acao    = string.Empty;
                string telcomm = string.Empty; //電信公司
                string phone   = string.Empty; //手機種類

                string entityType      = string.Empty;
                int    replaceStartPos = 0;
                foreach (var item in luisResponse.entities)
                {
                    entityType      = item.type;
                    replaceStartPos = entityType.IndexOf("::");
                    if (replaceStartPos > 0)
                    {
                        entityType = entityType.Substring(0, replaceStartPos);
                    }
                    switch (entityType)
                    {
                    case "電信公司":
                        telcomm = item.entity;
                        break;

                    case "手機種類":
                        phone = item.entity;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(telcomm))
                {
                    if (!string.IsNullOrEmpty(phone))
                    {
                        resposta = message.CreateReply($"好的! 這裡是您的 {telcomm}  {phone}方案");
                    }
                    else
                    {
                        resposta = message.CreateReply("你要 " + telcomm + "的方案,也請提供手機型號.");
                    }
                }
                else
                {
                    resposta = message.CreateReply("對不起不了解您問的,請輸入> [電信公司](ex:中華電信)的[手機型號](ex: ipone7)資費方案.");
                }
            }
            return(resposta);
        }
Beispiel #4
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;
            //    private static async void Response(IDialogContext context, Activity message)
            //{
            //  Activity activity = new Activity();
            var response = await Luis.GetResponse(activity.Text);

            if (response != null)
            {
                var intent = new Intent();
                var entity = new Entity1();

                string laptop  = string.Empty;
                string atm     = string.Empty;
                string service = string.Empty;

                foreach (var item in response.entities)
                {
                    switch (item.type.ToLower())
                    {
                    case "laptop repair":
                        laptop = item.entity;
                        break;

                    case "atm machine":
                        atm = item.entity;
                        break;

                    case "service line":
                        service = item.entity;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(laptop))
                {
                    // return our reply to the user
                    await context.PostAsync($"Hello, {laptop} available to A-3F, B-2F, D-3F");
                }
                else if (!string.IsNullOrEmpty(atm))
                {
                    await context.PostAsync($"Hello, {atm} available to A-Ground Floor, D-Cafeteria");
                }
                else if (!string.IsNullOrEmpty(service))
                {
                    await context.PostAsync($"Hello, {service} are SI, DD, AI ");
                }
                else
                {
                    await context.PostAsync($"No result found");
                }
            }
        }
        private static async Task <Message> Response(Message message)
        {
            Message resposta = new Message();
            var     response = await Luis.GetResponse(message.Text);

            if (response != null)
            {
                var intent = new Intent();
                var entity = new Entity();

                string acao         = string.Empty;
                string pessoa       = string.Empty;
                string agendaInf    = string.Empty;
                string agendaResult = string.Empty;

                foreach (var item in response.entities)
                {
                    switch (item.type)
                    {
                    case "Pessoa":
                        pessoa = item.entity;
                        break;

                    case "AgendaInf":
                        agendaInf = item.entity;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(pessoa))
                {
                    if (!string.IsNullOrEmpty(agendaInf))
                    {
                        resposta = message.CreateReplyMessage($"OK! Entendi, mostrando {agendaInf} de {pessoa}");
                    }
                    else
                    {
                        resposta = message.CreateReplyMessage("Não entendi qual informação vc quer do " + pessoa + ".");
                    }
                }
                else
                {
                    resposta = message.CreateReplyMessage("Não entendi qual a pessoa vc deseja a informação.");
                }
            }
            return(resposta);
        }
Beispiel #6
0
        /// <summary>
        /// Takes the user input and sends it to LUIS and deserialize the LUIS response to a model.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task <Luis> GetModelFromLuis(string query)
        {
            query = Uri.EscapeDataString(query);
            Luis model = new Luis();

            using (HttpClient client = new HttpClient())
            {
                string RequestURI       = luisEndPoint + appId + "&subscription-key=" + azureSubscriptionKey + "&q=" + query + "&timezoneOffset=0.0";
                HttpResponseMessage msg = await client.GetAsync(RequestURI);

                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse = await msg.Content.ReadAsStringAsync();

                    model = JsonConvert.DeserializeObject <Luis>(JsonDataResponse);
                }
            }
            return(model);
        }
        private static async Task <Activity> GetLuisResponse(Activity message)
        {
            Activity resposta = new Activity();

            var luisResponse = await Luis.GetResponse(message.Text); //Call LUIS Service

            if (luisResponse != null)
            {
                var intent = new Intent();
                var entity = new Serialization.Entity();

                string weather  = string.Empty;
                string location = string.Empty;

                string entityType = string.Empty;

                int replaceStartPos = 0;
                resposta = message.CreateReply("我不識字XD");

                foreach (var item in luisResponse.entities)
                {
                    entityType      = item.type;
                    replaceStartPos = entityType.IndexOf("::");
                    if (replaceStartPos > 0)
                    {
                        entityType = entityType.Substring(0, replaceStartPos);
                    }

                    switch (entityType)
                    {
                    case "天氣":
                        weather = item.entity;
                        break;

                    case "地點":
                        location = item.entity;
                        break;
                    }
                }
                resposta = message.CreateReply($"您在問的是〔{weather}〕,地點在〔{location}〕");
            }
            return(resposta);
        }
Beispiel #8
0
        private static async Task <string> Response(Activity message)
        {
            Activity output   = new Activity();
            var      response = await Luis.GetResponse(message.Text);

            if (response != null)
            {
                var    intent = new Intent();
                var    entity = new Serialization.Entity();
                String msg    = "Intent : " + System.Environment.NewLine;

                foreach (var item in response.intents)
                {
                    msg += item.intent + " , score = " + item.score + System.Environment.NewLine;
                }

                output = message.CreateReply(msg);
            }
            return(output.Text);
        }
        /// <summary>
        /// LuisViewModel constructor.
        /// Creates vision client, luis client, speech-to-text and text-to-speech clients, as well as ICommand objects
        /// </summary>
        public LuisViewModel()
        {
            _bingSearch = new BingSearch();

            _visionClient = new VisionServiceClient("FACE_API_KEY", "ROOT_URI");

            _luis = new Luis(new LuisClient("LUIS_APP_ID", "LUIS_API_KEY"));
            _luis.OnLuisUtteranceResultUpdated += OnLuisUtteranceResultUpdated;

            _sttClient = new SpeechToText(_bingApiKey);
            _sttClient.OnSttStatusUpdated += OnSttStatusUpdated;

            _ttsClient = new TextToSpeech();
            _ttsClient.OnAudioAvailable += OnTtsAudioAvailable;
            _ttsClient.OnError          += OnTtsError;
            GenerateHeaders();

            RecordUtteranceCommand  = new DelegateCommand(RecordUtterance);
            ExecuteUtteranceCommand = new DelegateCommand(ExecuteUtterance, CanExecuteUtterance);
        }
 public LuisViewModel()
 {
     _luis = new Luis(new LuisClient("APP_ID_HERE", "API_KEY_HERE", true));
     _luis.OnLuisUtteranceResultUpdated += OnLuisUtteranceResultUpdated;
     ExecuteUtteranceCommand             = new DelegateCommand(ExecuteUtterance, CanExecuteUtterance);
 }
Beispiel #11
0
        public static async Task buscar_producto(IDialogContext context, IAwaitable <object> result, Luis luis)
        {
            var message = await result as Activity;

            //await context.PostAsync("entites recome: ");// +luis.entities[0] );

            /*   await context.PostAsync("entites buscar: ");// + luis.entities[0]);
             *  if(luis.entities.Length>0)
             *      await context.PostAsync("entites buscar: "+ luis.entities[0]);  */
            //context.Wait(_RouterDialog.router);

            await BusquedasDialog.BusquedaGeneral(context, result);
        }
Beispiel #12
0
        public static async Task recomendacion(IDialogContext context, IAwaitable <object> result, Luis luis)
        {
            var message = await result as Activity;
            //await context.PostAsync("entites recome: ");// +luis.entities[0] );

            await context.PostAsync("¿Que pelicula estas buscando? ");

            context.Wait(BusquedasDialog.BusquedaGeneral_Result);

            //context.Wait(_RouterDialog.router);
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var response = String.Empty;
            List <Attachment> attachments = new List <Attachment>();

            var activity = await result as Activity;

            if (activity.Text != null)
            {
                //Envia dados para Application Insights Analytics
                TelemetryClient telemetry  = new TelemetryClient();
                var             properties = new Dictionary <string, string> {
                    { "Question", activity.Text }, { "Dialog", "Informações Básicas" }
                };
                if (activity.From != null)
                {
                    properties.Add("Name", activity.From.Name);
                    properties.Add("Channel", activity.ChannelId);
                    properties.Add("IdChatbot", activity.From.Id);
                }
                telemetry.TrackEvent("BotQuestion", properties);
                //

                //Call API LUIS (Language Understanding Intelligent Service)
                var responseLUIS = await Luis.GetResponse(activity);

                if (responseLUIS != null)
                {
                    //Intenção com a melhor pontuação
                    var intent = responseLUIS.topScoringIntent;

                    dynamic retorno = null;

                    //Verifica se a intent tem um score suficiente para ser usado
                    if (!string.IsNullOrEmpty(intent.intent) && intent.intent.ToUpper() != "NONE" && intent.score >= 0.30) //30%
                    {
                        var item = loginUser;

                        if (item != null)
                        {
                            var client = new FacebookClient();
                            client.AccessToken = item.AccessTokenFacebook.AccessToken;
                            client.Version     = "v2.10";
                            client.AppId       = ConfigurationManager.AppSettings["appIdFacebook"];
                            client.AppSecret   = ConfigurationManager.AppSettings["appSecretFacebook"];

                            if (intent.intent.Equals("hometown")) //Casos em que eu preciso de mais de uma propriedade
                            {
                                retorno = client.Get("me?fields=" + intent.intent + ",location");
                            }
                            else if (intent.intent.Equals("picture"))
                            {
                                retorno = client.Get("me?fields=" + intent.intent + ",about");
                            }
                            else
                            {
                                retorno = client.Get("me?fields=" + intent.intent);
                            }

                            if (retorno.Count > 1)
                            {
                                switch (intent.intent)
                                {
                                case "name":
                                    response = "Meu nome é " + retorno.name + ", prazer em conhecê-lo! \U0001F600";

                                    break;

                                case "birthday":
                                    string birthday = retorno.birthday;

                                    if (birthday.Count() == 10)
                                    {
                                        DateTime dataNasc = Convert.ToDateTime(birthday, CultureInfo.CreateSpecificCulture("en-US"));
                                        string   format   = "dd/MM/yyyy";

                                        // Retorna o número de anos
                                        int anos = DateTime.Now.Year - dataNasc.Year;

                                        // Se a data de aniversário não ocorreu ainda este ano, subtrair um ano a partir da idade
                                        if (DateTime.Now.Month < dataNasc.Month || (DateTime.Now.Month == dataNasc.Month && DateTime.Now.Day < dataNasc.Day))
                                        {
                                            anos--;
                                        }

                                        response = "Eu nasci em " + dataNasc.ToString(format) + ", tenho " + anos + " anos!";
                                    }

                                    break;

                                case "email":
                                    response = "Você pode me contatar no e-mail " + retorno.email + " \U0001F609";

                                    break;

                                case "education":
                                    foreach (var educ in retorno.education)
                                    {
                                        if (string.IsNullOrEmpty(response))
                                        {
                                            response += educ.type + " - " + educ.school.name;
                                        }
                                        else
                                        {
                                            response += "\n" + educ.type + " - " + educ.school.name;
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(response))
                                    {
                                        response = ("Este é o meu histórico de ensino:\n\n" + response);
                                    }

                                    break;

                                case "hometown":
                                    if (retorno.Count == 3)
                                    {
                                        if (retorno.hometown.name == retorno.location.name)
                                        {
                                            response = "Eu moro em " + retorno.location.name;
                                        }
                                        else
                                        {
                                            response = "Eu sou de " + retorno.hometown.name + ", mas moro em " + retorno.location.name;
                                        }
                                    }

                                    break;

                                case "interested_in":
                                    string[] generos = new string[retorno.interested_in.Count];

                                    for (int i = 0; i < generos.Length; i++)
                                    {
                                        if (retorno.interested_in[i] == "female")
                                        {
                                            generos[i] = "Mulheres";
                                        }
                                        else if (retorno.interested_in[i] == "male")
                                        {
                                            generos[i] = "Homens";
                                        }
                                        else
                                        {
                                            generos[i] = retorno.interested_in[i];
                                        }
                                    }

                                    response = "Estou interessado em " + string.Join(", ", generos);

                                    break;

                                case "languages":
                                    foreach (var language in retorno.languages)
                                    {
                                        if (response == "")
                                        {
                                            response += language.name;
                                        }
                                        else
                                        {
                                            response += ", " + language.name;
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(response))
                                    {
                                        response = "Eu falo " + response;
                                    }

                                    break;

                                case "relationship_status":
                                    response = "Vou responder essa em Inglês: I'm currently " + retorno.relationship_status;

                                    break;

                                case "religion":
                                    response = "Falando em religião, a minha é " + retorno.religion;

                                    break;

                                case "website":
                                    response = "Meu site na web é " + retorno.website;

                                    break;

                                case "picture":
                                    if (retorno.Count == 3)
                                    {
                                        string about = retorno.about;

                                        List <CardImage> cardImages = new List <CardImage>();
                                        cardImages.Add(new CardImage(url: retorno.picture.data.url));

                                        ThumbnailCard plCard = new ThumbnailCard()
                                        {
                                            Title  = "Este sou eu! \U0001F603",
                                            Text   = about,
                                            Images = cardImages,
                                        };

                                        Attachment attachment = plCard.ToAttachment();
                                        attachments.Add(attachment);
                                    }
                                    else
                                    {
                                        response = "Este sou eu! \U0001F603";
                                        attachments.Add(new Attachment {
                                            ContentType = "image/jpg", ContentUrl = retorno.picture.data.url
                                        });
                                    }

                                    break;

                                case "work":
                                    foreach (var work in retorno.work)
                                    {
                                        string position = "";
                                        try
                                        {
                                            if (work.position.Count > 0)
                                            {
                                                position = work.position.name;
                                            }
                                        }
                                        catch (Exception ex) { }

                                        if (string.IsNullOrEmpty(response))
                                        {
                                            if (string.IsNullOrEmpty(position))
                                            {
                                                response += work.employer.name;
                                            }
                                            else
                                            {
                                                response += position + " - " + work.employer.name;
                                            }
                                        }
                                        else
                                        {
                                            if (string.IsNullOrEmpty(position))
                                            {
                                                response += "\n" + work.employer.name;
                                            }
                                            else
                                            {
                                                response += "\n" + position + " - " + work.employer.name;
                                            }
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(response))
                                    {
                                        response = ("Estas são as minhas experiências profissionais em ordem decrescente de período:\n\n" + response);
                                    }

                                    break;

                                case "political":
                                    response = retorno.political;

                                    break;

                                case "family":
                                    foreach (var family in retorno.family.data)
                                    {
                                        if (string.IsNullOrEmpty(response))
                                        {
                                            response = family.name + " (" + family.relationship + ")";
                                        }
                                        else
                                        {
                                            response += "\n" + family.name + " (" + family.relationship + ")";
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(response))
                                    {
                                        response = ("Estes são alguns membros da minha família:\n\n" + response);
                                    }

                                    break;

                                default:
                                    response = "Desculpe! Não estou habilitado para falar sobre isso \U0001F614";

                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        response = "Desculpe! Analisei a sua pergunta e não entendi muito bem a sua solicitação \U0001F630";
                    }
                }
            }
            else
            {
                response = "Não estou capacitado para entender este tipo de solicitação, desculpe! \U0001F61E";
            }

            if (string.IsNullOrEmpty(response) && attachments.Count == 0)
            {
                response = "Minhas pesquisas não retornaram um valor satisfatório, talvez a informação não esteja habilitada pra mim \U0001F615";
            }

            var reply = activity.CreateReply(response);

            reply.Type        = ActivityTypes.Message;
            reply.TextFormat  = TextFormatTypes.Plain;
            reply.Attachments = attachments;

            // return our reply to the user
            await context.PostAsync(reply);

            context.Wait(this.MessageReceivedAsync);
        }
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            var rand = new Random();

            string[] defaultMessages = { "Estes são alguns resultados que encontrei:",
                                         "Aqui estão alguns dos principais resultados sobre isso:",
                                         "Eu gosto disso, fique à vontade para saber mais:" };
            var      reply = activity.CreateReply(defaultMessages[rand.Next(defaultMessages.Count())]);

            reply.Type             = ActivityTypes.Message;
            reply.TextFormat       = TextFormatTypes.Plain;
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Attachments      = new List <Attachment>();

            var item = loginUser;

            if (item != null)
            {
                var client = new FacebookClient();
                client.AccessToken = item.AccessTokenFacebook.AccessToken;
                client.Version     = "v2.10";
                client.AppId       = ConfigurationManager.AppSettings["appIdFacebook"];
                client.AppSecret   = ConfigurationManager.AppSettings["appSecretFacebook"];

                dynamic retorno = null;

                //Verifica se foi solicitado algum interesse via pergunta
                if (activity.Text != null)
                {
                    //Envia dados para Application Insights Analytics
                    TelemetryClient telemetry  = new TelemetryClient();
                    var             properties = new Dictionary <string, string> {
                        { "Question", activity.Text }, { "Dialog", "Interesses" }
                    };
                    if (activity.From != null)
                    {
                        properties.Add("Name", activity.From.Name);
                        properties.Add("Channel", activity.ChannelId);
                        properties.Add("IdChatbot", activity.From.Id);
                    }
                    telemetry.TrackEvent("BotQuestion", properties);
                    //

                    string[] words = activity.Text.Split(' ');
                    if (words.Length > 1)
                    {
                        //Call API LUIS (Language Understanding Intelligent Service)
                        var responseLUIS = await Luis.GetResponse(activity);

                        //Trata resposta (DEVE SER CRIADO EM UM OUTRO MÉTODO)
                        if (responseLUIS != null)
                        {
                            var intent = responseLUIS.topScoringIntent;

                            if (!string.IsNullOrEmpty(intent.intent) && intent.intent.ToUpper() != "NONE" && intent.score >= 0.30) //30%
                            {
                                activity.Text = intent.intent;
                            }
                        }
                    }

                    switch (activity.Text.ToUpper())
                    {
                    /*case "Amigos":
                     *  reply.AttachmentLayout = AttachmentLayoutTypes.List;
                     *
                     *  retorno = client.Get("me/friends?fields=name");
                     *
                     *  List<CardElement> cardElements = new List<CardElement>();
                     *
                     *  foreach (var friend in retorno.data)
                     *  {
                     *      cardElements.Add(new TextBlock { Text = friend.name, Size = TextSize.Small });
                     *  }
                     *
                     *  AdaptiveCard adaptiveCard = new AdaptiveCard()
                     *  {
                     *      Body = cardElements
                     *  };
                     *
                     *  reply.Attachments.Add(new Attachment { ContentType = "application/vnd.microsoft.card.adaptive", Content = adaptiveCard });
                     *
                     *  break;*/
                    case "ATLETAS":
                    case "ATHLETES":
                        reply.AttachmentLayout = AttachmentLayoutTypes.List;

                        retorno = client.Get("me?fields=favorite_athletes");

                        if (retorno.Count > 1)
                        {
                            foreach (var athlete in retorno.favorite_athletes)
                            {
                                HeroCard plCard = new HeroCard()
                                {
                                    Title = athlete.name
                                };

                                Attachment attachment = plCard.ToAttachment();
                                reply.Attachments.Add(attachment);
                            }
                        }

                        break;

                    case "ESPORTES":
                    case "SPORTS":
                        reply.AttachmentLayout = AttachmentLayoutTypes.List;

                        retorno = client.Get("me?fields=sports");

                        if (retorno.Count > 1)
                        {
                            foreach (var sport in retorno.sports)
                            {
                                HeroCard plCard = new HeroCard()
                                {
                                    Title = sport.name
                                };

                                Attachment attachment = plCard.ToAttachment();
                                reply.Attachments.Add(attachment);
                            }
                        }

                        break;

                    case "EVENTOS":
                    case "EVENTS":
                        retorno = client.Get("me/events?fields=name,cover,id");

                        foreach (var evento in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                cardImages.Add(new CardImage(url: evento.cover.source));
                            }
                            catch (Exception ex) { }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = "https://www.facebook.com/events/" + evento.id,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            HeroCard plCard = new HeroCard()
                            {
                                Title   = evento.name,
                                Images  = cardImages,
                                Buttons = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "FILMES":
                    case "MOVIES":
                        //FILMES JÁ ASSISTIDOS:
                        //retorno = client.Get("me/video.watches?fields=data");
                        retorno = client.Get("me/movies?fields=name,genre,about,description,link,cover");

                        foreach (var movie in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                cardImages.Add(new CardImage(url: movie.cover.source));
                            }
                            catch (Exception ex) { }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = movie.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            HeroCard plCard = new HeroCard()
                            {
                                Title    = movie.name,
                                Subtitle = movie.genre,
                                Text     = !string.IsNullOrEmpty(movie.description) ? movie.description : movie.about,
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "FOTOS":
                    case "PHOTOS":
                        retorno = client.Get("me/photos?fields=name,link,images");

                        foreach (var photo in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            cardImages.Add(new CardImage(url: photo.images[0].source));

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = photo.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            HeroCard plCard = new HeroCard()
                            {
                                Subtitle = photo.name,
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);

                            //ADAPTIVECARD : http://adaptivecards.io/explorer/#ActionOpenUrl

                            /*List<CardElement> cardElements = new List<CardElement>();
                             * cardElements.Add(new Image { Url = photo.picture.data.url, Size = ImageSize.Large, HorizontalAlignment = HorizontalAlignment.Center });
                             * cardElements.Add(new TextBlock { Text = photo.name, Size = TextSize.Small });
                             *
                             * List<ActionBase> cardActions = new List<ActionBase>();
                             * cardActions.Add(new OpenUrlAction { Url = photo.link, Title = "Mais Informações" });
                             *
                             * AdaptiveCard adaptiveCard = new AdaptiveCard()
                             * {
                             *  Body = cardElements,
                             *  Actions = cardActions
                             * };
                             *
                             * Attachment attachment = new Attachment();
                             * attachment.ContentType = "application/vnd.microsoft.card.adaptive";
                             * attachment.Content = adaptiveCard;*/
                        }

                        break;

                    case "GOSTOS":
                    case "LIKES":
                        reply.AttachmentLayout = AttachmentLayoutTypes.List;

                        retorno = client.Get("me/likes?fields=name,about,picture");

                        foreach (var like in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                cardImages.Add(new CardImage(url: like.picture.data.url));
                            }
                            catch (Exception ex) { }

                            ThumbnailCard plCard = new ThumbnailCard()
                            {
                                Title    = like.name,
                                Subtitle = like.about,
                                Images   = cardImages
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "JOGOS":
                    case "GAMES":
                        retorno = client.Get("me/games?fields=name,link,picture,description,category");

                        foreach (var game in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                cardImages.Add(new CardImage(url: game.picture.data.url));
                            }
                            catch (Exception ex) { }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = game.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            ThumbnailCard plCard = new ThumbnailCard()
                            {
                                Title    = game.name,
                                Subtitle = game.category,
                                Text     = game.description,
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "LIVROS":
                    case "BOOKS":
                        //LIVROS JÁ LIDOS:
                        //retorno = client.Get("me/books.reads?fields=data");
                        retorno = client.Get("me/books?fields=name,description,link,picture,about");

                        foreach (var book in retorno.data)
                        {
                            /*List<CardImage> cardImages = new List<CardImage>();
                             * cardImages.Add(new CardImage(url: book.picture.data.url));*/

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = book.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            HeroCard plCard = new HeroCard()
                            {
                                Title = book.name,
                                Text  = !string.IsNullOrEmpty(book.description) ? book.description : book.about,
                                //Images = cardImages,
                                Buttons = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "LUGARES":
                    case "PLACES":
                        retorno = client.Get("me/tagged_places?fields=name,place");

                        var apiKey = ConfigurationManager.AppSettings["BingMapsApiKey"];

                        List <Models.Location> locations = new List <Models.Location>();
                        foreach (var place in retorno.data)
                        {
                            if (place.place.location != null)
                            {
                                Models.Location location = new Models.Location();

                                Models.GeocodePoint geocodePoint = new Models.GeocodePoint();
                                geocodePoint.Coordinates = new List <double>();
                                geocodePoint.Coordinates.Add(place.place.location.latitude);     //latitude
                                geocodePoint.Coordinates.Add(place.place.location.longitude);    //longitude

                                location.Point = geocodePoint;
                                location.Name  = place.place.name;

                                try
                                {
                                    string endereco = "";
                                    if (!string.IsNullOrEmpty(place.place.location.street))
                                    {
                                        endereco = place.place.location.street;
                                    }

                                    if (!string.IsNullOrEmpty(place.place.location.city) && !string.IsNullOrEmpty(place.place.location.state))
                                    {
                                        if (string.IsNullOrEmpty(endereco))
                                        {
                                            endereco += place.place.location.city + "/" + place.place.location.state;
                                        }
                                        else
                                        {
                                            endereco += " - " + place.place.location.city + "/" + place.place.location.state;
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(place.place.location.country))
                                    {
                                        if (string.IsNullOrEmpty(endereco))
                                        {
                                            endereco += place.place.location.country;
                                        }
                                        else
                                        {
                                            endereco += " - " + place.place.location.country;
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(endereco))
                                    {
                                        location.Name += " (" + endereco + ")";
                                    }
                                }
                                catch (Exception ex) { }

                                locations.Add(location);
                            }
                        }

                        var cards = new List <HeroCard>();
                        int i     = 1;
                        foreach (var location in locations)
                        {
                            var heroCard = new HeroCard
                            {
                                Subtitle = location.Name
                            };

                            if (location.Point != null)
                            {
                                var image = new CardImage(
                                    url: new BingGeoSpatialService(apiKey).GetLocationMapImageUrl(location, i)
                                    );

                                heroCard.Images = new[] { image };

                                NumberFormatInfo nfi = new NumberFormatInfo();
                                nfi.NumberDecimalSeparator = ".";

                                var button = new CardAction(
                                    type: "openUrl",
                                    title: "Abrir no Google Maps",
                                    value: "https://maps.google.com/maps?ll=" + location.Point.Coordinates[0].ToString(nfi) + "," + location.Point.Coordinates[1].ToString(nfi)
                                    );

                                heroCard.Buttons = new[] { button };
                            }

                            cards.Add(heroCard);

                            i++;
                        }

                        foreach (var card in cards)
                        {
                            reply.Attachments.Add(card.ToAttachment());
                        }

                        break;

                    case "MÚSICAS":
                    case "MUSICAS":
                    case "MUSIC":
                        //MÚSICAS JÁ ESCUTADAS:
                        //retorno = client.Get("me/music.listens?fields=data");
                        retorno = client.Get("me/music?fields=name,about,link,picture,genre");

                        foreach (var music in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                cardImages.Add(new CardImage(url: music.picture.data.url));
                            }
                            catch (Exception ex) { }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = music.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            ThumbnailCard plCard = new ThumbnailCard()
                            {
                                Title    = music.name,
                                Subtitle = music.genre,
                                Text     = music.about,
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "TELEVISÃO":
                    case "TELEVISAO":
                    case "TELEVISION":
                        //PROGRAMAS DE TV JÁ ASSISTIDOS:
                        //retorno = client.Get("me/video.watches?fields=data");
                        retorno = client.Get("me/television?fields=name,genre,description,link,cover,about");

                        foreach (var tv in retorno.data)
                        {
                            List <CardImage> cardImages = new List <CardImage>();
                            try
                            {
                                if (tv.cover.Count > 0)
                                {
                                    cardImages.Add(new CardImage(url: tv.cover.source));
                                }
                            }
                            catch (Exception ex) { }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = tv.link,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            HeroCard plCard = new HeroCard()
                            {
                                Title    = tv.name,
                                Subtitle = tv.genre,
                                Text     = !string.IsNullOrEmpty(tv.description) ? tv.description : tv.about,
                                Images   = cardImages,
                                Buttons  = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;

                    case "TIMES":
                    case "TEAMS":
                        reply.AttachmentLayout = AttachmentLayoutTypes.List;

                        retorno = client.Get("me?fields=favorite_teams");

                        if (retorno.Count > 1)
                        {
                            foreach (var team in retorno.favorite_teams)
                            {
                                HeroCard plCard = new HeroCard()
                                {
                                    Title = team.name
                                };

                                Attachment attachment = plCard.ToAttachment();
                                reply.Attachments.Add(attachment);
                            }
                        }

                        break;

                    case "VÍDEOS":
                    case "VIDEOS":
                        retorno = client.Get("me/videos?fields=description,source,permalink_url,thumbnails");

                        foreach (var video in retorno.data)
                        {
                            ThumbnailUrl image = new ThumbnailUrl();
                            image.Url = video.thumbnails.data[0].uri;
                            foreach (var thumbnail in video.thumbnails.data)
                            {
                                if (thumbnail.is_preferred)
                                {
                                    image.Url = thumbnail.uri;
                                    break;
                                }
                            }

                            List <CardAction> cardButtons = new List <CardAction>();
                            cardButtons.Add(new CardAction()
                            {
                                Value = "https://www.facebook.com" + video.permalink_url,
                                Type  = "openUrl",
                                Title = "Mais Informações"
                            });

                            List <MediaUrl> mediaUrl = new List <MediaUrl>();
                            mediaUrl.Add(new MediaUrl(url: video.source));

                            VideoCard plCard = new VideoCard()
                            {
                                Title   = video.description,
                                Media   = mediaUrl,
                                Image   = image,
                                Buttons = cardButtons
                            };

                            Attachment attachment = plCard.ToAttachment();
                            reply.Attachments.Add(attachment);
                        }

                        break;
                    }
                }
            }

            if (reply.Attachments.Count == 0)
            {
                reply.Text = "Desculpe! Eu não encontrei nada sobre isso ou não estou capacitado para entender esse tipo de solicitação \U0001F61E";
            }

            await context.PostAsync(reply);

            context.Wait(this.MessageReceivedAsync);
        }
Beispiel #15
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)

        {
            var activity = await result as Activity;
            var response = await Luis.GetResponse(activity.Text);

            if (response != null)
            {
                List <string> entities = new List <string>();
                foreach (var item in response.entities)
                {
                    entities.Add(item.type);
                }
                var matchedTag = FindXmlConfigurationMatchingNode(entities);
                var infoToUser = CreditCardDetails();
                // Later to remove if else else if
                if (matchedTag.Classic)
                {
                    if (matchedTag.Benefits || matchedTag.Rewards)
                    {
                        await context.PostAsync($" {infoToUser.Classic.ClassicInformation.Rewards}");
                    }
                    else if (matchedTag.CreditLimit || matchedTag.CardLimit)
                    {
                        await context.PostAsync($" {infoToUser.Classic.ClassicInformation.CardLimit} ");
                    }
                    else if (matchedTag.Eligibility)
                    {
                        await context.PostAsync($" {infoToUser.Classic.ClassicInformation.Eligibility}");
                    }
                    else if (matchedTag.InterestRate)
                    {
                        await context.PostAsync($"{infoToUser.Classic.ClassicInformation.InterestRates}");
                    }
                    else if (matchedTag.Fee)
                    {
                        await context.PostAsync($"{infoToUser.Classic.ClassicInformation.AnnualFee} for a classic card");
                    }
                    else if (matchedTag.Features)
                    {
                        await context.PostAsync($"{infoToUser.Classic.ClassicInformation.Features} ");
                    }
                    else
                    {
                        await context.PostAsync($"Hello, Classic card has the following features - \n\nAnnual Fees - {infoToUser.Classic.ClassicInformation.AnnualFee} \n\n CardLimit is {infoToUser.Classic.ClassicInformation.CardLimit} AUD \n\n To be eligible {infoToUser.Classic.ClassicInformation.Eligibility} \n\n {infoToUser.Classic.ClassicInformation.InterestRates}");
                    }
                }
                else if (matchedTag.Platinum)
                {
                    if (matchedTag.Benefits || matchedTag.Rewards)
                    {
                        await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.Rewards}");
                    }
                    else if (matchedTag.Eligibility)
                    {
                        await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.Eligibility}");
                    }
                    else if (matchedTag.CreditLimit || matchedTag.CardLimit)
                    {
                        await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.CardLimit}");
                    }
                    else if (matchedTag.InterestRate)
                    {
                        await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.InterestRates}");
                    }
                    else if (matchedTag.Fee)
                    {
                        await context.PostAsync($" {infoToUser.Platinum.PlatinumInformation.AnnualFee} ");
                    }
                    else if (matchedTag.Features)
                    {
                        await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.Features} ");
                    }

                    else
                    {
                        await context.PostAsync($"Hello, Platinum card has the following features - \n\nAnnual Fees - {infoToUser.Platinum.PlatinumInformation.AnnualFee} \n\n CardLimit is {infoToUser.Platinum.PlatinumInformation.CardLimit} AUD \n\n To be eligible {infoToUser.Platinum.PlatinumInformation.Eligibility} \n\n {infoToUser.Platinum.PlatinumInformation.InterestRates}");
                    }
                }
                else if ((matchedTag.Rewards && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.Platinum.PlatinumInformation.Rewards}");
                }
                else if ((matchedTag.Benefits && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.Benefits}");
                }
                else if ((matchedTag.Features && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.Features}");
                }
                else if ((matchedTag.InterestRate && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.InterestRates}");
                }
                else if ((matchedTag.AnnualFee && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.AnnualFee}");
                }
                else if ((matchedTag.CardLimit && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.CardLimit}");
                }
                else if ((matchedTag.Rewards && matchedTag.CreditCard))
                {
                    await context.PostAsync($"{infoToUser.Rewards}");
                }
                else if ((matchedTag.CreditCard && matchedTag.CCInformation) || matchedTag.CreditCard)
                {
                    await context.PostAsync($" {infoToUser.CardType} ");
                }
                else
                {
                    await context.PostAsync($"Help us to query your question, refine youe question.");
                }
            }
        }
Beispiel #16
0
        private static async Task<Luis> GetEntityFromLUIS(string Query)
        {
            Query = Uri.EscapeDataString(Query);
            Luis Data = new Luis();
            using (HttpClient client = new HttpClient())
            {
                string RequestURI = "https://api.projectoxford.ai/luis/v1/application?id=6510dc6d-c79d-402d-994a-419164f25627&subscription-key=5455eb8082b9465282db6623b157d8a0&q=" + Query;
                HttpResponseMessage msg = await client.GetAsync(RequestURI);

                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse = await msg.Content.ReadAsStringAsync();
                    Data = JsonConvert.DeserializeObject<Luis>(JsonDataResponse);
                }
            }
            return Data;
        }
Beispiel #17
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            //------------- added 22 Nov 2016
            #region Set CurrentBaseURL and ChannelAccount
            // Get the base URL that this service is running at
            // This is used to show images
            string currentBaseURL =
                this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", "");

            // Create an instance of BotData to store data
            BotData objBotData = new BotData();

            // Instantiate a StateClient to save BotData
            StateClient stateClient = activity.GetStateClient();

            // Use stateClient to get current userData
            BotData userData = await stateClient.BotState.GetUserDataAsync(
                activity.ChannelId, activity.From.Id);

            // Update userData by setting CurrentBaseURL and Recipient
            //userData.SetProperty<string>("CurrentBaseURL", currentBaseURL);

            // Save changes to userData
            //await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
            #endregion
            //------------- end of added 22 Nov
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                var userMessage = activity.Text;

                //StateClient stateClient = activity.GetStateClient();
                //BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
                // *************************
                // Log to Database
                // *************************
                // Instantiate the BotData dbContext
                CombinedBotDBEntities DB = new CombinedBotDBEntities();
                // Create a new MessageLog object
                MessageLog NewMsgLog = new MessageLog();
                // Set the properties on the MessageLog object
                NewMsgLog.Channel  = activity.ChannelId;
                NewMsgLog.UserID   = activity.From.Id;
                NewMsgLog.UserName = activity.From.Name;
                NewMsgLog.Created  = DateTime.UtcNow;
                NewMsgLog.Message  = activity.Text.Truncate(500);
                // Add the MessageLog object to MessageLogs
                DB.MessageLogs.Add(NewMsgLog);
                // Save the changes to the database
                DB.SaveChanges();
                //----------------
                string endOutput          = "Hi";
                bool   textAnswer         = true;
                bool   needtoSaveUserData = false;
                bool   sentGreeting       = userData.GetProperty <bool>("SentGreeting");
                int    capacity           = userData.GetProperty <int>("Capacity");
                string hiringDay          = userData.GetProperty <string>("HiringDay");
                string customerAdd        = userData.GetProperty <string>("CustomerAdd");
                int    selectedCarId      = userData.GetProperty <int>("SelectedCarId");
                bool   resetFlag          = false;
                //-------- local variables
                int    carPrice = 0;
                string carName  = "";
                //----------------
                if (userMessage.ToLower().Contains("reset"))
                {
                    sentGreeting  = false;
                    capacity      = 0;
                    hiringDay     = "";
                    customerAdd   = "";
                    selectedCarId = 0;
                    //userData.SetProperty<bool>("SentGreeting", sentGreeting);
                    userData.SetProperty <int>("Capacity", capacity);
                    userData.SetProperty <string>("HiringDay", hiringDay);
                    userData.SetProperty <string>("CustomerAdd", customerAdd);
                    userData.SetProperty <int>("SelectedCarId", selectedCarId);
                    //endOutput = "The conversation has just been restarted from beggining.";
                    needtoSaveUserData = true;
                    resetFlag          = true;
                }
                //sentGreeting = false;
                //resetFlag = true;   // for debugging on server
                if (!resetFlag)
                {
                    //---- try to detect several basic input commands first
                    if (capacity <= 0)
                    {
                        bool result = Int32.TryParse(userMessage, out capacity);
                        if (result)
                        {
                            userData.SetProperty <int>("Capacity", capacity);
                            needtoSaveUserData = true;
                        }
                    }
                    else if (capacity > 0 && selectedCarId <= 0)
                    {
                        bool result = Int32.TryParse(userMessage, out selectedCarId);
                        if (result)
                        {
                            userData.SetProperty <int>("SelectedCarId", selectedCarId);
                            needtoSaveUserData = true;
                        }
                    }
                }
                if (!sentGreeting)
                {
                    sentGreeting = true;
                    endOutput    = "Hello. What can I help you with?";
                    userData.SetProperty <bool>("SentGreeting", sentGreeting);
                    needtoSaveUserData = true;
                    //await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                }
                else //if (1==2)
                {
                    if (userMessage.ToLower().Contains("hire"))
                    {
                        endOutput = "Great! Thanks for choosing our service.";
                    }
                    if (capacity <= 0)
                    {
                        endOutput += " You need a car for how many people?";
                    }
                    if (capacity > 0 && selectedCarId <= 0)
                    {
                        endOutput = "You need " + capacity.ToString() + " seats. We have above vehicles that match your requirements, please select one.";
                        //list cars here
                        HttpResponseMessage x = await ListAllCars(capacity, currentBaseURL, activity, connector);

                        //bool x = await ListAllCars(capacity, currentBaseURL, activity, connector);
                    }
                    if (selectedCarId > 0)
                    {
                        bool carFound = Common.GetCarInfo(selectedCarId, ref carPrice, ref carName);
                        if (carFound)
                        {
                            endOutput = "You selected the car " + carName + " (ID=" + selectedCarId.ToString() + "). A very smart choice! The hiring fee is $" + carPrice + "NZD per day";
                        }
                        else
                        {
                            endOutput = "Your selected car cannot be found. Please type reset to restart again.";
                        }
                    }
                    Luis question = await GetEntityFromLUIS(userMessage);

                    //endOutput = question.intent;
                    if (question.intent == "currencyconvert" && carPrice > 0)
                    {
                        string convCarPrice = await GetExchange(question.entity, carPrice);

                        endOutput = convCarPrice;
                    }
                    if (question.intent == "carbranch" && (customerAdd == null || customerAdd == "")) //&& question.intent != "customeradd")
                    {
                        endOutput = "We have two branches in the city. Where are you living now?";
                    }
                    if (question.intent == "customeradd" && (customerAdd == null || customerAdd == ""))
                    {
                        customerAdd = userMessage;
                        // send recommendation about branch address
                        endOutput = await BranchRecommendation(customerAdd);
                    }
                }
                if (textAnswer)
                {
                    if (needtoSaveUserData)
                    {
                        await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
                    }
                    // *************************
                    // Log to Database
                    // *************************
                    //endOutput= endOutput+ "-" + activity.ChannelId.ToString() + "-" + activity.From.Id + "-" + activity.From.Name;
                    // return our reply to the user
                    Activity infoReply = activity.CreateReply(endOutput);
                    // Set the properties on the MessageLog object
                    //NewMsgLog.Channel = infoReply.ChannelId;  // This part doesn't work, need to be checked
                    //NewMsgLog.UserID = infoReply.From.Id;
                    //NewMsgLog.UserName = infoReply.From.Name;
                    NewMsgLog.Channel  = activity.ChannelId;
                    NewMsgLog.UserID   = activity.From.Id;
                    NewMsgLog.UserName = activity.From.Name;
                    NewMsgLog.Created  = DateTime.UtcNow;
                    NewMsgLog.Message  = infoReply.Text.Truncate(500);
                    // Add the MessageLog object to MessageLogs
                    DB.MessageLogs.Add(NewMsgLog);
                    // Save the changes to the database
                    DB.SaveChanges();
                    await connector.Conversations.ReplyToActivityAsync(infoReply);
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return(response);
        }
        static async Task Main(string[] args)
        {
            bool       add        = true;
            bool       repeat     = true;
            LuisParams luisParams = new LuisParams
            {
                AppId     = "<App Key>",
                VersionId = "<App version e.g 0.1>",
                SubsKey   = "<Luis Primary key>",
                //this is only used when you have already the ID
                PhraseListId = "<Luis PhaseList ID>",
                Endpoint     = Region.WestEurope
            };
            ILuis luis = new Luis(luisParams);

            //// This step is one Time only to get a phaselist ID in order to use it as param for the  RelatedValuesAsync method
            ////CreatePhaseListAsync method doesn't need the PhraseListId as property in the luisParams object
            ////In case of lost of the phaseListID you can use the overrided method of CreatePhaseListAsync by passing a name for your phaselist. exmaple .CreatePhaseListAsync("phaseListTest")
            //int phaseListID = await luis.CreatePhaseListAsync();
            //Console.WriteLine(phaseListID);

            while (repeat)
            {
                List <string> keywords = new List <string>();
                while (add)
                {
                    Console.WriteLine("Give us a word to search for a related value");
                    string word = Console.ReadLine();
                    keywords.Add(word);
                    Console.WriteLine("Do you want to add more: y/n");
                    char reply1 = Console.ReadLine()[0];
                    if (reply1.ToString().ToLower() != "y")
                    {
                        add = false;
                    }
                }
                Console.WriteLine("Give us the number of Top elements");
                int number = int.Parse(Console.ReadLine());

                /*
                 * RelatedValuesAsync and StrongValuesAsync method take as params keywords wich is List<string> and number of related values
                 * to return as result.
                 * keywords could be one to * but,it better to give a list of maximum 3 words
                 */

                //Console.WriteLine("++++++++++++++++The related Values++++++++++++++++++");
                //List<string> response = await luis.RelatedValuesAsync(keywords, number);

                Console.WriteLine("++++++++++++++++The connected Values++++++++++++++++++");
                List <string> response = await luis.StrongValuesAsync(keywords, number);


                foreach (var item in response)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine("Do you want to repeat : y/n");
                char reply = Console.ReadLine()[0];
                if (reply.ToString().ToLower() != "y")
                {
                    repeat = false;
                }
                add = true;
            }

            Console.ReadLine();
        }