private async Task Salutation(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

            if (string.IsNullOrEmpty(userState.Status))
            {
                dialogContext.ActiveDialog.State = new Dictionary <string, object>();
                await dialogContext.Context.SendActivity("Olá, seja bem vindo a Pergher Pizzaria!!!");

                await dialogContext.Context.SendActivity($"Eu sou o Jorge {Emojis.ManRaisingHand} o bot da Pergher pizzaria. Estou aqui para te ajudar em seu pedido.  \n" +
                                                         $"Dúvidas? Digite *AJUDA* e será encaminhado ao manual de utilização.  \n" +
                                                         $"Problemas em alguma parte da conversa? Digite *SAIR* e voltaremos ao fluxo normal.");

                await dialogContext.Context.SendActivity(new Activity
                {
                    Type = ActivityTypes.Typing
                });

                await dialogContext.Prompt(TextPrompt, "Como você está se sentindo hoje?");
            }
            else
            {
                await dialogContext.Context.SendActivity(new Activity
                {
                    Type = ActivityTypes.Typing
                });

                await dialogContext.Context.SendActivity($"Olá, é um prazer ter você aqui {Emojis.SmileHappy}  \nO que você gostaria hoje? ");

                await dialogContext.End();
            }
        }
예제 #2
0
 public ProfileControl()
     : base("fillProfile")
 {
     Dialogs.Add("fillProfile",
                 new WaterfallStep[]
     {
         async(dc, args, next) =>
         {
             dc.ActiveDialog.State = new Dictionary <string, object>();
             await dc.Prompt("textPrompt", "What is your name?");
         },
         async(dc, args, next) =>
         {
             dc.ActiveDialog.State["name"] = args["Value"];
             GameInfo game  = UserState <GameInfo> .Get(dc.Context);
             game.User.Name = args["Value"].ToString();
             await dc.Prompt("textPrompt", $"Hello {game.User.Name}! Be prepared to lose.");
         },
         async(dc, args, next) =>
         {
             dc.ActiveDialog.State["phone"] = args["Value"];
             await dc.End(dc.ActiveDialog.State);
         }
     });
     Dialogs.Add("textPrompt", new TextPrompt());
 }
예제 #3
0
        /// <summary>
        /// Every Conversation turn for our bot calls this method.
        /// </summary>
        /// <param name="context">The current turn context.</param>
        public async Task OnTurn(ITurnContext context)
        {
            if (context.Activity.Type is ActivityTypes.Message)
            {
                // Get the user and conversation state from the turn context.
                var state = UserState <UserData> .Get(context);

                var conversationInfo = ConversationState <ConversationInfo> .Get(context);

                // Establish dialog state from the conversation state.
                var dc = _dialogs.CreateContext(context, conversationInfo);

                // Continue any current dialog.
                await dc.Continue();

                // Every turn sends a response, so if no response was sent,
                // then there no dialog is currently active.
                if (!context.Responded)
                {
                    // Greet them if we haven't already
                    if (state.Greeted == "not greeted")
                    {
                        await RootResponses.ReplyWithGreeting(context);

                        await RootResponses.ReplyWithHelp(context);

                        state.Greeted = "greeted";
                    }
                    else
                    {
                        await dc.Begin(RootDialog);
                    }
                }
            }
        }
예제 #4
0
        public UserViewModel Get(string userId)
        {
            var user = _userState.Get(userId);

            return(user != null ? new UserViewModel
            {
                Name = user.Name,
                Id = userId
            } : null);
        }
예제 #5
0
        private Guid GetGuestId()
        {
            UserState us = UserState.Get(UserState.States.GuestIdState);

            if (us == null) // Create a new guest user id.
            {
                us = new MvcRQUser.GuestIdState(Guid.NewGuid());
            }
            return(((GuestIdState)us).GuestId);
        }
예제 #6
0
 public static void PutQueryToState(RQquery query, UserState.States stateType)
 {
     state = (ViewState)UserState.Get(stateType);
     if (state == null)
     {
         state = new ViewState(stateType);
     }
     state.query = query;
     state.Save();
 }
        private async Task How_Is(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

            await dialogContext.Context.SendActivity(new Activity
            {
                Type = ActivityTypes.Typing
            });

            await dialogContext.Prompt(TextPrompt, "Eu estou ótimo e você, como está se sentindo hoje?");
        }
