예제 #1
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();
            }
        }
예제 #2
0
        private async Task BookingRoomFinish(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var state = new TechClubAssistantBotState(dialogContext.ActiveDialog.State);

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

            if (state.IsConfirmed)
            {
                var bookingResult = await _meetingRoomBookingService.BookMeetingRoomAsync(new BookingRequest()
                {
                    MeetingRoom = state.MeetingRoom, Time = state.Time, Duration = state.Duration
                });

                await dialogContext.Context.SendActivity($"Your booking was processed.");
            }
            else
            {
                await dialogContext.Context.SendActivity($"Your booking was cancelled");
            }

            await dialogContext.End();
        }
예제 #3
0
        private async Task ShowHelpStep(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            await dialogContext.Context.SendActivity("These are the commands I support:\n" +
                                                     ".... To be implemented");

            await dialogContext.End();
        }
예제 #4
0
        private async Task ShowProductCarouselStep(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            var context       = dc.Context;
            var catalogFilter = dc.Context.GetUserState <UserInfo>().CatalogFilter;

            var products = await GetProducts(catalogFilter, catalogAIService, catalogService);

            int pageCount = (products.Count + CatalogFilterData.PageSize - 1) / CatalogFilterData.PageSize;

            if (products.Count != 0)
            {
                const bool logged           = false;
                const bool supportsMarkdown = false;
                var        text             = $"Page {catalogFilter.PageIndex + 1} of {pageCount} ( {products.Count} items )";
                var        items            = CatalogCarousel(products, logged, supportsMarkdown);
                await context.SendActivities(new[]
                {
                    MessageFactory.Carousel(items, text),
                    MessageFactory.SuggestedActions(CreateNextButtons(catalogFilter.PageIndex, pageCount, logged), "choose one option")
                });
            }
            else
            {
                await context.SendActivities(new[] {
                    MessageFactory.Text("There are no results matching your search"),
                    MessageFactory.Text("Type what do you want to do.")
                });

                await dc.End();
            }
        }
예제 #5
0
        private async Task ProvideAdditionalEpisodeInfo(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var inquiry = new EpisodeInquiry(dialogContext.ActiveDialog.State);

            if (args is Prompts.ChoiceResult result)
            {
                inquiry.ProvideAdditionalInfo = result.Value.Value == "Yes";
            }

            if (inquiry.ProvideAdditionalInfo)
            {
                if (inquiry.Episode.Overview != null)
                {
                    var response = $"Summary: {inquiry.Episode.Overview}";
                    await dialogContext.Context.SendActivity(response);
                }

                var imageUrl = await TmdbService.Instance.GetShowImageUrlLandscape(inquiry.Show.Ids.Tmdb);

                var activity = MessageFactory.Attachment(GetInternetAttachment(imageUrl, inquiry.Show.Title));
                await dialogContext.Context.SendActivity(activity);
            }

            await dialogContext.End();
        }
예제 #6
0
        private async Task GatherInfoStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state   = dialogContext.Context.GetConversationState <BotState>();
            var context = dialogContext.Context;

            state.Name = (result as TextResult).Value;

            var teacher = new Student(context.Activity.From.Id,
                                      state.Name,
                                      Constants.TeachersGroupName,
                                      new List <string>(),
                                      new StudentChannelInfo
            {
                ToId           = context.Activity.From.Id,
                ToName         = context.Activity.From.Name,
                FromId         = context.Activity.Recipient.Id,
                FromName       = context.Activity.Recipient.Name,
                ServiceUrl     = context.Activity.ServiceUrl,
                ChannelId      = context.Activity.ChannelId,
                ConversationId = context.Activity.Conversation.Id
            },
                                      true);

            state.RegistrationComplete = true;
            state.Id = teacher.Id;

            await DatabaseProvider.AddStudent(teacher);

            await dialogContext.Context.SendActivity("Вы зарегистрированны.");

            await dialogContext.End();
        }
        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();
            }
        }
