Beispiel #1
0
        private async Task <DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            if (innerDc.Context.Activity.Type == ActivityTypes.Message)
            {
                var text = innerDc.Context.Activity.Text.ToLowerInvariant();

                switch (text)
                {
                case "ayuda":
                case "?":
                    var helpMessage = MessageFactory.Text(HelpMsgText, HelpMsgText, InputHints.ExpectingInput);
                    await innerDc.Context.SendActivityAsync(helpMessage, cancellationToken);

                    await innerDc.RepromptDialogAsync(cancellationToken);

                    return(new DialogTurnResult(DialogTurnStatus.Waiting));

                case "cancelar":
                case "salir":
                    var cancelMessage = MessageFactory.Text(CancelMsgText, CancelMsgText, InputHints.IgnoringInput);
                    await innerDc.Context.SendActivityAsync(cancelMessage, cancellationToken);

                    return(await innerDc.CancelAllDialogsAsync(cancellationToken));
                }
            }

            return(null);
        }
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. I've canceled our last activity.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }

                return(true);
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                await dc.Context.SendActivityAsync("I order pizzas on Fridays, being asked for help, or being asked to cancel what I am doing.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);
            }

            return(false);
        }
Beispiel #3
0
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. I've canceled our last activity.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }
                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                await dc.Context.SendActivityAsync("I can tell price of stocks, understand being asked for help, or being asked to cancel what I am doing. Try typing 'What is the price of Microsoft?'");

                await dc.Context.SendActivityAsync("Jobs in queue: " + PortfolioPushService.QueueSize + ": " + PortfolioPushService.Queue);

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }
                return(true);        // Handled the interrupt.
            }

            return(false);           // Did not handle the interrupt.
        }
Beispiel #4
0
        // Determine if an interruption has occured before we dispatch to any active dialog.
        private static async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(StopIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Sorry, I haven't noticed that the context changed. How can I help you?");
                }
                else
                {
                    await dc.Context.SendActivityAsync("How can I help you?");
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                await dc.Context.SendActivityAsync("You can ask me about the state of your reservations, ask to make a new reservation for you or confirm the key drop-off.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }

            return(false);           // Did not handle the interrupt.
        }
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. Anulowałem ostatnią aktywność.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("Nie mam niczego co mógłbym anulować.");
                }

                return(true);
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Już służę pomocą.");

                await dc.Context.SendActivityAsync("Zamawiam pizze w piątki, udzielam pomocy lub anuluję to co robię.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);
            }

            return(false);
        }
        // Determine if an interruption has occurred before we dispatch to any active dialog.
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. I've canceled our last activity.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                await dc.Context.SendActivityAsync("I understand greetings, being asked for help, or being asked to cancel what I am doing.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }

            return(false);           // Did not handle the interrupt.
        }
Beispiel #7
0
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResultKey);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_responseManager.GetResponse(POISharedResponses.CancellingMessage));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_responseManager.GetResponse(POIMainResponses.HelpMessage));

                        await innerDc.RepromptDialogAsync();

                        interrupted = true;
                        break;
                    }

                    case General.Intent.Logout:
                    {
                        // Log user out of all accounts.
                        await LogUserOut(innerDc);

                        await innerDc.Context.SendActivityAsync(_responseManager.GetResponse(POIMainResponses.LogOut));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralLuisResult);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case GeneralLuis.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("CancelledMessage"));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }

                    case GeneralLuis.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("HelpCard"));

                        await innerDc.RepromptDialogAsync();

                        interrupted = true;
                        break;
                    }

                    case GeneralLuis.Intent.Logout:
                    {
                        // Log user out of all accounts.
                        await LogUserOut(innerDc);

                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("LogoutMessage"));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #9
0
        public async Task Handle(DialogContext ctx)
        {
            var answerState = await _answersStateAccessor.GetAsync(ctx.Context);

            var targets = await _targetSetupStateAccessor.GetAsync(ctx.Context) ?? new TargetSetupState();

            if ((answerState?.Questions.Count ?? 0) == 0)
            {
                await ctx.Context.Senddd("You need to answer questions at least once");
            }
            else
            {
                var allQuestions = answerState.Questions.ToArray();
                var last3Weeks   = allQuestions.Reverse().Take(21)
                                   .Select((x, i) => (stats: x, week: Math.Floor((float)i / 7)))
                                   .GroupBy(x => x.week)
                                   .Select(x => (
                                               week: x.Key,
                                               averageActivity: x.Select(a => a.stats.ActivityScore).Cast <int>().Average() * 5,
                                               averageFood: x.Select(a => a.stats.FoodScore).Cast <int>().Average() * 5,
                                               averageSleep: x.Select(a => a.stats.SleepScore).Cast <int>().Average() * 5
                                               ))
                                   .ToArray()
                                   .Reverse()
                                   .ToArray();

                var baseWeek = (DateProvider.CurrentDateForBot.DayOfYear - 7 + (int)(new DateTime(2019, 01, 01).DayOfWeek)) / 7 + 1;

                var activityTrend = last3Weeks
                                    .Select((x, i) => (week: baseWeek + i, value: x.averageActivity, change: i == 0 ? "●" : ChangeOf(x.averageActivity, last3Weeks[i - 1].averageActivity)))
                                    .ToArray();
                var foodTrend = last3Weeks
                                .Select((x, i) => (week: baseWeek + i, value: x.averageFood, change: i == 0 ? "●" : ChangeOf(x.averageFood, last3Weeks[i - 1].averageFood)))
                                .ToArray();
                var sleepTrend = last3Weeks
                                 .Select((x, i) => (week: baseWeek + i, value: x.averageSleep, change: i == 0 ? "●" : ChangeOf(x.averageSleep, last3Weeks[i - 1].averageSleep)))
                                 .ToArray();

                await ctx.Context.Senddd($"These are your results from last {Math.Max(21, allQuestions.Length)} days:");

                await ctx.Context.Senddd(string.Join("\n", new []
                {
                    $"Activity Habits [target: {targets.Activity}]\n\n- {string.Join("\n- ", activityTrend.Select(x => $"{x.change} week {x.week}: **{x.value:0.0}**"))}",
                    $"Food Habits [target: {targets.Food}]\n\n- {string.Join("\n- ", foodTrend.Select(x => $"{x.change} week {x.week}: **{x.value:0.0}**"))}",
                    $"Sleep Habits [target: {targets.Sleep}]\n\n- {string.Join("\n- ", sleepTrend.Select(x => $"{x.change} week {x.week}: **{x.value:0.0}**"))}",
                }));
            }

            if (ctx.ActiveDialog != null)
            {
                await ctx.RepromptDialogAsync();
            }
        }