예제 #8
0
 public static Boolean GetClasstreeOptionsState()
 {
     state = (ViewState)UserState.Get(UserState.States.ClasstreeOptionsState);
     if (state == null)
     {
         state       = new ViewState(UserState.States.ClasstreeOptionsState);
         state.query = false;
         state.Save();
     }
     return((Boolean)state.query);
 }
예제 #9
0
        /// <summary>
        /// Builds the actual query.
        /// </summary>
        /// <param name="queryString">
        /// queryString == null | ""        : Rebuilds actual query from stored query state parameters or returns the default query.
        /// queryString != null             : Builds a new query from queryString and stores it in query state parameters.
        /// </param>
        /// <param name="stateType">
        /// stateType == ListViewState      : (Re)builds actual query for ListView.
        /// stateType == BrowseViewState    : (Re)builds actual query for BrowseView.
        /// stateType == ItemViewState      : (Re)builds actual query for SingleItemView.
        /// </param>
        /// <returns>
        /// Actual query.
        /// </returns>
        public static RQquery GetQueryFromState(string queryString, UserState.States stateType)
        {
            RQquery query = null;

            state = (ViewState)UserState.Get(stateType);
            if (state == null)
            {
                if (string.IsNullOrEmpty(queryString))
                {
                    query = new RQquery("$recent$recent additions", "recent");
                }
                else
                {
                    query = new RQquery(queryString);
                }
                state       = new ViewState(stateType); //, queryString);
                state.query = query;
                //state.Save();
            }
            else
            {
                string querytest;
                UserSettingsService us = new UserSettingsService();

                query = (RQquery)state.query;
                if (!string.IsNullOrEmpty(queryString) && queryString.StartsWith("$") && queryString.LastIndexOf("$") > 1)
                {
                    querytest = queryString.Substring(0, queryString.LastIndexOf("$") + 1) + query.QueryString;
                }
                else
                {
                    querytest = query.QueryString;
                }
                //if (   (! string.IsNullOrEmpty(queryString) && querytest != queryString)
                //    || (query.QueryExternal == "" && us.GetIncludeExternal() == true)
                //    || (query.QueryExternal != "" && us.GetIncludeExternal() == false) )
                //{
                //    query = new RQquery(! string.IsNullOrEmpty(queryString) ? queryString : query.QueryString);
                //    query.QueryExternal = us.GetIncludeExternal() == true ? "003" : "";
                //    state.query = query;
                //    //state.Save();
                //}
                if (!string.IsNullOrEmpty(queryString) && querytest != queryString)
                {
                    query = new RQquery(!string.IsNullOrEmpty(queryString) ? queryString : query.QueryString);
                }
                query.QueryExternal = us.GetIncludeExternal() == true ? "003" : "";
                state.query         = query;
            }
            return(query);
        }
예제 #10
0
 public static Boolean ChangeClasstreeOptionsState()
 {
     state = (ViewState)UserState.Get(UserState.States.ClasstreeOptionsState);
     if (state == null)
     {
         state       = new ViewState(UserState.States.ClasstreeOptionsState);
         state.query = true;
     }
     else
     {
         state.query = (Boolean)state.query == true ? false : true;
     }
     state.Save();
     return((Boolean)state.query);
 }
예제 #11
0
        public async override Task OnMessage(ITurnContext context)
        {
            var SysMem = UserState <T> .Get(context).SysMem;

            if (!SysMem.ContainsKey("UQueue"))
            {
                SysMem.Add("UQueue", new Queue <string>());
            }
            var UQueue = (Queue <string>)SysMem["UQueue"];

            UQueue.Enqueue(context.Activity.Text);
            if (UQueue.Count >= N)
            {
                UQueue.Dequeue();
            }
        }
