public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var recognizer = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var topIntent  = recognizer?.GetTopScoringIntent();

                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    var location = LuisParser.GetEntityValue(recognizer);

                    if (location.ToString() != string.Empty)
                    {
                        var ro = await WeatherService.GetWeather(location);

                        var weather = $"{ro.weather.First().main} ({ro.main.temp.ToString("N2")} °C)";

                        var typing = Activity.CreateTypingActivity();
                        var delay  = new Activity {
                            Type = "delay", Value = 5000
                        };

                        var activities = new IActivity[] {
                            typing,
                            delay,
                            MessageFactory.Text($"Weather of {location} is: {weather}"),
                            MessageFactory.Text("Thanks for using our service!")
                        };

                        await turnContext.SendActivitiesAsync(activities);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync($"==>Can't understand you, sorry!");
                    }
                }
                else
                {
                    var msg = @"No LUIS intents were found.
                    This sample is about identifying a city and an intent:
                    'Find the current weather in a city'
                    Try typing 'What's the weather in Prague'";

                    await turnContext.SendActivityAsync(msg);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken);
            }
        }
Пример #2
0
        // start the right function
        public void Muxer(string LuisResult)
        {
            // parse JSON
            string Intent = LuisParser.getIntent(LuisResult);
            Dictionary <string, Entity> Entities = LuisParser.getEntities(LuisResult);

            if (Functions.ContainsKey(Intent))
            {
                Functions[Intent](messages, Entities);
            }
            else
            {
                PushMessage("Sorry, I was not able to understand that", ANSWER_STYLE);
            }
        }
Пример #3
0
        public void StartRegularRequest(string query)
        {
            // check if the query is empty
            if (query == "")
            {
                return;
            }

            // clean the command box
            commandBox.Text = "";
            PushMessage(query, REQUEST_STYLE);

            // make connection with LUIS
            try
            {
                var result = Task.Run(async() => { return(await LuisParser.MakeRequest(query)); }).Result;
                Muxer(result);
            }

            catch (Exception)
            {
                PushMessage("Sorry, I'm having a problem with the internet connection", ANSWER_STYLE);
            }
        }
