Beispiel #1
0
        public async Task OnTurn(ITurnContext turnContext)
        {
            try
            {
                Dictionary <string, object> state = null;
                DialogContext dc = null;
                switch (turnContext.Activity.Type)
                {
                case ActivityTypes.Message:
                    if (turnContext.Activity.Text == "signout")
                    {
                        var botframeworkAdapter = turnContext.Adapter as BotFrameworkAdapter;
                        await botframeworkAdapter.SignOutUser(turnContext, _connectionSettingName);

                        await turnContext.SendActivity("You are now signed out.");
                    }
                    else
                    {
                        state = ConversationState <Dictionary <string, object> > .Get(turnContext);

                        dc = _dialogs.CreateContext(turnContext, state);
                        await dc.Continue();

                        // Check to see if anyone replied. If not then start dialog
                        if (!turnContext.Responded)
                        {
                            await dc.Begin("displayToken");
                        }
                    }
                    break;

                case ActivityTypes.Event:
                case ActivityTypes.Invoke:
                    // Create dialog context and continue executing the "current" dialog, if any.
                    // This is important for OAuthCards because tokens can be received via TokenResponse events
                    state = ConversationState <Dictionary <string, object> > .Get(turnContext);

                    dc = _dialogs.CreateContext(turnContext, state);
                    await dc.Continue();

                    break;
                }
            }
            catch (Exception e)
            {
                await turnContext.SendActivity($"Exception: {e.Message}");
            }
        }
Beispiel #2
0
        /*async Task AllowRerunsValidator(ITurnContext context, Prompts.TextResult result)
         * {
         *      if(string.IsNullOrWhiteSpace(result.Value)
         || (!result.Value.Equals("yes", StringComparison.CurrentCultureIgnoreCase) && !result.Value.Equals("no", StringComparison.CurrentCultureIgnoreCase))
         ||             && (!result.Value.Equals("y", StringComparison.CurrentCultureIgnoreCase) && !result.Value.Equals("n", StringComparison.CurrentCultureIgnoreCase)))
         ||     {
         ||             result.Status = Prompts.PromptStatus.NotRecognized;
         ||             await context.SendActivity("Please reply with 'yes' or 'no'");
         ||     }
         ||}
         ||private Task DefaultDialog(DialogContext dialogContext, object args, SkipStepFunction next)
         ||{
         ||     return dialogContext.Context.SendActivity("I'm sorry, I'm not quite sure what you mean.");
         ||}*/

        #endregion

        #region Resolve Cast Info Inquiry

        private async Task ResolveCastInfoInquiry(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var inquiry = new CastInfoInquiry(dialogContext.ActiveDialog.State);

            if (args is IDictionary <string, object> hash)
            {
                if (hash["LuisResult"] is RecognizerResult luisResult)
                {
                    var title = GetEntity <string>(luisResult, "Media_Title");
                    if (!string.IsNullOrEmpty(title))
                    {
                        inquiry.MediaTitle = title;
                    }

                    var characterName = GetEntity <string>(luisResult, "Media_CharacterName");
                    if (!string.IsNullOrEmpty(characterName))
                    {
                        inquiry.CharacterName = characterName;
                    }

                    dialogContext.ActiveDialog.State = inquiry;
                }
            }

            var(show, episode) = await TraktService.Instance.GetNextEpisode(inquiry.MediaTitle);

            if (show == null)
            {
                var response = $"Hrmm, it doesn't look like there are any shows called '{inquiry.MediaTitle}'.";
                //TODO: Possibly prompt them for an alternate title

                await dialogContext.Context.SendActivity(response);

                await dialogContext.End();

                return;
            }

            //inquiry.Episode = episode;
            //inquiry.Show = show;
            dialogContext.ActiveDialog.State = inquiry;

            if (episode == null)
            {
                var response = $"It doesn't look like {show.Title} has any upcoming episodes.";
                await dialogContext.Context.SendActivity(response);

                await dialogContext.End();
            }
            else
            {
                var response = $"The next episode of {show.Title} will air on {episode.FirstAired.LocalDateTime.ToString("dddd, MMMM d 'at' h:mm tt")} on {show.Network}.";
                await dialogContext.Context.SendActivity(response);

                var userContext = dialogContext.Context.GetUserState <UserState>();
                //userContext.EpisodeInquiries.Add(inquiry);

                await dialogContext.Continue();
            }
        }