예제 #12
0
파일: KGBot.cs 프로젝트: deepmipt/kgbot
        public async Task OnTurn(ITurnContext ctx)
        {
            if (ctx.Activity.Type is ActivityTypes.Message)
            {
                if (!ctx.Responded)
                {
                    await ctx.SendActivity("Hello! I am KudaGo bot! You can say <<help>> to see what you can ask");
                }
                // Trace state
#if PRINT_STATE
                var S = UserState <KGBState> .Get(ctx);

                await ctx.SendActivity($"State: {S}");
#endif
            }
        }
예제 #13
0
        public async Task OnTurn(ITurnContext context, MiddlewareSet.NextDelegate next)
        {
            if (context.Activity.Type is ActivityTypes.Message)
            {
                // simple middleware to add an additional send activity
                var user = UserState <User> .Get(context);

                user.Queries.Add(context.Activity.AsMessageActivity().Text);

                //if (user.Queries.Count > 50)
                //    // Send an email to the author with all respective
                //    // output of the sentiments, like score etc.
                //    ExtractSentiments(user.Queries);
            }

            await next();
        }
        private async Task Answer_How_Is(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            dialogContext.ActiveDialog.State["status"] = args["Value"];

            BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

            userState.Status = Convert.ToString(dialogContext.ActiveDialog.State["status"]);

            await dialogContext.Context.SendActivity(new Activity
            {
                Type = ActivityTypes.Typing
            });

            await dialogContext.Context.SendActivity($"Eu estou ótimo {Emojis.SmileHappy}!  \nO que você gostaria hoje?");

            await dialogContext.End();
        }
예제 #15
0
        private async Task Ask_StatusBegin(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            await dialogContext.Context.SendActivity(new Activity
            {
                Type = ActivityTypes.Typing
            });

            BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

            User user = context.Users.Where(x => x.UserIdBot == dialogContext.Context.Activity.From.Id).FirstOrDefault();

            List <Order> orders = context.Orders.Where(x => x.User.UserId == user.UserId).ToList();

            if (orders.Count > 0)
            {
                IActivity activity = MessageFactory.Carousel(GetAttachmentsByOrders(orders));
                await dialogContext.Context.SendActivity(activity);
            }
            else
            {
                await dialogContext.Context.SendActivity("Você não possui nenhum pedido em aberto no momento!  \n O que você gostaria hoje?");
            }
        }
예제 #16
0
 public FirstRun()
     : base("firstRun")
 {
     Dialogs.Add("fillProfile", new ProfileControl());
     Dialogs.Add("roll", new PlayerMoves());
     Dialogs.Add("firstRun",
                 new WaterfallStep[]
     {
         async(dc, args, next) =>
         {
             await dc.Context.SendActivity("Welcome! We need to ask a few questions to get started.");
             await dc.Begin("fillProfile");
         },
         async(dc, args, next) =>
         {
             //await dc.Context.SendActivity($"Thanks {args["name"]} I have your phone number as {args["phone"]}!");
             UserState <GameInfo> .Get(dc.Context).User.Name = args["name"].ToString();
             //await dc.End();
             await dc.Begin("roll");
         }
     });
     Dialogs.Add("textPrompt", new TextPrompt());
 }