Пример #4
0
        public async override Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = new CancellationToken())
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // luis
                var recognizer = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var topIntent  = recognizer?.GetTopScoringIntent();

                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    switch (topIntent.Value.intent)
                    {
                    case Constants.LoginIntent:
                        var ent = LuisParser.GetEntityValue(recognizer);
                        var t_v = ent.Split("_", 2);

                        switch (t_v[0])
                        {
                        case Constants.EmailLabel:
                            var customer = await WebApiService.GetCustomer(t_v[1]);

                            var userName = "";

                            if (customer != null)
                            {
                                userName = customer.CustomerName;

                                var hero = new HeroCard();
                                hero.Title    = "Welcome";
                                hero.Text     = customer.CustomerName;
                                hero.Subtitle = customer.CompanyName;

                                var us = _userState.CreateProperty <CustomerShort>(nameof(CustomerShort));
                                var c  = await us.GetAsync(turnContext, () => new CustomerShort());

                                c.CompanyName  = customer.CompanyName;
                                c.CustomerName = customer.CustomerName;
                                c.CustomerID   = customer.CustomerID;
                                c.EmailAddress = customer.EmailAddress;

                                var response = turnContext.Activity.CreateReply();
                                response.Attachments = new List <Attachment>()
                                {
                                    hero.ToAttachment()
                                };
                                await turnContext.SendActivityAsync(response, cancellationToken);

                                //await turnContext.SendActivityAsync($"Welcome {userName}");
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"User not found. Pleae try again");
                            }
                            break;

                        default:
                            await turnContext.SendActivityAsync("Please add your email to your login message");

                            break;
                        }
                        break;

                    case Constants.ProductInfoIntent:
                        var entity = LuisParser.GetEntityValue(recognizer, Constants.ProductInfoIntent);

                        var type_value = entity.Split("_", 2);

                        switch (type_value[0])
                        {
                        case Constants.ProductLabel:
                        case Constants.ProductNameLabel:
                            var product = "_";
                            var message = "Our Top 5 Products are:";

                            if (type_value[0] == Constants.ProductNameLabel)
                            {
                                product = type_value[1];
                                message = "Your query returned the following products: ";
                            }

                            var products = await WebApiService.GetProducts(product);

                            var data = "No results";

                            var typing = Activity.CreateTypingActivity();
                            var delay  = new Activity {
                                Type = "delay", Value = 5000
                            };

                            if (products != null)
                            {
                                var responseProducts = turnContext.Activity.CreateReply();
                                responseProducts.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                                responseProducts.Attachments      = new List <Attachment>();

                                foreach (var item in products)
                                {
                                    var card = new HeroCard();
                                    card.Subtitle = item.ListPrice.ToString("N2");
                                    card.Title    = item.Name;
                                    card.Text     = $"{item.Category} - {item.Model} - {item.Color}";
                                    card.Buttons  = new List <CardAction>()
                                    {
                                        new CardAction()
                                        {
                                            Value = $"Add product {item.ProductID} to the cart",
                                            Type  = ActionTypes.ImBack,
                                            Title = " Add To Cart "
                                        }
                                    };

                                    card.Images = new List <CardImage>()
                                    {
                                        new CardImage()
                                        {
                                            Url = $"data:image/gif;base64,{item.Photo}"
                                        }
                                    };

                                    var plAttachment = card.ToAttachment();
                                    responseProducts.Attachments.Add(plAttachment);
                                }

                                var activities = new IActivity[]
                                {
                                    typing,
                                    delay,
                                    MessageFactory.Text($"{message}: "),
                                    responseProducts,
                                    MessageFactory.Text("What else can I do for you?")
                                };

                                await turnContext.SendActivitiesAsync(activities);
                            }
                            else
                            {
                                var activities = new IActivity[]
                                { typing,
                                  delay,
                                  MessageFactory.Text($"{message}: {data}"),
                                  MessageFactory.Text("What else can I do for you?") };

                                await turnContext.SendActivitiesAsync(activities);
                            }
                            break;

                        default:
                            break;
                        }
                        break;

                    case Constants.AddToCartIntent:
                        var entProd = LuisParser.GetEntityValue(recognizer, Constants.NumberLabel);
                        var tv      = entProd.Split("_", 2);
                        var number  = 0;

                        if (tv[0] == Constants.NumberLabel)
                        {
                            number = int.Parse(tv[1]);

                            var product = await WebApiService.GetProduct(number);

                            var userStateAccessors    = _userState.CreateProperty <CustomerShort>(nameof(CustomerShort));
                            var shoppingCartAccessors = _userState.CreateProperty <List <ShoppingCart> >(nameof(List <ShoppingCart>));

                            var customer = await userStateAccessors.GetAsync(turnContext, () => new CustomerShort());

                            var cart = await shoppingCartAccessors.GetAsync(turnContext, () => new List <ShoppingCart>());

                            var item = new ShoppingCart()
                            {
                                CustomerID  = customer.CustomerID,
                                ProductID   = product.ProductID,
                                ProductName = product.Name,
                                ListPrice   = product.ListPrice,
                                Photo       = product.Photo
                            };
                            cart.Add(item);

                            var act = new IActivity[]
                            {
                                Activity.CreateTypingActivity(),
                                new Activity {
                                    Type = "delay", Value = 5000
                                },
                                MessageFactory.Text($"Product {product.Name} was added to the cart."),
                                MessageFactory.Text("What else can I do for you?")
                            };

                            await turnContext.SendActivitiesAsync(act);
                        }

                        break;

                    case Constants.PlaceOrderIntent:
                        //////////////////////77
                        var usAccessors = _userState.CreateProperty <CustomerShort>(nameof(CustomerShort));
                        var scAccessors = _userState.CreateProperty <List <ShoppingCart> >(nameof(List <ShoppingCart>));

                        var cust = await usAccessors.GetAsync(turnContext, () => new CustomerShort());

                        var shoppingCart = await scAccessors.GetAsync(turnContext, () => new List <ShoppingCart>());

                        if (shoppingCart.Count() > 0)
                        {
                            var receipt = turnContext.Activity.CreateReply();
                            receipt.Attachments = new List <Attachment>();

                            var card = new ReceiptCard();
                            card.Title = "Adventure Works";
                            card.Facts = new List <Fact>
                            {
                                new Fact("Name:", cust.CustomerName),
                                new Fact("E-mail:", cust.EmailAddress),
                                new Fact("Company:", cust.CompanyName),
                            };

                            decimal subtotal = 0;
                            decimal p        = 16M / 100;

                            card.Items = new List <ReceiptItem>();

                            foreach (var product in shoppingCart)
                            {
                                var item = new ReceiptItem();
                                item.Price    = product.ListPrice.ToString("N2");
                                item.Quantity = "1";
                                item.Text     = product.ProductName;
                                item.Subtitle = product.ProductName;
                                item.Image    = new CardImage()
                                {
                                    Url = $"data:image/gif;base64, {product.Photo}"
                                };

                                subtotal += product.ListPrice;

                                card.Items.Add(item);
                                //var plAttachment = card.ToAttachment();
                                //receipt.Attachments.Add(plAttachment);
                            }
                            receipt.Attachments.Add(card.ToAttachment());

                            var tax = subtotal * p;
                            card.Tax = tax.ToString("N2");

                            var total = subtotal + tax;
                            card.Total = total.ToString("N2");

                            var activities = new IActivity[]
                            {
                                Activity.CreateTypingActivity(),
                                new Activity {
                                    Type = "delay", Value = 5000
                                },
                                MessageFactory.Text("Here is your receipt: "),
                                receipt,
                                MessageFactory.Text("What else can I do for you?")
                            };

                            await turnContext.SendActivitiesAsync(activities);
                        }
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    var text = turnContext.Activity.Text.ToLowerInvariant();
                    switch (text)
                    {
                    case "help":
                        await SendIntroCardAsync(turnContext, cancellationToken);

                        break;

                    default:
                        await turnContext.SendActivityAsync("I did not understand you, sorry. Try again with a different sentence, please", cancellationToken : cancellationToken);

                        break;
                    }
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (!welcome)
                {
                    welcome = true;

                    await turnContext.SendActivityAsync($"Hi there. {WelcomeMessage}", cancellationToken : cancellationToken);

                    await turnContext.SendActivityAsync(InfoMessage, cancellationToken : cancellationToken);

                    await turnContext.SendActivityAsync(PatternMessage, cancellationToken : cancellationToken);
                }
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} activity detected");
            }

            // Save any state changes that might have occured during the turn.
            await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

            await _userState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