Beispiel #10
0
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            DialogTurnResult interrupted = null;
            var activity = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResult);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        var state = await _conversationStateAccessor.GetAsync(innerDc.Context, () => new RestaurantBookingState(), cancellationToken);

                        state.Clear();

                        await innerDc.Context.SendActivityAsync(_localeTemplateManager.GenerateActivity(RestaurantBookingSharedResponses.CancellingMessage), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult { ActionSuccess = false } : null, cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_localeTemplateManager.GenerateActivity(RestaurantBookingMainResponses.HelpMessage), cancellationToken);

                        await innerDc.RepromptDialogAsync(cancellationToken);

                        interrupted = EndOfTurn;
                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
        public override async Task RepromptDialogAsync(ITurnContext turnContext, DialogInstance instance, CancellationToken cancellationToken = default)
        {
            // Forward to current sequence step
            var state = (instance.State as Dictionary <string, object>)[AdaptiveKey] as AdaptiveDialogState;

            if (state.Actions.Any())
            {
                // We need to mockup a DialogContext so that we can call RepromptDialog
                // for the active step
                var stepDc = new DialogContext(this.Dialogs, turnContext, state.Actions[0]);
                await stepDc.RepromptDialogAsync(cancellationToken).ConfigureAwait(false);
            }
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            DialogTurnResult interrupted = null;
            var activity = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResult);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(MainStrings.CANCELLED), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            var state = await _stateAccessor.GetAsync(innerDc.Context, () => new NewsSkillState(), cancellationToken : cancellationToken);

                            interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult(false) : null, cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(HeroCardResponses.SendHelpCard(innerDc.Context, _templateManager), cancellationToken);

                        await innerDc.RepromptDialogAsync(cancellationToken);

                        interrupted = EndOfTurn;
                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
        protected async Task <bool> DetourIntentAsync(DialogContext dialogContext, DetourIntent intent)
        {
            IActivity[] activities = intent.DetourActivities;

            foreach (var activity in activities)
            {
                await dialogContext.Context.SendActivityAsync(activity);
            }

            if (dialogContext.ActiveDialog != null)
            {
                await dialogContext.RepromptDialogAsync();
            }

            return(true);
        }
Beispiel #14
0
        public async Task Handle(DialogContext ctx)
        {
            await ctx.Context.Senddd("Here are some commands you could try:");

            await ctx.Context.Senddd(@"
- **target** - set your targets for Activity, Food and Sleep habits scores
- **start** - (optionally) you could prompt me to start daily questions
- **stats** - I can print snapshot of your current statistics
- **progress** - I can show you how your performance improved over time
- **cancel** - Abort current conversation
");

            if (ctx.ActiveDialog != null)
            {
                await ctx.RepromptDialogAsync();
            }
        }
Beispiel #15
0
        // Determine if an interruption has occured before we dispatch to any active dialog.
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. I've cancelled our last activity.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                var result = await _qnaService.GetQnAAnswer(dc.Context.Activity.Text);

                if (result.answers[0].answer.Contains("No good match found in KB."))
                {
                    await dc.Context.SendActivityAsync("Sorry that did not work out! Please try another query");
                }
                else
                {
                    await dc.Context.SendActivityAsync(result.answers[0].answer);
                }

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }

            return(false);           // Did not handle the interrupt.
        }
        protected override async Task <DialogTurnResult> OnContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken)
        {
            var status = await OnDialogInterruptionAsync(dc, cancellationToken);

            if (status == InterruptionStatus.Interrupted)
            {
                // Resume the waiting dialog after interruption
                await dc.RepromptDialogAsync().ConfigureAwait(false);

                return(EndOfTurn);
            }
            else if (status == InterruptionStatus.Waiting)
            {
                // Stack is already waiting for a response, shelve inner stack
                return(EndOfTurn);
            }

            return(await base.OnContinueDialogAsync(dc, cancellationToken));
        }
Beispiel #17
0
        // Determine if an interruption has occured before we dispatch to any active dialog.
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    await dc.Context.SendActivityAsync("Ok. I've cancelled our last activity.");
                }
                else
                {
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                await DisplayHelp(dc.Context);

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }

            if (dc.Context.Activity.From.Id.ToLower().Equals("probot"))
            {
                string message = dc.Context.Activity.Text;

                await dc.Context.SendActivityAsync($"Thanks for the update probot \r\n{message}");

                await _notificationService.NotifyChannels(dc.Context, AppId, message);
            }

            return(false);           // Did not handle the interrupt.
        }