예제 #17
0
        public PlayerMoves()
            : base("roll")
        {
            Dialogs.Add("BotRoll", new BotMoves());
            Dialogs.Add("roll",
                        new WaterfallStep[]
            {
                async(dc, args, next) =>
                {
                    dc.ActiveDialog.State = new Dictionary <string, object>();
                    await dc.Context.SendActivity("Roll?");
                },
                async(dc, args, next) =>
                {
                    Random rnd = new Random((int)DateTime.Now.Ticks);
                    int num    = rnd.Next(1, 7);
                    dc.ActiveDialog.State["rollAmount"] = num;

                    GameInfo game       = UserState <GameInfo> .Get(dc.Context);
                    game.User.Position += num;
                    if (game.User.Position >= Board.Properties.Length)
                    {
                        game.User.Position -= Board.Properties.Length;
                        await dc.Prompt("textPrompt", $"You passed Go. I get ${Board.GoMoney}.");
                        game.User.Money += Board.GoMoney;
                    }

                    int position      = game.User.Position;
                    Property property = Board.Properties[position];
                    await dc.Prompt("textPrompt", $"You've landed on {property.Name}.");
                    if (game.User.Money < property.Cost)
                    {
                        await dc.Prompt("textPrompt", $"You dont have enough money to buy {property.Name}.");
                    }
                    // no one owns this yet
                    else if (game.PropertyOnwers[game.User.Position] == 0)
                    {
                        await dc.Prompt("textPrompt", $"Do you want to buy {property.Name} for {property.Cost}?");
                    }
                    // mine
                    else if (property.Owner == 1)
                    {
                        await dc.Prompt("textPrompt", $"You moved to your land: {property.Name}.");
                    }
                    // bots
                    else if (property.Owner == 2)
                    {
                        await dc.Prompt("textPrompt", $"Pay me rent! ${property.Cost}.");
                    }
                },
                async(dc, args, next) =>
                {
                    //dc.ActiveDialog.State["BuyProperty"] = args["Value"];
                    GameInfo game     = UserState <GameInfo> .Get(dc.Context);
                    Property property = Board.Properties[game.User.Position];
                    if (args["Value"].ToString() == "yes" && game.User.Money >= property.Cost)
                    {
                        dc.ActiveDialog.State["BuyProperty"] = "yes";
                        // TODO : options to buy or not
                        game.PropertyOnwers[game.User.Position] = 1;
                        // TODO : player cant buy if dont have enough money
                        game.User.Money -= property.Cost;
                    }
                    await dc.Prompt("textPrompt", $"You now have {game.User.Money} money in your bank.");
                    dc.ActiveDialog.State["BuyProperty"] = "no";

                    if (game.User.Money < 0)
                    {
                        await dc.End();
                    }
                    else
                    {
                        await dc.Begin("BotRoll");
                        game.Turn = 1;
                    }
                }
            });
            Dialogs.Add("textPrompt", new TextPrompt());
        }
예제 #18
0
        public async Task OnTurn(ITurnContext turnContext)
        {
            /*if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate && turnContext.Activity.MembersAdded.FirstOrDefault()?.Id == turnContext.Activity.Recipient.Id)
             * {
             *  await turnContext.SendActivity($"Seja bem vindo a Pergher pizzaria {Emojis.SmileHappy}");
             *
             *  await turnContext.SendActivity(new Activity
             *  {
             *      Type = ActivityTypes.Typing
             *  });
             *
             *  await turnContext.SendActivity($"Eu sou o Jorge o bot da Pergher pizzaria e estou aqui para auxiliá-lo no seu pedido {Emojis.SmileHappy} \n" +
             *      "Atualmente eu posso realizar as seguintes tarefas: \n" +
             *      "*-Ofereço bebidas e pizzas cutomizadas na sua solicitação* \n" +
             *      "*-Mostro como seu carrinho está no momento* \n" +
             *      "*-Limpo seu carrinho quando solicitado* \n" +
             *      "*-Finalizo seu carrinho quando solicitado* \n" +
             *      "*-Edito e removo itens seu carrinho quando solicitado* \n" +
             *      "*-Edito seu endreço de entrega atual quando solicitado* \n" +
             *      "*-Busco seus pedidos abertos para saber o seu estado* \n");
             *
             *  await turnContext.SendActivity($"Quando tiver alguma dúvida simplesmente escreva *AJUDA* e lhe redirecionarei para exemplos de uso {Emojis.SmileHappy}\n" +
             *      $"Caso queira sair de uma conversa que esteja no momento, simplesmente digite *SAIR* e voltaremos ao fluxo normal da conversa {Emojis.SmileHappy}\n" +
             *      $"Em que lhe posso ser útil no momento?");
             *
             * }*/

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var           dialogState   = turnContext.GetConversationState <Dictionary <string, object> >();
                DialogContext dialogContext = DialogFlow.CreateContext(turnContext, dialogState);

                if (turnContext.Activity.Text.ToLower() == "sair")
                {
                    dialogContext.EndAll();
                }
                else if (turnContext.Activity.Text.ToLower() == "ajuda")
                {
                    //IActivity activity = MessageFactory.SuggestedActions(new CardAction[]
                    //    {
                    //        new CardAction
                    //        {
                    //            Title = "Abrir documentação",
                    //            Type = ActionTypes.OpenUrl,
                    //            Value = "https://pizzeria-bot-tc.readthedocs.io/pt/latest/index.html"
                    //        }
                    //    });

                    IActivity activity = MessageFactory.Attachment(new HeroCard
                    {
                        Buttons = new List <CardAction>
                        {
                            new CardAction
                            {
                                Title = "Abrir manual",
                                Type  = ActionTypes.OpenUrl,
                                Value = "https://pizzeria-bot-tc.readthedocs.io/pt/latest/index.html"
                            }
                        }
                    }.ToAttachment());

                    await dialogContext.Context.SendActivity($"Clique no botão abaixo para abrir o manual {Emojis.SmileHappy} ");

                    await dialogContext.Context.SendActivity(activity);
                }
                else
                {
                    await dialogContext.Continue();

                    BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

                    if (!turnContext.Responded)
                    {
                        RecognizerResult luisResult   = turnContext.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey);
                        string           intentResult = LuisResult.GetLuisIntent(luisResult, userState);

                        IDictionary <string, object> args = new Dictionary <string, object>
                        {
                            { "entities", EntitiesParse.RecognizeEntities(luisResult.Entities) }
                        };

                        await dialogContext.Begin(intentResult, args);
                    }
                }
            }
            else if (turnContext.Activity.Type != ActivityTypes.ConversationUpdate)
            {
                await turnContext.SendActivity($"Olá, ainda não estou preparado para tratar este tipo de informacão {Emojis.SmileSad}  \n" +
                                               $"Peço que utilize apenas texto para melhorar nossa interação {Emojis.SmileHappy}");
            }
        }