Пример #5
0
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var recognizer = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var topIntent  = recognizer?.GetTopScoringIntent();

                switch (topIntent.Value.intent)
                {
                case "Get_Weather_Condition":
                {
                    if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                    {
                        var location = LuisParser.GetEntityValue(recognizer, Constants.LocationLabel, Constants.LocationPatternLabel);
                        if (location.ToString() != string.Empty)
                        {
                            var ro = await WeatherService.GetWeather(location);

                            var weather = $"{ro.weather.First().main}({ro.main.temp.ToString("N2")} °C)";
                            var typing  = Activity.CreateTypingActivity();
                            var delay   = new Activity {
                                Type = "delay", Value = 5000
                            };
                            var activities = new IActivity[]
                            {
                                typing,
                                delay,
                                MessageFactory.Text($"Weather of {location} is: {weather}"),
                                MessageFactory.Text("Thanks for using our service!")
                            };
                            await turnContext.SendActivitiesAsync(activities);
                        }
                        else
                        {
                            await turnContext.SendActivityAsync("Sorry, I don´t understand");
                        }
                    }
                    else
                    {
                        var msg = @"No LUIS intents were found.
                                This sample is about identifying a city and an intent:
                                'Find the current weather in a city'
                                Try typing 'What's the weather in Prague'";

                        await turnContext.SendActivityAsync(msg);
                    }
                    break;
                }

                case "QnAMaker":
                {
                    var serviceQnAMaker = new QnAMakerService();
                    var answer          = serviceQnAMaker.GetAnswer(turnContext.Activity.Text);
                    if (answer.Equals(Constants.AnswerNotFound))
                    {
                        await turnContext.SendActivityAsync("Lo siento, pero no estoy preparado para este tipo de preguntas.");
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(answer);
                    }
                    break;
                }

                case "SearchVideo":
                {
                    //var searchVideo = LuisParser.GetEntityValue(recognizer, Constants.VideoLabel, Constants.VideoPatternLabel);
                    var searchVideo         = recognizer.Entities.Last.First[0].ToString();
                    var serviceVideoIndexer = new VideoIndexerService();
                    var response            = Task.Run(() => serviceVideoIndexer.SearchVideo("valor"));
                    response.Wait();
                    var videoList = response.Result;


                    var reply = (turnContext.Activity as Activity).CreateReply();
                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    var card = videoList.Select(r => new ThumbnailCard(r.VideoTitle, r.Description, r.Duration,
                                                                       new List <CardImage> {
                            new CardImage(url: r.Thumbnaill, r.VideoTitle)
                        },
                                                                       new List <CardAction>
                        {
                            new CardAction(ActionTypes.OpenUrl, "ver", null, value: r.UrlVideo, text: "ver", displayText: "ver"),
                            new CardAction(ActionTypes.OpenUrl, "Descargar", null, value: r.DownloadVideoUrl, text: "Descargar", displayText: "Descargar")
                        }
                                                                       ).ToAttachment()).ToList();

                    if (card.Any())
                    {
                        await turnContext.SendActivityAsync("Gracias por la espera, estos son los videos que encontré");

                        reply.Attachments = card;
                        await turnContext.SendActivityAsync(reply);
                    }

                    break;
                }
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken);
            }
        }