Beispiel #3
0
        private async Task BookingRoomStart(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var state = new TechClubAssistantBotState(dialogContext.ActiveDialog.State);

            FillBookingStateFromLuisResult(state, (args as IDictionary <string, object>)?["luisResult"] as LuisResult);

            dialogContext.ActiveDialog.State = state;

            await dialogContext.Context.SendActivity($"Booking meeting room started");

            if (String.IsNullOrEmpty(state.MeetingRoom))
            {
                var choices = MeetingRooms.Select(r => new Choice()
                {
                    Value = r
                }).ToList();
                await dialogContext.Prompt(MeetingRoomPrompt, "Select meeting room: ", new ChoicePromptOptions()
                {
                    Choices = choices
                });
            }
            else
            {
                await dialogContext.Continue();
            }
        }
        // This is the first step of the Order History dialog
        private async Task AskOrderLookupInfo(DialogContext dc, IDictionary<string, object> args, SkipStepFunction next)
        {
            var dialogState = dc.ActiveDialog.State as IDictionary<string, object>;
            if (args != null)
            {
                //Check if the LuisResult contains our email entity or not
                if (args["LuisResult"] is RecognizerResult luisResult)
                {
                    var email = GetEntity<string>(luisResult, "email");
                    if (!string.IsNullOrEmpty(email))
                    {
                        dialogState.Add("EmailAddress", email);
                    }
                }
            }

            // Save info back to the dialog instance
            dc.ActiveDialog.State = dialogState;

            //Now if we don't need it, don't ask the user to answer this question
            if (!dialogState.ContainsKey("EmailAddress"))
            {
                await dc.Context.SendActivity("Great, I just need a few pieces of information from you.");
                await dc.Prompt("emailPrompt", "Can I get your email address for the order?");
            }
            else
            {
                await dc.Context.SendActivity($"Great, I see your email address is {dc.ActiveDialog.State["EmailAddress"]}, now I just need one more piece of information from you.");

                // so go to the next step in the waterfall
                await dc.Continue();
            }
        }
Beispiel #5
0
        // This is the first step of the Order History dialog
        private async Task AskOrderLookupInfo(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            var dialogState = dc.ActiveDialog.State as IDictionary <string, object>;

            if (args != null)
            {
                //Check if the LuisResult contains our tracking number entity or not
                if (args["LuisResult"] is RecognizerResult luisResult)
                {
                    var orderNumber = GetEntity <string>(luisResult, "ordernumber");
                    if (!string.IsNullOrEmpty(orderNumber))
                    {
                        dialogState.Add("OrderNumber", orderNumber);
                    }
                }
            }

            // Save info back to the dialog instance
            dc.ActiveDialog.State = dialogState;

            //Now if we don't need it, don't ask the user to answer this question
            if (!dialogState.ContainsKey("OrderNumber"))
            {
                await dc.Context.SendActivity("Great, I just need one piece of information from you.");

                await dc.Prompt("textPrompt", "Can I get your order number for the order?");
            }
            else
            {
                await dc.Context.SendActivity($"Great, I see your order number is {dc.ActiveDialog.State["OrderNumber"]}, let me go find your tracking number now.");

                // so go to the next step in the waterfall
                await dc.Continue();
            }
        }