예제 #8
0
        public async Task DialogBegin(DialogContext dc, IDictionary <string, object> dialogArgs = null)
        {
            var message = dc.Context.Activity.Text;

            if (!string.IsNullOrEmpty(message))
            {
                ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                {
                    Endpoint = "https://westeurope.api.cognitive.microsoft.com"
                };


                var result = client.DetectLanguageAsync(new BatchInput(
                                                            new List <Input>()
                {
                    new Input("1", message)
                })).Result;

                foreach (var document in result.Documents)
                {
                    await dc.Context.SendActivity(document.DetectedLanguages[0].Name);
                }

                await dc.End();
            }
            else
            {
                await dc.Context.SendActivity("Введите текст для распознавания языка");
            }
        }
예제 #9
0
        /// <summary>
        /// Method to finish the order after all info is collected.
        /// Sends a response and clears the order details.
        /// </summary>
        private async Task CompleteOrder(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            // Get the current dialog
            var service           = new ConversationModelService();
            var conversationModel = service.ConversationModel();

            // Send the flow's outcome response with the user's inputed values
            var   state    = dialogContext.Context.GetConversationState <Dictionary <string, object> >();
            Regex _regex   = new Regex(@"\{(\w+)\}", RegexOptions.Compiled);
            var   response = _regex.Replace(conversationModel.Outcome.Value,
                                            match => state[service.GetPrompt(match.Groups[1].Value).PropertyName].ToString());
            await dialogContext.Context.SendActivity(response, response, InputHints.AcceptingInput);

            // TODO: Business logic to process the user's inputed values would go here

            // Clear the user's inputed values for the current dialog
            foreach (var entity in conversationModel.Entities)
            {
                state.Remove(service.GetPrompt(entity).PropertyName);
            }

            // End dialog
            stepsCollected = false;
            await dialogContext.End();
        }
예제 #10
0
        private async Task ProcessNextStep(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            var catalogFilter  = dc.Context.GetUserState <UserInfo>().CatalogFilter;
            var selectedAction = (args["Activity"] as Activity)?.Text?.Trim();

            dynamic activityResponse;

            try
            {
                activityResponse = JsonConvert.DeserializeObject(selectedAction);
            } catch (Exception ex)
            {
                await dc.Context.SendActivity("I didn't understand your response. Please click on a button");

                await dc.Replace(Id);

                return;
            }
            if (activityResponse.ActionType == BotActionTypes.Back)
            {
                await dc.Context.SendActivity("Type what do you want to do.");

                await dc.End();
            }
            //else if (activityResponse.ActionType == BotActionTypes.CatalogFilter)
            //{
            //    await dc.Replace(CatalogFilterDialog.Id);
            //}
            else
            {
                catalogFilter.PageIndex++;
                await dc.Replace(Id);
            }
        }
예제 #11
0
        private async Task PassProductToShoppingCartOnWebsite(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            List <SKU> skus = (List <SKU>)dc.ActiveDialog.State["skus"];

            var chosenSku = skus[(int)dc.ActiveDialog.State["chosenChoice"]];

            var qtyrResult = (NumberResult <int>)args;

            await dc.Context.SendActivity($"Thank you, but we are not ready to receive payment right now. Please continue to our e-commerce store to finalize your purchase.");

            var activity = MessageFactory.Attachment(
                new HeroCard(
                    title: "",
                    images: new CardImage[] { new CardImage(url: $"http://dg11.bizstreamcms.com/getmedia/a9d1644a-1cdf-467a-afae-668213d9ee7d/dg_logo.aspx") },
                    buttons: new CardAction[]
            {
                new CardAction(
                    title: "Continue Purchase",
                    type: ActionTypes.OpenUrl,
                    value: $"http://dg11.bizstreamcms.com/Store/Checkout/Shopping-cart?skuid={chosenSku.SKUID}&qty={qtyrResult.Value}"
                    )
            })
                .ToAttachment());

            await dc.Context.SendActivity(activity);

            await dc.End(dc.ActiveDialog.State);
        }
예제 #12
0
        private async Task DonePrompt(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            await Respond(dc, args);

            await dc.Context.SendActivity("The End");

            await dc.End();
        }
예제 #13
0
        private async Task GatherInfoStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <ClaimStateModel>();

            state.FullName = (result as TextResult).Value;
            await dialogContext.Context.SendActivity($"Your name is {state.FullName}, great!");

            await dialogContext.End();
        }
예제 #14
0
        private async Task GatherInfoStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <EchoState>();

            state.CardPin = (result as NumberResult <int>).Value;
            await dialogContext.Context.SendActivity($"Your name is {state.RecipientName} and your age is {state.CardPin}");

            await dialogContext.End();
        }
        private async Task GatherInfoStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <MultiplePromptsState>();

            state.Age = (result as NumberResult <int>).Value;
            await dialogContext.Context.SendActivity($"Your name is {state.Name} and your age is {state.Age}");

            await dialogContext.End();
        }
예제 #16
0
        private async Task LogoutPromptStep(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var userState = dialogContext.Context.GetUserState <UserState>();

            userState.AccessToken = null;

            await dialogContext.Context.SendActivity("You are now signed out");

            await dialogContext.End();
        }
예제 #17
0
        private async Task ConfirmShow(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var userContext = dialogContext.Context.GetUserState <UserState>();

            if (args is Prompts.ChoiceResult choice)
            {
                var reminder = userContext.Reminders[choice.Value.Index];
                await dialogContext.Context.SendActivity($"Reminder: {reminder.Title}");
            }
            await dialogContext.End();
        }
예제 #18
0
        private async Task WaterfallStep3(DialogContext dc, object args, SkipStepFunction next)
        {
            if (args != null)
            {
                var numberResult = (NumberResult <int>)args;
                await dc.Context.SendActivity($"Thanks for '{numberResult.Value}'");
            }
            await dc.Context.SendActivity("step3");

            await dc.End();
        }
예제 #19
0
        private async Task DoneStep(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            string message;
            string speaker = dc.ActiveDialog.State["speakerName"].ToString();
            string session = dc.ActiveDialog.State["sessionName"].ToString();

            message = $"Thanks for providing feedback for {session} presented by {speaker}.";

            await dc.Context.SendActivity(message);

            await dc.End();
        }
예제 #20
0
        private static async Task Waterfall2_Step3(DialogContext dc, object args, SkipStepFunction next)
        {
            if (args != null)
            {
                var numberResult = (NumberResult <int>)args;
                await dc.Context.SendActivity($"Thanks for '{numberResult.Value}'");
            }
            await dc.Context.SendActivity("step3");

            await dc.End(new Dictionary <string, object> {
                { "Value", "All Done!" }
            });
        }
예제 #21
0
        /// <summary>
        /// Check if user is not already authenticated (and if so, also check that the access token is still
        /// valid), and if not prompt the user to sign in.
        /// </summary>
        private async Task RedirectToLoginStep(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            if (!string.IsNullOrEmpty(dialogContext.Context.Activity.ChannelId))
            {
                // TODO Show warning that we are not in a private conversation and end flow
            }

            var userState = dialogContext.Context.GetUserState <UserState>();

            if (!string.IsNullOrEmpty(userState.AccessToken))
            {
                // TODO Verify access token still works, and don't skip if access token is bad
                var stillValid = true;
                if (stillValid)
                {
                    await next();

                    return;
                }
            }

            userState.AccessToken = null;

            await dialogContext.Context.SendActivity(new Activity
            {
                Type        = ActivityTypes.Message,
                Attachments = new List <Attachment>
                {
                    new HeroCard
                    {
                        Title   = "Please log in to MsTeamsBot",
                        Text    = "Click below to log in to MyAwesomeProduct(tm), to start using all the great features",
                        Buttons = new List <CardAction>
                        {
                            new CardAction
                            {
                                Type  = "signin",
                                Title = "Log-in",
                                Text  = "Log-in",
                                Value = _loginStartUrl
                            }
                        }
                    }.ToAttachment()
                }
            });

            // Don't continue, AuthenticationMiddleware will trigger confirmation when completed
            await dialogContext.End();
        }
예제 #22
0
        private async Task SaveReminder(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var reminder = new Reminder(dialogContext.ActiveDialog.State);

            if (args is Prompts.TextResult textResult)
            {
                reminder.Title = textResult.Value;
            }
            await dialogContext.Context.SendActivity($"Your reminder named '{reminder.Title}' is set.");

            var userContext = dialogContext.Context.GetUserState <UserState>();

            userContext.Reminders.Add(reminder);
            await dialogContext.End();
        }
예제 #23
0
        private async Task AskNameStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <BotState>();

            if ((result as TextResult).Value != Configuration[Constants.TeacherRegistrationTokenKey])
            {
                await dialogContext.Context.SendActivity("Неверный ключ регистрации!");

                await dialogContext.End();
            }
            else
            {
                await dialogContext.Prompt(PromptStep.NamePrompt, "Введите ФИО:");
            }
        }
예제 #24
0
        private async Task DonePrompt(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            string message;

            if ((bool)args["Confirmation"] == true)
            {
                message = "Order Placed";
            }
            else
            {
                message = "Order Cancelled";
            }
            await dc.Context.SendActivity(message);

            await dc.End();
        }
        private async Task ReturnOrderHistory(DialogContext dc, IDictionary<string, object> args, SkipStepFunction next)
        {
            var message = string.Empty;

            //Grab the response and save it to state
            TextResult zipResult = (TextResult)args;
            dc.ActiveDialog.State["ZipCode"] = zipResult.Text;

            var email = dc.ActiveDialog.State["EmailAddress"].ToString();

            //Find customer by email
            Customer c = await _kenticoRestService.GetEcommerceCustomerByEmail(email);
            if (c.CustomerID > 0)
            {
                message += $"Thank you {c.CustomerFirstName}, ";

                List<Order> orders = await _kenticoRestService.GetEcommerceOrdersByCustomer(c.CustomerID, zipResult.Text);
                if (orders.Count > 0)
                {
                    message += $"we found {orders.Count} orders with that email address.\n";

                    int i = 1;
                    foreach (Order o in orders)
                    {
                        message += $"{i}. On {o.OrderDate}\n Order #**{o.OrderNumber}** was placed for a total of **{o.OrderTotalPrice:c}**.\n This order has a status of **{o.OrderStatusName}**.\n";
                        foreach (OrderItem oi in o.OrderItems)
                        {
                            message += $"* {oi.SkuName} ({oi.Quantity} @ {oi.ItemPrice:c})\n";
                        }
                        i++;
                        message += "\n";
                    }
                }
                else
                {
                    message += $"I was unable to find orders for that customer, or the zip code that was provided ({zipResult.Text}) didn't match.";
                }
            }
            else
            {
                message += $"However, I'm sorry we could not find any customers with an email address of {email}";
            }

            await dc.Context.SendActivity(message);

            await dc.End(dc.ActiveDialog.State);
        }
        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();
        }
예제 #27
0
        /// <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();
            }
        }
예제 #28
0
        /// <summary>
        /// Show login information
        /// </summary>
        private async Task ShowLoginConfirmation(DialogContext dialogContext, object args, SkipStepFunction next)
        {
            var userState = dialogContext.Context.GetUserState <UserState>();

            if (!string.IsNullOrEmpty(userState.AccessToken))
            {
                await dialogContext.Context.SendActivity(
                    $"Hello {userState.FullName}, you are signed in as {userState.Email}\n" +
                    $"Type '`logout`' if you want to log out again");
            }
            else
            {
                await dialogContext.Context.SendActivity("Something went wrong, please try again");
            }

            await dialogContext.End();
        }
        public async Task DialogBegin(DialogContext dc, IDictionary <string, object> dialogArgs = null)
        {
            var message = dc.Context.Activity.Text;

            if (!string.IsNullOrEmpty(message))
            {
                var textBytes  = System.Text.Encoding.UTF8.GetBytes(message);
                var base64text = System.Convert.ToBase64String(textBytes);

                await dc.Context.SendActivity(base64text);

                await dc.End();
            }
            else
            {
                await dc.Context.SendActivity("Введите текст для преобразования в base64:");
            }
        }
예제 #30
0
        public async Task DialogBegin(DialogContext dc, IDictionary <string, object> dialogArgs = null)
        {
            var message = dc.Context.Activity.Text;

            if (!string.IsNullOrEmpty(message))
            {
                var base64EncodedBytes = System.Convert.FromBase64String(message);
                var normalText         = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

                await dc.Context.SendActivity(normalText);

                await dc.End();
            }
            else
            {
                await dc.Context.SendActivity("Введите base64 текст");
            }
        }