예제 #19
0
        public BotMoves()
            : base("BotRoll")
        {
            Dialogs.Add("BotRoll",
                        new WaterfallStep[]
            {
                async(dc, args, next) =>
                {
                    dc.ActiveDialog.State = new Dictionary <string, object>();
                },
                async(dc, args, next) =>
                {
                    Random rnd = new Random((int)DateTime.Now.Ticks);
                    int num    = rnd.Next(1, 7);
                    dc.ActiveDialog.State["rollAmount"] = num;

                    GameInfo game      = UserState <GameInfo> .Get(dc.Context);
                    game.Bot.Position += num;
                    if (game.Bot.Position >= Board.Properties.Length)
                    {
                        game.Bot.Position -= Board.Properties.Length;
                        await dc.Prompt("textPrompt", $"I passed Go. I get ${Board.GoMoney}.");
                        game.Bot.Money += Board.GoMoney;
                    }

                    int position      = game.Bot.Position;
                    Property property = Board.Properties[position];
                    await dc.Prompt("textPrompt", $"I landed on {property.Name}.");
                    if (game.Bot.Money >= property.Cost && game.PropertyOnwers[game.Bot.Position] == 0)
                    {
                        await dc.Prompt("textPrompt", $"I'll buy {property.Name}.");
                        game.Bot.Money -= property.Cost;
                        game.PropertyOnwers[game.User.Position] = 2;
                    }
                    // no one owns this yet
                    else if (game.Bot.Money < property.Cost)
                    {
                        await dc.Prompt("textPrompt", $"I'll pass on {property.Name} for now.");
                    }
                    // mine
                    else if (game.PropertyOnwers[game.User.Position] == 1)
                    {
                        await dc.Prompt("textPrompt", $"I guess I have to pay you ${property.Cost}.");
                        game.Bot.Money -= property.Cost;
                    }
                    // bots
                    else if (game.PropertyOnwers[game.User.Position] == 2)
                    {
                        await dc.Prompt("textPrompt", $"I own this.");
                    }

                    if (game.User.Money < 0)
                    {
                        await dc.End();
                    }
                    else
                    {
                        await dc.Prompt("textPrompt", $"Your turn.");
                        game.Turn = 0;
                    }
                }
            });
            Dialogs.Add("textPrompt", new TextPrompt());
        }