Beispiel #6
0
        private async Task AskProvideAdditionalInfo(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var inquiry = new EpisodeInquiry(dialogContext.ActiveDialog.State);

            if (inquiry.Episode == null)
            {
                await dialogContext.Continue();

                return;
            }

            var item = inquiry.Episode.Overview == null ? "show" : "episode";
            var yes  = new Prompts.Choices.Choice {
                Value = "Yes"
            };
            var no = new Prompts.Choices.Choice {
                Value = "No"
            };
            await dialogContext.Prompt("ProvideAdditionalInfoPrompt", $"Would you like to see additional info about this {item}?", new ChoicePromptOptions()
            {
                Choices = new List <Prompts.Choices.Choice> {
                    yes, no
                }
            });
        }
        /// <summary>
        /// Method to authenticate the user.
        /// </summary>
        private async Task AuthenticateStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            // Load ConversationModel.json
            var service           = new ConversationModelService();
            var conversationModel = service.ConversationModel();

            if (!conversationModel.AuthenticationType.Equals(AuthenticationTypes.None))
            {
                // Auth will come through ChannelData
                switch (conversationModel.AuthenticationType)
                {
                case AuthenticationTypes.ChannelData:
                    if (dialogContext.Context.Activity.ChannelData != null)
                    {
                        var channelData = JsonConvert.DeserializeObject <Dictionary <string, string> >(dialogContext.Context.Activity.ChannelData.ToString());
                        channelData.TryGetValue("UserName", out string userName);
                        channelData.TryGetValue("Token", out string token);

                        // User is signed in
                        if (!token.Equals(string.Empty) && !userName.Equals(string.Empty))
                        {
                            // TODO: Act on the token
                            await dialogContext.Context.SendActivity($"Ok, {userName}.", $"Ok, {userName}.");

                            await dialogContext.Continue();
                        }
                        // User is not signed in
                        else
                        {
                            await dialogContext.Context.SendActivity("Please sign into your account.", "Please sign into your account.", InputHints.AcceptingInput);

                            await dialogContext.End();
                        }
                    }
                    break;

                // TODO: other types of auth
                default:
                    break;
                }
            }
            else
            {
                await dialogContext.Continue();
            }
        }
Beispiel #8
0
        public async Task OnTurn(ITurnContext context)
        {
            Dictionary <string, object> state = ConversationState <Dictionary <string, object> > .Get(context);

            DialogContext dc = dialogos.CreateContext(context, state);
            await dc.Continue();

            if (context.Activity.Type == ActivityTypes.Message)
            {
                RecognizerResult resultado = context.Services.Get <RecognizerResult>(LuisRecognizerMiddleware.LuisRecognizerResultKey);

                var intencaoMaisPontuada = resultado?.GetTopScoringIntent();
                if (!context.Responded)
                {
                    IDictionary <string, object> argumentos = new Dictionary <string, object>();

                    if (this.ObterEntidade <string>(resultado, "Cidade") != null)
                    {
                        argumentos.Add("Cidade", this.ObterEntidade <string>(resultado, "Cidade"));
                    }

                    if (this.ObterEntidade <string>(resultado, "Tamanho") != null)
                    {
                        argumentos.Add("Tamanho", this.ObterEntidade <string>(resultado, "Tamanho"));
                    }

                    if (this.ObterEntidade <string>(resultado, "Sabor") != null)
                    {
                        argumentos.Add("Sabor", this.ObterEntidade <string>(resultado, "Sabor"));
                    }

                    switch ((intencaoMaisPontuada != null) ? intencaoMaisPontuada.Value.intent : null)
                    {
                    case "None":
                        await context.SendActivity("Não entendi.");

                        break;

                    case "PedirPizza":
                        await dc.Begin("pedirPizza", argumentos);

                        break;

                    case "PrevisaoTempo":
                        await dc.Begin("previsaoTempo", argumentos);

                        break;

                    case "MarcarConsulta":
                        await dc.Begin("marcarConsulta");

                        break;
                    }
                }
            }
        }