Пример #6
0
#pragma warning disable CS0114 // Member hides inherited member; missing override keyword
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
#pragma warning restore CS0114 // Member hides inherited member; missing override keyword
        {
            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var    recognizer = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
                var    topIntent  = recognizer?.GetTopScoringIntent();
                string pregunta   = recognizer.Text;
                if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
                {
                    var entidades = LuisParser.GetEntityValue(recognizer);
                    switch (topIntent.Value.intent)
                    {
                    case "Configurar_Aplicacion":
                        var ad          = entidades.Split(',');
                        var aplicacion  = ad[0];
                        var dispositivo = ad[1];

                        if (entidades.ToString() != string.Empty)
                        {
                            var ro = await SupportService.GetEntityValue(entidades);

                            //var weather = $"{ro..First().main} ({ro.main.temp.ToString("N2")} °C)";
                            var title  = $"{ro.Results.First().HtmlUrl}";
                            var typing = Activity.CreateTypingActivity();
                            var delay  = new Activity {
                                Type = "delay", Value = 5000
                            };

                            var activities = new IActivity[] {
                                typing,
                                delay,
                                MessageFactory.Text($"Maybe this {title} could help you"),
                                MessageFactory.Text("Thanks for using our service!")
                            };

                            await turnContext.SendActivitiesAsync(activities);
                        }
                        else
                        {
                            await turnContext.SendActivityAsync($"==>Can't understand you, sorry!");
                        }
                        break;

                    default:
                        await turnContext.SendActivityAsync($"There is not information about your question:{pregunta} sorry!");

                        break;
                    }
                }
                else
                {
                    var msg = @"No LUIS intents were found.
                    This sample is about identifying a city and an intent:
                    'Find the current weather in a city'
                    Try typing 'What's the weather in Prague'";

                    await turnContext.SendActivityAsync(msg);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken : cancellationToken);
            }
        }