예제 #20
0
        public async Task Ask_Product(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            await dialogContext.Context.SendActivity(new Activity
            {
                Type = ActivityTypes.Typing
            });

            EntitiesParse entities  = (EntitiesParse)args["entities"];
            BotUserState  userState = UserState <BotUserState> .Get(dialogContext.Context);

            userState.EntitiesState = new EntitiesState
            {
                EntitiesParse      = entities,
                AddedDate          = DateTime.Now,
                DrinksQuantityUsed = 0,
                PizzasQuantityUsed = 0
            };

            if (entities.Ingredients.Count > 0)
            {
                List <Pizza> pizzas = EntitieRecomendation.GetPizzasByIngredients(entities.Ingredients, context);
                pizzas = pizzas.Skip(quantityPizza * userState.EntitiesState.PizzasQuantityUsed).ToList();

                List <Attachment> attachments = GetPizzaAttachments(pizzas, userState);
                userState.EntitiesState.PizzasQuantityUsed++;

                IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity($"Estou lhe enviando as pizzas disponíveis, começando pelas pizzas que possuem {GetIngredientsFindedText(pizzas, entities.Ingredients)}");

                await dialogContext.Context.SendActivity(new Activity
                {
                    Type = ActivityTypes.Typing
                });

                Thread.Sleep(4000);
                await dialogContext.Context.SendActivity(messageActivity);
            }
            else if (entities.Drinks.Count > 0)
            {
                List <Drink> drinks = EntitieRecomendation.GetDrinksMoreSalesWithUserDrinks(userState.EntitiesState.EntitiesParse.Drinks, context);

                drinks = drinks.Skip(quantityDrink * userState.EntitiesState.DrinksQuantityUsed).ToList();

                List <Attachment> attachments = GetDrinkAttachments(drinks, userState);
                userState.EntitiesState.DrinksQuantityUsed++;

                IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity("Estou lhe enviando as bebidas disponíveis, começando pelas solicitadas");

                await dialogContext.Context.SendActivity(new Activity
                {
                    Type = ActivityTypes.Typing
                });

                Thread.Sleep(4000);
                await dialogContext.Context.SendActivity(messageActivity);
            }
            else if (entities.ProductTypes.Count > 0)
            {
                if (entities.ProductTypes.Where(x => x == "pizza").ToList().Count > 0)
                {
                    List <Pizza> pizzas = EntitieRecomendation.GetPizzasByIngredients(userState.EntitiesState.EntitiesParse.Ingredients, context);
                    pizzas = pizzas.Skip(quantityPizza * userState.EntitiesState.PizzasQuantityUsed).ToList();

                    List <Attachment> attachments = GetPizzaAttachments(pizzas, userState);
                    userState.EntitiesState.PizzasQuantityUsed++;

                    IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                    await dialogContext.Context.SendActivity("Estou lhe enviando as pizzas disponíveis, ordenando pelas mais vendidas");

                    await dialogContext.Context.SendActivity(new Activity
                    {
                        Type = ActivityTypes.Typing
                    });

                    Thread.Sleep(4000);
                    await dialogContext.Context.SendActivity(messageActivity);
                }
                else if (entities.ProductTypes.Where(x => x == "bebida").ToList().Count > 0)
                {
                    List <Drink> drinks = EntitieRecomendation.GetDrinksMoreSalesWithUserDrinks(userState.EntitiesState.EntitiesParse.Drinks, context);

                    drinks = drinks.Skip(quantityDrink * userState.EntitiesState.DrinksQuantityUsed).ToList();

                    List <Attachment> attachments = GetDrinkAttachments(drinks, userState);
                    userState.EntitiesState.DrinksQuantityUsed++;

                    IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                    await dialogContext.Context.SendActivity("Estou lhe enviando as bebidas disponíveis, ordenando pelas mais vendidas");

                    await dialogContext.Context.SendActivity(new Activity
                    {
                        Type = ActivityTypes.Typing
                    });

                    Thread.Sleep(4000);
                    await dialogContext.Context.SendActivity(messageActivity);
                }
            }
            else
            {
                List <Pizza> pizzas = EntitieRecomendation.GetPizzasMoreSales(context);
                pizzas = pizzas.Skip(quantityPizza * userState.EntitiesState.PizzasQuantityUsed).ToList();

                List <Attachment> attachments = GetPizzaAttachments(pizzas, userState);
                userState.EntitiesState.PizzasQuantityUsed++;

                IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity("Estou lhe enviando as pizzas disponíveis, ordenando pelas mais vendidas");

                await dialogContext.Context.SendActivity(new Activity
                {
                    Type = ActivityTypes.Typing
                });

                Thread.Sleep(2000);
                await dialogContext.Context.SendActivity(messageActivity);
            }
        }