Beispiel #9
0
        private async Task AskNameStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <EchoState>();

            if (state.RecipientName != null)
            {
                await dialogContext.Continue();
            }

            await dialogContext.Prompt(PromptStep.NamePrompt, "What is your name?");

            var t = "";
        }
        private async Task AskReminderTitle(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var reminder = new Reminder(dialogContext.ActiveDialog.State);

            dialogContext.ActiveDialog.State = reminder;
            if (!string.IsNullOrEmpty(reminder.Title))
            {
                await dialogContext.Continue();
            }
            else
            {
                await dialogContext.Prompt("TitlePrompt", "What would you like to call your reminder?");
            }
        }
Beispiel #11
0
        public async Task OnTurn(ITurnContext context)
        {
            Dictionary <string, object> state = ConversationState <Dictionary <string, object> > .Get(context);

            DialogContext dc = dialogos.CreateContext(context, state);
            await dc.Continue();

            if (context.Activity.Type == ActivityTypes.Message)
            {
                if (!context.Responded)
                {
                    await dc.Begin("PedirPizaa");
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Method to collect info from the user.
        /// </summary>
        private async Task CollectStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            // Check to see if info was already collected
            var state     = dialogContext.Context.GetConversationState <Dictionary <string, object> >();
            var collected = state.TryGetValue(collectSteps[0].PropertyName, out object userInput);

            if (collected)
            {
                // If found, remove this step from the dialog and continue
                collectSteps.Remove(collectSteps[0]);
                await dialogContext.Continue();
            }
            else
            {
                // Prompt for info
                var options = new PromptOptions
                {
                    Speak = collectSteps[0].Value,
                };
                await dialogContext.Prompt($"{collectSteps[0].EntityName}Prompt", collectSteps[0].Value, options);
            }
        }
Beispiel #13
0
        private async Task BookingRoomDuration(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var state = new TechClubAssistantBotState(dialogContext.ActiveDialog.State);

            dialogContext.ActiveDialog.State = state;

            if (args is Microsoft.Bot.Builder.Prompts.DateTimeResult result)
            {
                state.Time = result.Text;
            }

            if (String.IsNullOrEmpty(state.Duration))
            {
                await dialogContext.Prompt(DurationPrompt, "Enter duration: ", new PromptOptions()
                {
                    RetryPromptString = "Please enter correct duration"
                });
            }
            else
            {
                await dialogContext.Continue();
            }
        }
Beispiel #14
0
        private async Task BookingRoomTime(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var state = new TechClubAssistantBotState(dialogContext.ActiveDialog.State);

            dialogContext.ActiveDialog.State = state;


            if (args is Microsoft.Bot.Builder.Prompts.ChoiceResult choiceResult)
            {
                state.MeetingRoom = choiceResult.Value.Value;
            }

            if (String.IsNullOrEmpty(state.Time))
            {
                await dialogContext.Prompt(TimePrompt, "Enter date and time: ", new PromptOptions()
                {
                    RetryPromptString = "Please enter correct date and time"
                });
            }
            else
            {
                await dialogContext.Continue();
            }
        }
Beispiel #15
0
        public async Task OnTurn(ITurnContext context)
        {
            //TODO: is this the right way to handle cards?
            string  utterance = context.Activity.Text;
            JObject cardData  = (JObject)context.Activity.Value;

            if (cardData != null && cardData.Property("intent") != null)
            {
                utterance = cardData["utterance"].ToString();
            }
            System.Threading.CancellationToken ct;

            CafeBotUserState userState         = context.GetUserState <CafeBotUserState>();
            CafeBotConvState conversationState = context.GetConversationState <CafeBotConvState>();

            switch (context.Activity.Type)
            {
            case ActivityTypes.ConversationUpdate:
                var newUserName = context.Activity.MembersAdded[0].Name;
                if (!string.IsNullOrWhiteSpace(newUserName) && newUserName != "Bot")
                {
                    await context.SendActivity($"Hello {newUserName}! I'm the Cafe bot!");

                    // remember the user's name
                    userState.name = newUserName;

                    userState.sendCards = true;

                    await context.SendActivity("I can help you find contoso cafe locations, book a table and answer questions about Contoso cafe!");

                    // send a welcome card
                    if (userState.sendCards)
                    {
                        await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                    }
                }
                break;

            case ActivityTypes.Message:
                // create dialogContext
                DialogContext dc = _dialogs.CreateContext(context, conversationState);


                if (utterance == "start over")
                {
                    //restart the conversation
                    await context.SendActivity("Sure.. Let's start over");

                    dc.EndAll();
                }
                else
                {
                    // continue with any active dialogs
                    await dc.Continue();
                }

                if (!context.Responded)
                {
                    // call LUIS and get results
                    LuisRecognizer lRecognizer = createLUISRecognizer();
                    cafeLUISModel  lResult     = await lRecognizer.Recognize <cafeLUISModel>(utterance, ct);

                    Dictionary <string, object> lD = new Dictionary <string, object>();
                    if (lResult != null)
                    {
                        lD.Add("luisResult", lResult);
                    }

                    // top level dispatch
                    switch (lResult.TopIntent().intent)
                    {
                    case cafeLUISModel.Intent.Greeting:
                        await context.SendActivity("Hello, I'm the contoso cafe bot. How can I help you?");

                        if (userState.sendCards)
                        {
                            await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                        }
                        break;

                    case cafeLUISModel.Intent.Book_Table:
                        await dc.Begin("BookTable", lD);

                        break;

                    case cafeLUISModel.Intent.Who_are_you_intent:
                        await dc.Begin("WhoAreYou");

                        break;

                    case cafeLUISModel.Intent.None:
                    default:
                        await getQnAResult(context);

                        break;
                    }
                }
                break;
            }
        }
Beispiel #16
0
        public async Task OnTurn(ITurnContext context)
        {
            //TODO: is this the right way to handle cards?
            string  utterance = context.Activity.Text;
            JObject cardData  = (JObject)context.Activity.Value;

            if (cardData != null && cardData.Property("intent") != null)
            {
                utterance = cardData["utterance"].ToString();
            }

            var userState         = context.GetUserState <CafeBotUserState>();
            var conversationState = context.GetConversationState <CafeBotConvState>();

            switch (context.Activity.Type)
            {
            case ActivityTypes.ConversationUpdate:
                var newUserName = context.Activity.MembersAdded[0].Name;
                if (!string.IsNullOrWhiteSpace(newUserName) && newUserName != "Bot")
                {
                    await context.SendActivity($"Hello {newUserName}! I'm the Cafe bot!");

                    // remember the user's name
                    userState.name = newUserName;

                    userState.sendCards = true;

                    await context.SendActivity("I can help you find contoso cafe locations, book a table and answer questions about Contoso cafe!");

                    // send a welcome card
                    if (userState.sendCards)
                    {
                        await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                    }
                }
                break;

            case ActivityTypes.Message:

                // create dialogContext
                DialogContext dc = _dialogs.CreateContext(context, conversationState);

                if (utterance == "start over")
                {
                    //restart the conversation
                    await context.SendActivity("Sure.. Let's start over");

                    dc.EndAll();
                }
                else
                {
                    // continue with any active dialogs
                    await dc.Continue();
                }
                if (!context.Responded)
                {
                    // top level dispatch
                    switch (utterance)
                    {
                    case "hi":
                        await context.SendActivity("Hello, I'm the contoso cafe bot. How can I help you?");

                        if (userState.sendCards)
                        {
                            await context.SendActivity(CreateCardResponse(context.Activity, createWelcomeCardAttachment()));
                        }
                        break;

                    case "book table":
                        // await context.SendActivity("I'm still learning to book a table!");
                        // start waterfall dialog for table booking
                        await dc.Begin("BookTable");

                        break;

                    case "who are you?":
                        // await context.SendActivity("I'm the cafe bot!");
                        // start waterfall dialog for who are you?
                        await dc.Begin("WhoAreYou");

                        break;

                    default:
                        await getQnAResult(context);

                        break;
                    }
                }
                break;
            }
        }
Beispiel #17
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}");
            }
        }