Beispiel #18
0
        /// <summary>
        /// Called when the dialog is continued, where it is the active dialog and the
        /// user replies with a new activity.
        /// </summary>
        /// <param name="innerDc">The inner <see cref="DialogContext"/> for the current turn of conversation.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <remarks>If the task is successful, the result indicates whether the dialog is still
        /// active after the turn has been processed by the dialog. The result may also contain a
        /// return value.
        ///
        /// By default, this calls <see cref="InterruptableDialog.OnInterruptDialogAsync(DialogContext, CancellationToken)"/>
        /// then routes the activity to the waiting active dialog, or to a handling method based on its activity type.
        /// </remarks>
        protected override async Task <DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default)
        {
            // Check for any interruptions.
            var status = await OnInterruptDialogAsync(innerDc, cancellationToken).ConfigureAwait(false);

            if (status == InterruptionAction.Resume)
            {
                // Interruption message was sent, and the waiting dialog should resume/reprompt.
                await innerDc.RepromptDialogAsync().ConfigureAwait(false);
            }
            else if (status == InterruptionAction.Waiting)
            {
                // Interruption intercepted conversation and is waiting for user to respond.
                return(EndOfTurn);
            }
            else if (status == InterruptionAction.End)
            {
                // Interruption ended conversation, and current dialog should end.
                return(await innerDc.EndDialogAsync().ConfigureAwait(false));
            }
            else if (status == InterruptionAction.NoAction)
            {
                // No interruption was detected. Process activity normally.
                var activity = innerDc.Context.Activity;

                switch (activity.Type)
                {
                case ActivityTypes.Message:
                {
                    // Pass message to waiting child dialog.
                    var result = await innerDc.ContinueDialogAsync().ConfigureAwait(false);

                    if (result.Status == DialogTurnStatus.Empty)
                    {
                        // There was no waiting dialog on the stack, process message normally.
                        await OnMessageActivityAsync(innerDc).ConfigureAwait(false);
                    }

                    break;
                }

                case ActivityTypes.Event:
                {
                    await OnEventActivityAsync(innerDc).ConfigureAwait(false);

                    break;
                }

                case ActivityTypes.Invoke:
                {
                    // Used by Teams for Authentication scenarios.
                    await innerDc.ContinueDialogAsync().ConfigureAwait(false);

                    break;
                }

                case ActivityTypes.ConversationUpdate:
                {
                    await OnMembersAddedAsync(innerDc).ConfigureAwait(false);

                    break;
                }

                default:
                {
                    // All other activity types will be routed here. Custom handling should be added in implementation.
                    await OnUnhandledActivityTypeAsync(innerDc).ConfigureAwait(false);

                    break;
                }
                }
            }

            if (innerDc.ActiveDialog == null)
            {
                // If the inner dialog stack completed during this turn, this component should be ended.
                return(await innerDc.EndDialogAsync().ConfigureAwait(false));
            }

            return(EndOfTurn);
        }