예제 #21
0
 public async Task PrintState(ITurnContext ctx)
 {
     await ctx.SendActivity($"{UserState<KGBState>.Get(ctx)}");
 }
예제 #22
0
        public async Task OrderProducts(DialogContext dialogContext, IDictionary <string, object> args, SkipStepFunction next)
        {
            await dialogContext.Context.SendActivity(new Activity
            {
                Type = ActivityTypes.Typing
            });

            Activity     activity  = (Activity)args["Activity"];
            BotUserState userState = UserState <BotUserState> .Get(dialogContext.Context);

            List <Pizza> pizzas = EntitieRecomendation.GetPizzasByIngredients(userState.EntitiesState.EntitiesParse.Ingredients, context);

            if (userState.EntitiesState.EntitiesParse.Ingredients.Count == 0)
            {
                pizzas = EntitieRecomendation.GetPizzasMoreSales(context);
            }
            List <Drink> drinks = EntitieRecomendation.GetDrinksMoreSalesWithUserDrinks(userState.EntitiesState.EntitiesParse.Drinks, context);

            if (activity.Text.Contains(ActionTypes.PostBack + "AddPizza"))
            {
                string[]   productData = activity.Text.Split("||");
                PizzaModel pizzaModel  = AddPizzaOrder(productData[0], productData[1], userState);
                userState.EntitiesState.PizzasQuantityUsed--;

                await dialogContext.Context.SendActivity($"A pizza {pizzaModel.PizzaName} - {pizzaModel.SizeName} foi adicionada com sucesso {Emojis.SmileHappy}");

                await dialogContext.Context.SendActivity($"Gostaria de ver mais alguma pizza?  \nClique no botão caso deseje, ou simplesmente solicite o que deseja {Emojis.SmileHappy})");

                await dialogContext.Context.SendActivity(GetSuggestedActionsNewsPizzasAndDrinks("Pizza"));
            }
            else if (activity.Text.Contains(ActionTypes.PostBack + "SuggestedActionPizza"))
            {
                pizzas = pizzas.Skip(quantityPizza * userState.EntitiesState.PizzasQuantityUsed).ToList();
                List <Attachment> attachments = GetPizzaAttachments(pizzas, userState);
                userState.EntitiesState.PizzasQuantityUsed++;
                IMessageActivity activitySend = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity(activitySend);
            }
            else if (activity.Text == (ActionTypes.PostBack + "MorePizza"))
            {
                pizzas = pizzas.Skip(quantityPizza * userState.EntitiesState.PizzasQuantityUsed).ToList();
                List <Attachment> attachments = GetPizzaAttachments(pizzas, userState);
                userState.EntitiesState.PizzasQuantityUsed++;
                IMessageActivity activitySend = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity(activitySend);
            }
            else if (activity.Text.Contains(ActionTypes.PostBack + "AddDrink"))
            {
                string[]   productData = activity.Text.Split("||");
                DrinkModel drinkModel  = AddDrinkOrder(productData[0], productData[1], userState);
                userState.EntitiesState.DrinksQuantityUsed--;

                await dialogContext.Context.SendActivity($"{drinkModel.DrinkName} {drinkModel.DrinkSizeName} adicionado com sucesso {Emojis.SmileHappy}");

                await dialogContext.Context.SendActivity($"Gostaria de ver mais alguma bebida?  \nClique no botão caso deseje, ou simplesmente solicite o que deseja {Emojis.SmileHappy}");

                await dialogContext.Context.SendActivity(GetSuggestedActionsNewsPizzasAndDrinks("Drink"));
            }
            else if (activity.Text.Contains(ActionTypes.PostBack + "SuggestedActionDrink"))
            {
                drinks = drinks.Skip(quantityDrink * userState.EntitiesState.DrinksQuantityUsed).ToList();
                List <Attachment> attachments = GetDrinkAttachments(drinks, userState);
                userState.EntitiesState.DrinksQuantityUsed++;
                IMessageActivity activitySend = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity(activitySend);
            }
            else if (activity.Text == (ActionTypes.PostBack + "MoreDrink"))
            {
                drinks = drinks.Skip(quantityDrink * userState.EntitiesState.DrinksQuantityUsed).ToList();
                List <Attachment> attachments = GetDrinkAttachments(drinks, userState);
                userState.EntitiesState.DrinksQuantityUsed++;
                IMessageActivity messageActivity = MessageFactory.Carousel(attachments);
                await dialogContext.Context.SendActivity(messageActivity);
            }
            else
            {
                RecognizerResult luisResult   = dialogContext.Context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey);
                string           intentResult = LuisResult.GetLuisIntent(luisResult, userState);

                IDictionary <string, object> createdArgs = new Dictionary <string, object>
                {
                    { "entities", EntitiesParse.RecognizeEntities(luisResult.Entities) }
                };
                await dialogContext.Replace(intentResult, createdArgs);
            }
        }
예제 #23
0
        public override async Task OnMessage(ITurnContext context)
        {
            var S = UserState <KGBState> .Get(context);

            var R = new PavlovRequest(S.PavlovState);

            R.utter_history = UtteranceQueueMiddleware <KGBState> .GetUtteranceHistory(S);

            R.utterance = context.Activity.Text;
            var shownEvents = S.PavlovState.slot_history.ContainsKey("shown_events") ?
                              new HashSet <int>((List <int>)S.PavlovState.slot_history["shown_events"]) : new HashSet <int>();

#if PRINT_STATE
            await context.SendActivity(JsonConvert.SerializeObject(S.PavlovState));
#endif
            var http = new HttpClient();
            var s    = System.Web.HttpUtility.JavaScriptStringEncode(context.Activity.Text);
            var c    = new StringContent(JsonConvert.SerializeObject(R), Encoding.UTF8, "application/json");
            var resp = await http.PostAsync(ApiUri, c);

            var res = await resp.Content.ReadAsStringAsync();

#if PRINT_STATE
            await context.SendActivity(res);
#endif
            dynamic jres = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
            S.PavlovState.last_cluster_id = jres[3];
            var shs = jres[2].ToString();
            S.PavlovState.slot_history = JsonConvert.DeserializeObject <Dictionary <string, object> >(shs);
            foreach (var t in jres[1])
            {
                var lid = (int)t.local_id;
                shownEvents.Add(lid);
            }
            S.PavlovState.slot_history["shown_events"] = shownEvents.ToList();
            if (jres[0] is JValue) // this is single-line response
            {
                Activity msg;
                if (jres[1].Count == 0)
                {
                    S.PavlovState.slot_history = new Dictionary <string, object>();
                    UtteranceQueueMiddleware <KGBState> .Reset(S);

                    S.PavlovState.last_cluster_id = null;

                    msg = MessageFactory.Text(jres[0].ToString());
                }
                else
                {
                    msg = MessageFactory.Carousel(BuildEventsAttachment(jres[1]));
                    await context.SendActivity(msg);

                    msg = MessageFactory.Text(jres[0].ToString());
                }
                await context.SendActivity(msg);

                // await context.SendActivity($"{(string)jres[0]}\r\n{BuildEvents(jres[1])}");
            }
            else if (jres[0] is JArray)
            {
                // await context.SendActivity($"Вот что мы вам рекомендуем:\r\n{BuildEvents(jres[0])}");
            }
            else
            {
            }
        }
예제 #24
0
 /// <summary>
 /// Gets a user state object from the turn context.
 /// </summary>
 /// <typeparam name="TState">The type of the state object to get.</typeparam>
 /// <param name="context">The context object for this turn.</param>
 /// <returns>The state object.</returns>
 public static TState GetUserState <TState>(this ITurnContext context)
     where TState : class, new()
 {
     return(UserState <TState> .Get(context));
 }