Beispiel #19
0
        // Determine if an interruption has occurred before we dispatch to any active dialog.
        private async Task <bool> IsTurnInterruptedAsync(DialogContext dc, string topIntent)
        {
            // See if there are any conversation interrupts we need to handle.
            if (topIntent.Equals(CancelIntent))
            {
                if (dc.ActiveDialog != null)
                {
                    await dc.CancelAllDialogsAsync();

                    chatdata.Add("Bot: Ok. I've canceled our last activity.");
                    await dc.Context.SendActivityAsync("Ok. I've canceled our last activity.");
                }
                else
                {
                    chatdata.Add("Bot: I don't have anything to cancel.");
                    await dc.Context.SendActivityAsync("I don't have anything to cancel.");
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(HelpIntent))
            {
                chatdata.Add("Bot: Let me try to provide some help.Ok. I've canceled our last activity.");
                chatdata.Add("I understand greetings, being asked for help, or being asked to cancel what I am doing.");
                await dc.Context.SendActivityAsync("Let me try to provide some help.");

                await dc.Context.SendActivityAsync("I understand greetings, being asked for help, or being asked to cancel what I am doing.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }
            if (topIntent.Equals(OnBoardingIntent))
            {
                chatdata.Add("Bot: Sure Mr. X, I am your HR buddy. Here is the link of onboarding process.");
                chatdata.Add("https://www.avaya.com");
                await dc.Context.SendActivityAsync("Sure, I am your HR buddy. Here is the link of onboarding process.");

                await dc.Context.SendActivityAsync("https://www.avaya.com");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }

            if (topIntent.Equals(DeadlineIntent))
            {
                chatdata.Add("Bot: As per new deadline Mr. X, you will have to complete all activities by 31st of this month. You will get mail notifications as reminder. ");
                await dc.Context.SendActivityAsync("As per new deadline Mr. X, you will have to complete all activities by 31st of this month. You will get mail notifications as reminder.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }
            if (topIntent.Equals(ThankyouIntent))
            {
                chatdata.Add("Bot: Thanks for contacting us.");
                await dc.Context.SendActivityAsync("Thanks for contacting us.");

                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }
            if (topIntent.Equals(AgentIntent))
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(queueurl);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"skillset\":\"" + "" + "\"}";
                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                try
                {
                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    var result       = "";
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        result = streamReader.ReadToEnd();
                    }
                    var jsonObj      = JObject.Parse(result);
                    var values       = (JArray)jsonObj["body"]["metrics"];
                    int agentinqueue = 0;
                    foreach (var value in values)
                    {
                        agentinqueue = (int)value["availableAgentsInQueue"];
                        if (agentinqueue > 0)
                        {
                            await dc.Context.SendActivityAsync("Please wait,we are connecting you to live agent.");

                            try
                            {
                                Connect(dc);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        else
                        {
                            chatdata.Add("Bot: No agent available this time.Please try again later.");
                            await dc.Context.SendActivityAsync("No agent available this time.Please try again later.");
                        }
                    }
                    ;
                }
                catch (Exception ex)
                { }
                if (dc.ActiveDialog != null)
                {
                    await dc.RepromptDialogAsync();
                }

                return(true);        // Handled the interrupt.
            }
            return(false);           // Did not handle the interrupt.
        }
        protected override async Task <DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var status = await OnInterruptDialogAsync(innerDc, cancellationToken);

            if (status == InterruptionAction.MessageSentToUser)
            {
                // Resume the waiting dialog after interruption
                await innerDc.RepromptDialogAsync().ConfigureAwait(false);

                return(EndOfTurn);
            }
            else if (status == InterruptionAction.StartedDialog)
            {
                // Stack is already waiting for a response, shelve inner stack
                return(EndOfTurn);
            }
            else
            {
                var activity = innerDc.Context.Activity;

                if (activity.IsStartActivity())
                {
                    await OnStartAsync(innerDc);
                }

                switch (activity.Type)
                {
                case ActivityTypes.Message:
                {
                    var result = await innerDc.ContinueDialogAsync();

                    switch (result.Status)
                    {
                    case DialogTurnStatus.Empty:
                    {
                        await RouteAsync(innerDc);

                        break;
                    }

                    case DialogTurnStatus.Complete:
                    case DialogTurnStatus.Cancelled:
                    {
                        await CompleteAsync(innerDc, result);

                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }

                    break;
                }

                case ActivityTypes.Event:
                {
                    await OnEventAsync(innerDc);

                    break;
                }

                default:
                {
                    await OnSystemMessageAsync(innerDc);

                    break;
                }
                }

                return(EndOfTurn);
            }
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            DialogTurnResult interrupted = null;
            var activity = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                // Get cognitive models for the current locale.
                var localizedServices = _services.GetCognitiveModels();

                // Run LUIS recognition on General model and store result in turn state.
                localizedServices.LuisServices.TryGetValue("General", out var generalLuisService);
                if (generalLuisService == null)
                {
                    throw new Exception("The general LUIS Model could not be found in your Bot Services configuration.");
                }

                var generalResult = await generalLuisService.RecognizeAsync <General>(innerDc.Context, cancellationToken);

                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivity(MainResponses.CancelMessage), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            var state = await _stateAccessor.GetAsync(innerDc.Context, () => new SkillState(), cancellationToken : cancellationToken);

                            interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult(false) : null, cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivity(MainResponses.HelpMessage), cancellationToken);

                        await innerDc.RepromptDialogAsync(cancellationToken);

                        interrupted = EndOfTurn;
                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var state = await _stateAccessor.GetAsync(innerDc.Context, () => new CalendarSkillState());

                var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResultKey);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale(CalendarMainResponses.CancelMessage));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale(CalendarMainResponses.HelpMessage));

                        await innerDc.RepromptDialogAsync();

                        interrupted = true;
                        break;
                    }

                    case General.Intent.Logout:
                    {
                        // Log user out of all accounts.
                        await LogUserOut(innerDc);

                        await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale(CalendarMainResponses.LogOut));

                        await innerDc.CancelAllDialogsAsync();

                        await innerDc.BeginDialogAsync(InitialDialogId);

                        interrupted = true;
                        break;
                    }
                    }

                    if (!interrupted && innerDc.ActiveDialog != null)
                    {
                        var calendarLuisResult = innerDc.Context.TurnState.Get <CalendarLuis>(StateProperties.CalendarLuisResultKey);
                        var topCalendarIntent  = calendarLuisResult.TopIntent();

                        if (topCalendarIntent.score > 0.9 && !CalendarCommonUtil.IsFindEventsDialog(state.InitialIntent))
                        {
                            var intentSwitchingResult = CalendarCommonUtil.CheckIntentSwitching(topCalendarIntent.intent);
                            var newFlowOptions        = new CalendarSkillDialogOptions()
                            {
                                SubFlowMode = false
                            };

                            if (intentSwitchingResult != CalendarLuis.Intent.None)
                            {
                                state.Clear();
                                await innerDc.CancelAllDialogsAsync();

                                state.InitialIntent = intentSwitchingResult;

                                switch (intentSwitchingResult)
                                {
                                case CalendarLuis.Intent.DeleteCalendarEntry:
                                    await innerDc.BeginDialogAsync(nameof(ChangeEventStatusDialog), new ChangeEventStatusDialogOptions(newFlowOptions, EventStatus.Cancelled));

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.AcceptEventEntry:
                                    await innerDc.BeginDialogAsync(nameof(ChangeEventStatusDialog), new ChangeEventStatusDialogOptions(newFlowOptions, EventStatus.Accepted));

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.ChangeCalendarEntry:
                                    await innerDc.BeginDialogAsync(nameof(UpdateEventDialog), newFlowOptions);

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.CheckAvailability:
                                    await innerDc.BeginDialogAsync(nameof(CheckPersonAvailableDialog), newFlowOptions);

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.ConnectToMeeting:
                                    await innerDc.BeginDialogAsync(nameof(JoinEventDialog), newFlowOptions);

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.CreateCalendarEntry:
                                    await innerDc.BeginDialogAsync(nameof(CreateEventDialog), newFlowOptions);

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.FindCalendarDetail:
                                case CalendarLuis.Intent.FindCalendarEntry:
                                case CalendarLuis.Intent.FindCalendarWhen:
                                case CalendarLuis.Intent.FindCalendarWhere:
                                case CalendarLuis.Intent.FindCalendarWho:
                                case CalendarLuis.Intent.FindDuration:
                                    await innerDc.BeginDialogAsync(nameof(ShowEventsDialog), new ShowMeetingsDialogOptions(ShowMeetingsDialogOptions.ShowMeetingReason.FirstShowOverview, newFlowOptions));

                                    interrupted = true;
                                    break;

                                case CalendarLuis.Intent.TimeRemaining:
                                    await innerDc.BeginDialogAsync(nameof(TimeRemainingDialog), newFlowOptions);

                                    interrupted = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #23
0
        protected override async Task <DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var status = await OnInterruptDialogAsync(innerDc, cancellationToken).ConfigureAwait(false);

            if (status == InterruptionAction.MessageSentToUser)
            {
                // Resume the waiting dialog after interruption
                await innerDc.RepromptDialogAsync().ConfigureAwait(false);

                return(EndOfTurn);
            }
            else if (status == InterruptionAction.StartedDialog)
            {
                // Stack is already waiting for a response, shelve inner stack
                return(EndOfTurn);
            }
            else
            {
                var activity = innerDc.Context.Activity;

                if (activity.IsStartActivity())
                {
                    await OnStartAsync(innerDc).ConfigureAwait(false);
                }

                switch (activity.Type)
                {
                case ActivityTypes.Message:
                {
                    // Note: This check is a workaround for adaptive card buttons that should map to an event (i.e. startOnboarding button in intro card)
                    if (activity.Value != null)
                    {
                        await OnEventAsync(innerDc).ConfigureAwait(false);
                    }
                    else if (!string.IsNullOrEmpty(activity.Text))
                    {
                        var result = await innerDc.ContinueDialogAsync().ConfigureAwait(false);

                        switch (result.Status)
                        {
                        case DialogTurnStatus.Empty:
                        {
                            await RouteAsync(innerDc).ConfigureAwait(false);

                            break;
                        }

                        case DialogTurnStatus.Complete:
                        {
                            await CompleteAsync(innerDc).ConfigureAwait(false);

                            // End active dialog
                            await innerDc.EndDialogAsync().ConfigureAwait(false);

                            break;
                        }

                        default:
                        {
                            break;
                        }
                        }
                    }

                    break;
                }

                case ActivityTypes.Event:
                {
                    await OnEventAsync(innerDc).ConfigureAwait(false);

                    break;
                }

                default:
                {
                    await OnSystemMessageAsync(innerDc).ConfigureAwait(false);

                    break;
                }
                }

                return(EndOfTurn);
            }
        }
Beispiel #24
0
        private async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;
            var dialog      = innerDc.ActiveDialog?.Id != null?innerDc.FindDialog(innerDc.ActiveDialog?.Id) : null;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Check if the active dialog is a skill for conditional interruption.
                var isSkill = dialog is TeamsSkillDialog;
                EnhancedBotFrameworkSkill identifiedSkill;
                var skillId = innerDc.Context.Activity.GetSkillId();
                // Get Dispatch LUIS result from turn state.
                var dispatchResult = innerDc.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult);
                (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent();

                // Check if skill id is present in activity payload
                if (!string.IsNullOrWhiteSpace(skillId))
                {
                    identifiedSkill = _skillsConfig.Skills.Where(s => s.Value.AppId == skillId).FirstOrDefault().Value;

                    // Check if skill identified through activity payload is not the current active skill
                    if (isSkill && !dialog.Id.Equals(identifiedSkill.Id))
                    {
                        await SwitchSkillPrompt(innerDc, identifiedSkill);

                        interrupted = true;
                    }
                }
                else
                {
                    // Check if we need to switch skills.
                    if (isSkill && IsSkillIntent(dispatchIntent) && dispatchIntent.ToString() != dialog.Id && dispatchScore > 0.9)
                    {
                        if (_skillsConfig.Skills.TryGetValue(dispatchIntent.ToString(), out identifiedSkill))
                        {
                            await SwitchSkillPrompt(innerDc, identifiedSkill);

                            interrupted = true;
                        }
                        else
                        {
                            throw new ArgumentException($"{dispatchIntent.ToString()} is not in the skills configuration");
                        }
                    }
                }

                if (dispatchIntent == DispatchLuis.Intent.l_General)
                {
                    // Get connected LUIS result from turn state.
                    var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralResult);
                    (var generalIntent, var generalScore) = generalResult.TopIntent();

                    if (generalScore > 0.5)
                    {
                        switch (generalIntent)
                        {
                        case GeneralLuis.Intent.Cancel:
                        {
                            if (!isSkill)
                            {
                                await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("CancelledMessage"));

                                await innerDc.CancelAllDialogsAsync();

                                interrupted = true;
                            }

                            break;
                        }

                        case GeneralLuis.Intent.Escalate:
                        {
                            await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("EscalateMessage"));

                            await innerDc.RepromptDialogAsync();

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Help:
                        {
                            if (!isSkill)
                            {
                                // If current dialog is a skill, allow it to handle its own help intent.
                                await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("HelpCard"));

                                await innerDc.RepromptDialogAsync();

                                interrupted = true;
                            }

                            break;
                        }

                        case GeneralLuis.Intent.Logout:
                        {
                            if (!isSkill)
                            {
                                // Log user out of all accounts.
                                await LogUserOut(innerDc);

                                await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("LogoutMessage"));

                                await innerDc.CancelAllDialogsAsync();

                                interrupted = true;
                            }

                            break;
                        }

                        case GeneralLuis.Intent.Repeat:
                        {
                            // Sends the activities since the last user message again.
                            var previousResponse = await _previousResponseAccessor.GetAsync(innerDc.Context, () => new List <Activity>());

                            foreach (var response in previousResponse)
                            {
                                // Reset id of original activity so it can be processed by the channel.
                                response.Id = string.Empty;
                                await innerDc.Context.SendActivityAsync(response);
                            }

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.StartOver:
                        {
                            await innerDc.Context.SendActivityAsync(_templateEngine.GenerateActivityForLocale("StartOverMessage"));

                            // Cancel all dialogs on the stack.
                            await innerDc.CancelAllDialogsAsync();

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Stop:
                        {
                            // Use this intent to send an event to your device that can turn off the microphone in speech scenarios.
                            break;
                        }
                        }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #25
0
        private async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;
            var userProfile = await _userProfileState.GetAsync(innerDc.Context, () => new UserProfileState());

            var dialog = innerDc.ActiveDialog?.Id != null?innerDc.FindDialog(innerDc.ActiveDialog?.Id) : null;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Check if the active dialog is a skill for conditional interruption.
                var isSkill = dialog is SkillDialog;

                // Get Dispatch LUIS result from turn state.
                var dispatchResult = innerDc.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult);
                (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent();

                // Check if we need to switch skills.
                if (isSkill && IsSkillIntent(dispatchIntent) && dispatchIntent.ToString() != dialog.Id && dispatchScore > 0.9)
                {
                    EnhancedBotFrameworkSkill identifiedSkill;
                    if (_skillsConfig.Skills.TryGetValue(dispatchIntent.ToString(), out identifiedSkill))
                    {
                        var prompt = MessageFactory.Text($"Would you like to switch to the {identifiedSkill.Name}?");//_templateEngine.GenerateActivityForLocale("SkillSwitchPrompt", new { Skill = identifiedSkill.Name });
                        await innerDc.BeginDialogAsync(_switchSkillDialog.Id, new SwitchSkillDialogOptions(prompt, identifiedSkill));

                        interrupted = true;
                    }
                    else
                    {
                        throw new ArgumentException($"{dispatchIntent.ToString()} is not in the skills configuration");
                    }
                }

                if (dispatchIntent == DispatchLuis.Intent.l_General)
                {
                    // Get connected LUIS result from turn state.
                    var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralResult);
                    (var generalIntent, var generalScore) = generalResult.TopIntent();

                    if (generalScore > 0.5)
                    {
                        switch (generalIntent)
                        {
                        case GeneralLuis.Intent.Cancel:
                        {
                            await innerDc.Context.SendActivityAsync("CANCEL");

                            await innerDc.CancelAllDialogsAsync();

                            await innerDc.BeginDialogAsync(InitialDialogId);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Escalate:
                        {
                            await innerDc.Context.SendActivityAsync("ESCALLATE");

                            await innerDc.RepromptDialogAsync();

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Help:
                        {
                            if (!isSkill)
                            {
                                // If current dialog is a skill, allow it to handle its own help intent.
                                await innerDc.Context.SendActivityAsync("HELP");

                                await innerDc.RepromptDialogAsync();

                                interrupted = true;
                            }

                            break;
                        }

                        case GeneralLuis.Intent.Logout:
                        {
                            // Log user out of all accounts.
                            await LogUserOut(innerDc);

                            await innerDc.Context.SendActivityAsync("LOGOUT");

                            await innerDc.CancelAllDialogsAsync();

                            await innerDc.BeginDialogAsync(InitialDialogId);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Repeat:
                        {
                            // Sends the activities since the last user message again.
                            var previousResponse = await _previousResponseAccessor.GetAsync(innerDc.Context, () => new List <Activity>());

                            foreach (var response in previousResponse)
                            {
                                // Reset id of original activity so it can be processed by the channel.
                                response.Id = string.Empty;
                                await innerDc.Context.SendActivityAsync(response);
                            }

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.StartOver:
                        {
                            await innerDc.Context.SendActivityAsync("START OVER");

                            // Cancel all dialogs on the stack.
                            await innerDc.CancelAllDialogsAsync();

                            await innerDc.BeginDialogAsync(InitialDialogId);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Stop:
                        {
                            // Use this intent to send an event to your device that can turn off the microphone in speech scenarios.
                            break;
                        }
                        }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #26
0
        protected override async Task <DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var status = await OnInterruptDialogAsync(innerDc, cancellationToken).ConfigureAwait(false);

            if (status == InterruptionAction.Resume)
            {
                // Resume the waiting dialog after interruption
                await innerDc.RepromptDialogAsync().ConfigureAwait(false);

                return(EndOfTurn);
            }
            else if (status == InterruptionAction.Waiting)
            {
                // Stack is already waiting for a response, shelve inner stack
                return(EndOfTurn);
            }
            else
            {
                var activity = innerDc.Context.Activity;

                if (activity.IsStartActivity())
                {
                    await OnStartAsync(innerDc).ConfigureAwait(false);
                }

                switch (activity.Type)
                {
                case ActivityTypes.Message:
                {
                    // Note: This check is a workaround for adaptive card buttons that should map to an event (i.e. startOnboarding button in intro card)
                    if (activity.Value != null)
                    {
                        await OnEventAsync(innerDc).ConfigureAwait(false);
                    }
                    else
                    {
                        var result = await innerDc.ContinueDialogAsync().ConfigureAwait(false);

                        switch (result.Status)
                        {
                        case DialogTurnStatus.Empty:
                        {
                            await RouteAsync(innerDc).ConfigureAwait(false);

                            break;
                        }

                        case DialogTurnStatus.Complete:
                        {
                            // End active dialog
                            await innerDc.EndDialogAsync().ConfigureAwait(false);

                            break;
                        }

                        default:
                        {
                            break;
                        }
                        }
                    }

                    // If the active dialog was ended on this turn (either on single-turn dialog, or on continueDialogAsync) run CompleteAsync method.
                    if (innerDc.ActiveDialog == null)
                    {
                        await CompleteAsync(innerDc).ConfigureAwait(false);
                    }

                    break;
                }

                case ActivityTypes.Event:
                {
                    await OnEventAsync(innerDc).ConfigureAwait(false);

                    break;
                }

                case ActivityTypes.Invoke:
                {
                    // Used by Teams for Authentication scenarios.
                    await innerDc.ContinueDialogAsync().ConfigureAwait(false);

                    break;
                }

                default:
                {
                    await OnSystemMessageAsync(innerDc).ConfigureAwait(false);

                    break;
                }
                }

                return(EndOfTurn);
            }
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            DialogTurnResult interrupted = null;
            var activity = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralLuisResultKey);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case GeneralLuis.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivity(MainResponses.CancelMessage), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            interrupted = await innerDc.EndDialogAsync(cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }

                    case GeneralLuis.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivity(MainResponses.HelpMessage), cancellationToken);

                        await innerDc.RepromptDialogAsync(cancellationToken);

                        interrupted = EndOfTurn;
                        break;
                    }

                    case GeneralLuis.Intent.Logout:
                    {
                        await OnLogoutAsync(innerDc, cancellationToken);

                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivity(MainResponses.LogOut), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            interrupted = await innerDc.EndDialogAsync(cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #28
0
        private async Task <bool> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            var interrupted = false;
            var activity    = innerDc.Context.Activity;
            var userProfile = await _userProfileState.GetAsync(innerDc.Context, () => new UserProfileState(), cancellationToken);

            var dialog = innerDc.ActiveDialog?.Id != null?innerDc.FindDialog(innerDc.ActiveDialog?.Id) : null;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Check if the active dialog is a skill for conditional interruption.
                var isSkill = dialog is SkillDialog;

                // Get Dispatch LUIS result from turn state.
                var dispatchResult = innerDc.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult);
                (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent();

                // Check if we need to switch skills.
                if (isSkill && IsSkillIntent(dispatchIntent) && dispatchIntent.ToString() != dialog.Id && dispatchScore > 0.9)
                {
                    if (_skillsConfig.Skills.TryGetValue(dispatchIntent.ToString(), out var identifiedSkill))
                    {
                        var prompt = _templateManager.GenerateActivityForLocale("SkillSwitchPrompt", new { Skill = identifiedSkill.Name });
                        await innerDc.BeginDialogAsync(_switchSkillDialog.Id, new SwitchSkillDialogOptions(prompt, identifiedSkill), cancellationToken);

                        interrupted = true;
                    }
                    else
                    {
                        throw new ArgumentException($"{dispatchIntent.ToString()} is not in the skills configuration");
                    }
                }

                if (dispatchIntent == DispatchLuis.Intent.l_General)
                {
                    // Get connected LUIS result from turn state.
                    var generalResult = innerDc.Context.TurnState.Get <GeneralLuis>(StateProperties.GeneralResult);
                    (var generalIntent, var generalScore) = generalResult.TopIntent();

                    if (generalScore > 0.5)
                    {
                        switch (generalIntent)
                        {
                        case GeneralLuis.Intent.Cancel:
                        {
                            await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("CancelledMessage", userProfile), cancellationToken);

                            await innerDc.CancelAllDialogsAsync(cancellationToken);

                            await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Escalate:
                        {
                            var conversationState          = _serviceProvider.GetService <ConversationState>();
                            var conversationStateAccessors = conversationState.CreateProperty <LoggingConversationData>(nameof(LoggingConversationData));
                            var conversationData           = await conversationStateAccessors.GetAsync(innerDc.Context, () => new LoggingConversationData());

                            await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("EscalateMessage", userProfile), cancellationToken);

                            var transcript = new Transcript(conversationData.ConversationLog.Where(a => a.Type == ActivityTypes.Message).ToList());

                            var evnt = EventFactory.CreateHandoffInitiation(innerDc.Context,
                                                                            new
                                {
                                    Skill = "Expert Help",
                                    EngagementAttributes = new EngagementAttribute[]
                                    {
                                        new EngagementAttribute {
                                            Type = "ctmrinfo", CustomerType = "vip", SocialId = "123456789"
                                        },
                                        new EngagementAttribute {
                                            Type = "personal", FirstName = innerDc.Context.Activity.From.Name
                                        }
                                    }
                                },
                                                                            transcript);

                            await innerDc.Context.SendActivityAsync(evnt);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Help:
                        {
                            if (!isSkill)
                            {
                                // If current dialog is a skill, allow it to handle its own help intent.
                                await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("HelpCard", userProfile), cancellationToken);

                                await innerDc.RepromptDialogAsync(cancellationToken);

                                interrupted = true;
                            }

                            break;
                        }

                        case GeneralLuis.Intent.Logout:
                        {
                            // Log user out of all accounts.
                            await LogUserOutAsync(innerDc, cancellationToken);

                            await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("LogoutMessage", userProfile), cancellationToken);

                            await innerDc.CancelAllDialogsAsync(cancellationToken);

                            await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Repeat:
                        {
                            // Sends the activities since the last user message again.
                            var previousResponse = await _previousResponseAccessor.GetAsync(innerDc.Context, () => new List <Activity>(), cancellationToken);

                            foreach (var response in previousResponse)
                            {
                                // Reset id of original activity so it can be processed by the channel.
                                response.Id = string.Empty;
                                await innerDc.Context.SendActivityAsync(response, cancellationToken);
                            }

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.StartOver:
                        {
                            await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("StartOverMessage", userProfile), cancellationToken);

                            // Cancel all dialogs on the stack.
                            await innerDc.CancelAllDialogsAsync(cancellationToken);

                            await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);

                            interrupted = true;
                            break;
                        }

                        case GeneralLuis.Intent.Stop:
                        {
                            // Use this intent to send an event to your device that can turn off the microphone in speech scenarios.
                            break;
                        }
                        }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #29
0
        /// <summary>
        /// Main activity methond of the chatbot.
        /// </summary>
        /// <param name="turnContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            //Create dialogContext which is used to store all information around state.
            DialogContext dialogContext = await _dialogSet.CreateContextAsync(turnContext);

            //Assing user response to be validated against being interruption.
            string interruption = turnContext.Activity.Text;

            //This block validates user response and if one of the key words is used (more,help,cancel,exit) suitable action is taken.
            if (!string.IsNullOrWhiteSpace(interruption))
            {
                if (interruption.Trim().ToLowerInvariant() == "more flight")
                {
                    await turnContext.SendActivityAsync(
                        "Standard - 2 or 3 seats next to each other, radio output in the seat, no meal, cold beverage (water or juice)\n\n" +
                        "Premium - onboarding priority over Standard class, 2 seats next to each other, 230V AC/DC connector and USB connector in the seat, 20% more space for legs then in the Standard class, no meal, cold beverage (water or juice)\n\n" +
                        "Business - Business lounge with buffet and open bar, onboarding priority over Premium and Standard classes, separate seat which can be converted in to bed, 24 inches flat screen (TV, DVD, USB, HDIM), headset, meal and beverage included",
                        cancellationToken : cancellationToken);

                    await dialogContext.RepromptDialogAsync();
                }
                else if (interruption.Trim().ToLowerInvariant() == "more cars")
                {
                    await turnContext.SendActivityAsync(
                        "Economy - Basic radio, manually opened windows and central aircondition. Costs 15$ per a day.\n\n" +
                        "Standard - Audio with jack and usb connectors, electric windows in first seats row, separate aircondition for every seats row. Costs 40$ per a day.\n\n" +
                        "Business - Hight class audio system with jack and usb connectors, colorful satellite navigation with voice control, all electric windows and tailgate, separate aircondition for every seat. Costs 80$ per a day.",
                        cancellationToken : cancellationToken);

                    await dialogContext.RepromptDialogAsync();
                }
                else if (interruption.Trim().ToLowerInvariant() == "help")
                {
                    Attachment attachment = CreateHelpAttachement();
                    var        reply      = turnContext.Activity.CreateReply();
                    reply.Attachments = new List <Attachment>()
                    {
                        attachment
                    };
                    await turnContext.SendActivityAsync(reply, cancellationToken : cancellationToken);

                    await dialogContext.RepromptDialogAsync(cancellationToken : cancellationToken);
                }
                else if (interruption.Trim().ToLowerInvariant() == "cancel")
                {
                    await dialogContext.CancelAllDialogsAsync();

                    await dialogContext.BeginDialogAsync(MainDialogId);
                }
                else if (interruption.Trim().ToLowerInvariant() == "exit")
                {
                    await turnContext.SendActivityAsync("Goodby Passenger!");

                    await dialogContext.CancelAllDialogsAsync();
                }
            }
            //This block is executed if message is posted, existing dialog is continued.
            if (turnContext.Activity.Type == ActivityTypes.Message && !turnContext.Responded)
            {
                DialogTurnResult turnResult = await dialogContext.ContinueDialogAsync();

                if (turnResult.Status == DialogTurnStatus.Complete || turnResult.Status == DialogTurnStatus.Cancelled)
                {
                    await turnContext.SendActivityAsync("Goodby Passenger!");
                }
                else if (!dialogContext.Context.Responded)
                {
                    await turnContext.SendActivityAsync("I am unable to do anything...");
                }
            }
            //This block is executed on conversation update.
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                foreach (ChannelAccount member in turnContext.Activity.MembersAdded)
                {
                    if (turnContext.Activity.Recipient.Id != member.Id)
                    {
                        //Message to be send at the begining of the diatlog when user join the conversation
                        await turnContext.SendActivityAsync("Hello new Passenger!", cancellationToken : cancellationToken);

                        //Invoke of the Main Dialog
                        await dialogContext.BeginDialogAsync(MainDialogId);
                    }
                }
            }
            // Save changes after every turn.
            await _accessor.ConversationState.SaveChangesAsync(turnContext, false);
        }
        // Runs on every turn of the conversation to check if the conversation should be interrupted.
        protected async Task <DialogTurnResult> InterruptDialogAsync(DialogContext innerDc, CancellationToken cancellationToken)
        {
            DialogTurnResult interrupted = null;
            var activity = innerDc.Context.Activity;

            if (activity.Type == ActivityTypes.Message && !string.IsNullOrEmpty(activity.Text))
            {
                // Get connected LUIS result from turn state.
                var generalResult = innerDc.Context.TurnState.Get <General>(StateProperties.GeneralLuisResultKey);
                (var generalIntent, var generalScore) = generalResult.TopIntent();

                if (generalScore > 0.5)
                {
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(ToDoMainResponses.CancelMessage), cancellationToken);

                        await innerDc.CancelAllDialogsAsync();

                        if (innerDc.Context.IsSkill())
                        {
                            var state = await _stateAccessor.GetAsync(innerDc.Context, () => new ToDoSkillState(), cancellationToken);

                            interrupted = await innerDc.EndDialogAsync(state.IsAction?new TodoListInfo { ActionSuccess = false } : null, cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }

                    case General.Intent.Help:
                    {
                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(ToDoMainResponses.HelpMessage), cancellationToken);

                        await innerDc.RepromptDialogAsync(cancellationToken);

                        interrupted = EndOfTurn;
                        break;
                    }

                    case General.Intent.Logout:
                    {
                        // Log user out of all accounts.
                        await LogUserOutAsync(innerDc, cancellationToken);

                        await innerDc.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale(ToDoMainResponses.LogOut), cancellationToken);

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

                        if (innerDc.Context.IsSkill())
                        {
                            interrupted = await innerDc.EndDialogAsync(cancellationToken : cancellationToken);
                        }
                        else
                        {
                            interrupted = await innerDc.BeginDialogAsync(InitialDialogId, cancellationToken : cancellationToken);
                        }

                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }