Beispiel #1
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);
        }
Beispiel #2
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new EmailSkillState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _skillConfig.LocaleConfigurations[locale];

            // If dispatch result is general luis model
            localeConfig.LuisServices.TryGetValue("email", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var result = await luisService.RecognizeAsync <Email>(dc.Context, CancellationToken.None);

                var intent           = result?.TopIntent().intent;
                var generalTopIntent = state.GeneralLuisResult?.TopIntent().intent;

                var skillOptions = new EmailSkillDialogOptions
                {
                    SkillMode   = _skillMode,
                    SubFlowMode = false
                };

                // switch on general intents
                switch (intent)
                {
                case Email.Intent.SendEmail:
                {
                    await dc.BeginDialogAsync(nameof(SendEmailDialog), skillOptions);

                    break;
                }

                case Email.Intent.Forward:
                {
                    await dc.BeginDialogAsync(nameof(ForwardEmailDialog), skillOptions);

                    break;
                }

                case Email.Intent.Reply:
                {
                    await dc.BeginDialogAsync(nameof(ReplyEmailDialog), skillOptions);

                    break;
                }

                case Email.Intent.SearchMessages:
                case Email.Intent.CheckMessages:
                case Email.Intent.ReadAloud:
                case Email.Intent.QueryLastText:
                {
                    await dc.BeginDialogAsync(nameof(ShowEmailDialog), skillOptions);

                    break;
                }

                case Email.Intent.Delete:
                {
                    await dc.BeginDialogAsync(nameof(DeleteEmailDialog), skillOptions);

                    break;
                }

                case Email.Intent.None:
                {
                    if (generalTopIntent == General.Intent.Next || generalTopIntent == General.Intent.Previous)
                    {
                        await dc.BeginDialogAsync(nameof(ShowEmailDialog), skillOptions);
                    }
                    else
                    {
                        await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(EmailSharedResponses.DidntUnderstandMessage));

                        if (_skillMode)
                        {
                            await CompleteAsync(dc);
                        }
                    }

                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(EmailMainResponses.FeatureNotAvailable));

                    if (_skillMode)
                    {
                        await CompleteAsync(dc);
                    }

                    break;
                }
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="dc">Current dialog context.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Completed Task.</returns>
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the conversation state from the turn context
            var state = await this._accessors.EmailSkillState.GetAsync(dc.Context, () => new EmailSkillState());

            var dialogState = await this._accessors.ConversationDialogState.GetAsync(dc.Context, () => new DialogState());

            Email luisResult;

            // If invoked by a Skill we get the Luis IRecognizerConvert passed to use so we don't have to do that locally
            if (this._skillMode && state.LuisResultPassedFromSkill != null)
            {
                luisResult = (Email)state.LuisResultPassedFromSkill;
                state.LuisResultPassedFromSkill = null;
            }
            else if (this._services?.LuisRecognizer != null)
            {
                luisResult = await this._services.LuisRecognizer.RecognizeAsync <Email>(dc.Context, cancellationToken);
            }
            else
            {
                throw new Exception("EmailSkill: Could not get Luis Recognizer result.");
            }

            await EmailSkillHelper.DigestEmailLuisResult(dc.Context, this._accessors, luisResult);

            var topLuisIntent = luisResult?.TopIntent().intent;

            SkillDialogOptions options = new SkillDialogOptions {
                SkillMode = this._skillMode
            };

            switch (topLuisIntent)
            {
            case Email.Intent.SendEmail:
            {
                await dc.BeginDialogAsync(SendEmailDialog.Name, options);

                break;
            }

            case Email.Intent.Forward:
            {
                await dc.BeginDialogAsync(ForwardEmailDialog.Name, options);

                break;
            }

            case Email.Intent.Reply:
            {
                await dc.BeginDialogAsync(ReplyEmailDialog.Name, options);

                break;
            }

            case Email.Intent.Help:
            {
                await dc.BeginDialogAsync(HelpDialog.Name, options);

                break;
            }

            case Email.Intent.SearchMessages:
            case Email.Intent.ShowNext:
            case Email.Intent.ShowPrevious:
            case Email.Intent.CheckMessages:
            {
                await dc.BeginDialogAsync(ShowEmailDialog.Name, options);

                break;
            }

            case Email.Intent.None:
            {
                await this._responder.ReplyWith(dc.Context, EmailSkillResponses.Confused);

                if (_skillMode)
                {
                    await CompleteAsync(dc);
                }

                break;
            }

            default:
            {
                await dc.Context.SendActivityAsync("This feature is not yet available in the Email Skill. Please try asking something else.");

                if (_skillMode)
                {
                    await CompleteAsync(dc);
                }

                break;
            }
            }
        }
Beispiel #4
0
        private async Task <InterruptionAction> OnCancel(DialogContext dc)
        {
            await dc.BeginDialogAsync(nameof(CancelDialog));

            return(InterruptionAction.StartedDialog);
        }
        // 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.GeneralLuisResult);
                (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())
                        {
                            var state = await _stateAccessor.GetAsync(innerDc.Context, () => new HospitalitySkillState(), cancellationToken);

                            interrupted = await innerDc.EndDialogAsync(state.IsAction?new ActionResult(false) : null, 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:
                    {
                        // Log user out of all accounts.
                        await LogUserOutAsync(innerDc, cancellationToken);

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

                        await innerDc.CancelAllDialogsAsync(cancellationToken);

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

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

                        break;
                    }
                    }
                }
            }

            return(interrupted);
        }
Beispiel #6
0
        protected override async Task OnEventAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Check if there was an action submitted from intro card
            var value = dc.Context.Activity.Value;

            if (value.GetType() == typeof(JObject))
            {
                var submit = JObject.Parse(value.ToString());
                if (value != null && (string)submit["action"] == "startOnboarding")
                {
                    await dc.BeginDialogAsync(nameof(OnboardingDialog));

                    return;
                }
            }

            var forward = true;
            var ev      = dc.Context.Activity.AsEventActivity();

            if (!string.IsNullOrWhiteSpace(ev.Name))
            {
                switch (ev.Name)
                {
                case Events.TimezoneEvent:
                {
                    try
                    {
                        var timezone    = ev.Value.ToString();
                        var tz          = TimeZoneInfo.FindSystemTimeZoneById(timezone);
                        var timeZoneObj = new JObject();
                        timeZoneObj.Add(TimeZone, JToken.FromObject(tz));

                        var skillContext = await _skillContextAccessor.GetAsync(dc.Context, () => new SkillContext());

                        if (skillContext.ContainsKey(TimeZone))
                        {
                            skillContext[TimeZone] = timeZoneObj;
                        }
                        else
                        {
                            skillContext.Add(TimeZone, timeZoneObj);
                        }

                        await _skillContextAccessor.SetAsync(dc.Context, skillContext);
                    }
                    catch
                    {
                        await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Timezone passed could not be mapped to a valid Timezone. Property not set."));
                    }

                    forward = false;
                    break;
                }

                case Events.LocationEvent:
                {
                    var location    = ev.Value.ToString();
                    var locationObj = new JObject();
                    locationObj.Add(Location, JToken.FromObject(location));

                    var skillContext = await _skillContextAccessor.GetAsync(dc.Context, () => new SkillContext());

                    if (skillContext.ContainsKey(Location))
                    {
                        skillContext[Location] = locationObj;
                    }
                    else
                    {
                        skillContext.Add(Location, locationObj);
                    }

                    await _skillContextAccessor.SetAsync(dc.Context, skillContext);

                    forward = false;
                    break;
                }

                case TokenEvents.TokenResponseEventName:
                {
                    forward = true;
                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Unknown Event {ev.Name} was received but not processed."));

                    forward = false;
                    break;
                }
                }
            }

            if (forward)
            {
                var result = await dc.ContinueDialogAsync();

                if (result.Status == DialogTurnStatus.Complete)
                {
                    await CompleteAsync(dc);
                }
            }
        }
        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 = _templateManager.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(_templateManager.GenerateActivityForLocale("CancelledMessage", userProfile));

                            await innerDc.CancelAllDialogsAsync();

                            await innerDc.BeginDialogAsync(InitialDialogId);

                            interrupted = true;
                            break;
                        }

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

                            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(_templateManager.GenerateActivityForLocale("HelpCard", userProfile));

                                await innerDc.RepromptDialogAsync();

                                interrupted = true;
                            }

                            break;
                        }

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

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

                            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(_templateManager.GenerateActivityForLocale("StartOverMessage", userProfile));

                            // 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 #8
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the conversation state from the turn context
            var state = await _accessors.CalendarSkillState.GetAsync(dc.Context, () => new CalendarSkillState());

            var dialogState = await _accessors.ConversationDialogState.GetAsync(dc.Context, () => new DialogState());

            Calendar luisResult = null;

            if (_skillMode && state.LuisResultPassedFromSkill != null)
            {
                // If invoked by a Skill we get the Luis IRecognizerConvert passed to us on first turn so we don't have to do that locally
                luisResult = (Calendar)state.LuisResultPassedFromSkill;
                state.LuisResultPassedFromSkill = null;
            }
            else if (_services?.LuisRecognizer != null)
            {
                // When run in normal mode or 2+ turn of a skill we use LUIS ourselves as the parent Dispatcher doesn't do this
                luisResult = await _services.LuisRecognizer.RecognizeAsync <Calendar>(dc.Context, cancellationToken);
            }
            else
            {
                throw new Exception("CalendarSkill: Could not get Luis Recognizer result.");
            }

            var intent = luisResult?.TopIntent().intent;

            var skillOptions = new CalendarSkillDialogOptions
            {
                SkillMode = _skillMode,
            };

            switch (intent)
            {
            case Calendar.Intent.Greeting:
            {
                await dc.BeginDialogAsync(GreetingDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.FindMeetingRoom:
            case Calendar.Intent.CreateCalendarEntry:
            {
                await dc.BeginDialogAsync(CreateEventDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.DeleteCalendarEntry:
            {
                await dc.BeginDialogAsync(DeleteEventDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.NextMeeting:
            {
                await dc.BeginDialogAsync(NextMeetingDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.ChangeCalendarEntry:
            {
                await dc.BeginDialogAsync(UpdateEventDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.FindCalendarEntry:
            case Calendar.Intent.ShowNext:
            case Calendar.Intent.ShowPrevious:
            case Calendar.Intent.Summary:
            {
                await dc.BeginDialogAsync(SummaryDialog.Name, skillOptions);

                break;
            }

            case Calendar.Intent.None:
            {
                await _responder.ReplyWith(dc.Context, CalendarSkillResponses.Confused);

                if (_skillMode)
                {
                    await CompleteAsync(dc);
                }

                break;
            }

            default:
            {
                await dc.Context.SendActivityAsync("This feature is not yet available in the Calendar Skill. Please try asking something else.");

                if (_skillMode)
                {
                    await CompleteAsync(dc);
                }
                break;
            }
            }
        }
Beispiel #9
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // If dispatch result is general luis model
            _services.LuisServices.TryGetValue("todo", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var result = await luisService.RecognizeAsync <ToDo>(dc.Context, CancellationToken.None);

                var intent = result?.TopIntent().intent;

                var skillOptions = new ToDoSkillDialogOptions
                {
                    SkillMode = _skillMode,
                };

                // switch on general intents
                switch (intent)
                {
                case ToDo.Intent.AddToDo:
                {
                    await dc.BeginDialogAsync(nameof(AddToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.MarkToDo:
                {
                    await dc.BeginDialogAsync(nameof(MarkToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.DeleteToDo:
                {
                    await dc.BeginDialogAsync(nameof(DeleteToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.ShowToDo:
                {
                    await dc.BeginDialogAsync(nameof(ShowToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.None:
                {
                    // No intent was identified, send confused message
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(ToDoSharedResponses.DidntUnderstandMessage));

                    break;
                }

                default:
                {
                    // intent was identified but not yet implemented
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(ToDoMainResponses.FeatureNotAvailable));

                    break;
                }
                }
            }
        }
Beispiel #10
0
        public static async Task SendAsync(this Dialog dialog, ITurnContext turnContext, IStatePropertyAccessor <DialogState> accessor, CancellationToken cancellationToken = default)
        {
            DialogSet dialogSet = new DialogSet(accessor);

            dialogSet.Add(dialog);

            //Dialogs
            dialogSet.Add(new FoodDialog());
            dialogSet.Add(new FlightDialog());
            dialogSet.Add(new TestDialog());
            dialogSet.Add(new FuckDialog());

            ////Test Dialogs
            dialogSet.Add(new FlightNewDialog());
            dialogSet.Add(new FoodNewDialog());

            //Prompts
            dialogSet.Add(new TextPrompt(nameof(TextPrompt)));
            dialogSet.Add(new ChoicePrompt(nameof(ChoicePrompt)));

            DialogContext dialogContext = await dialogSet.CreateContextAsync(turnContext, cancellationToken);

            try
            {
                #region Cancel And Help
                if (turnContext.Activity.Text != null)
                {
                    string res = turnContext.Activity.Text;

                    if (res.ToLower().Contains("cancel"))
                    {
                        await dialogContext.CancelAllDialogsAsync();

                        await turnContext.SendActivityAsync("Cancel Dialog");

                        return;
                    }
                    else if (res.ToLower().Contains("help"))
                    {
                        await turnContext.SendActivityAsync("Help Dialog");
                    }
                }
                #endregion

                #region Dispatch
                if (turnContext.Activity.Text == null && turnContext.Activity.Value != null)
                {
                    await dialogContext.CancelAllDialogsAsync();

                    var intent = turnContext.Activity.Value.GetIntentFromMessageValue();

                    DialogTurnResult result = await dialogContext.BeginDialogAsync(intent);

                    return;
                }
                #endregion

                DialogTurnResult results = await dialogContext.ContinueDialogAsync(cancellationToken);

                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dialogContext.BeginDialogAsync(dialog.Id, null, cancellationToken);
                }
            }
            catch (Exception ex)
            {
                await turnContext.SendActivityAsync($"Pohubilo SE: {ex.ToString()}");
            }
        }
Beispiel #11
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var routeResult = EndOfTurn;

            // Check dispatch result
            var dispatchResult = await _services.DispatchRecognizer.RecognizeAsync <Dispatch>(dc, true, CancellationToken.None);

            var intent = dispatchResult.TopIntent().intent;

            if (intent == Dispatch.Intent.l_General)
            {
                // If dispatch result is general luis model
                _services.LuisServices.TryGetValue("general", out var luisService);

                if (luisService == null)
                {
                    throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
                }
                else
                {
                    var result = await luisService.RecognizeAsync <General>(dc, true, CancellationToken.None);

                    var generalIntent = result?.TopIntent().intent;

                    // switch on general intents
                    switch (generalIntent)
                    {
                    case General.Intent.Greeting:
                    {
                        // send greeting response
                        await _responder.ReplyWith(dc.Context, MainResponses.Greeting);

                        break;
                    }

                    case General.Intent.Help:
                    {
                        // send help response
                        routeResult = await dc.BeginDialogAsync(nameof(OnboardingDialog));

                        break;
                    }

                    case General.Intent.Cancel:
                    {
                        // send cancelled response
                        await _responder.ReplyWith(dc.Context, MainResponses.Cancelled);

                        // Cancel any active dialogs on the stack
                        routeResult = await dc.CancelAllDialogsAsync();

                        break;
                    }

                    case General.Intent.Escalate:
                    {
                        // start escalate dialog
                        routeResult = await dc.BeginDialogAsync(nameof(EscalateDialog));

                        break;
                    }

                    case General.Intent.None:
                    default:
                    {
                        // No intent was identified, send confused message
                        await _responder.ReplyWith(dc.Context, MainResponses.Confused);

                        break;
                    }
                    }
                }
            }
            else if (intent == Dispatch.Intent.l_Retail)
            {
                var luisService = _services.LuisServices["retail"];
                var luisResult  = await luisService.RecognizeAsync <Retail>(dc.Context, CancellationToken.None);

                var retailIntent = luisResult?.TopIntent().intent;

                switch (retailIntent)
                {
                case Retail.Intent.BuyOnlinePickUpInStore:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(PickUpInStoreDialog));

                    break;
                }

                case Retail.Intent.CancelOrder:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(CancelOrderDialog));

                    break;
                }

                case Retail.Intent.CheckItemAvailability:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(CheckItemAvailabilityDialog));

                    break;
                }

                case Retail.Intent.CheckOrderStatus:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(CheckOrderStatusDialog));

                    break;
                }

                case Retail.Intent.ExchangeItem:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(ExchangeItemDialog));

                    break;
                }

                case Retail.Intent.FindPromoCode:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(FindPromoCodeDialog));

                    break;
                }

                case Retail.Intent.FindStore:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(FindStoreDialog));

                    break;
                }

                case Retail.Intent.FreeShipping:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(FreeShippingDialog));

                    break;
                }

                case Retail.Intent.GetRefundStatus:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(GetRefundStatusDialog));

                    break;
                }

                case Retail.Intent.PayBill:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(PayBillDialog));

                    break;
                }

                case Retail.Intent.ResetPassword:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(ResetPasswordDialog));

                    break;
                }

                case Retail.Intent.StartReturn:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(StartReturnDialog));

                    break;
                }

                case Retail.Intent.UpdateAccount:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(UpdateAccountDialog));

                    break;
                }

                case Retail.Intent.UpdateShippingAddress:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(UpdateShippingAddressDialog));

                    break;
                }

                case Retail.Intent.None:
                default:
                {
                    // No intent was identified, send confused message
                    await _responder.ReplyWith(dc.Context, MainResponses.Confused);

                    break;
                }
                }
            }
            else if (intent == Dispatch.Intent.q_FAQ)
            {
                _services.QnAServices.TryGetValue("faq", out var qnaService);

                if (qnaService == null)
                {
                    throw new Exception("The specified QnAMaker Service could not be found in your Bot Services configuration.");
                }
                else
                {
                    var answers = await qnaService.GetAnswersAsync(dc.Context);

                    if (answers != null && answers.Count() > 0)
                    {
                        await dc.Context.SendActivityAsync(answers[0].Answer);
                    }
                }
            }

            if (routeResult.Status == DialogTurnStatus.Complete)
            {
                await CompleteAsync(dc);
            }
        }
        protected override async Task OnEventAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

            switch (dc.Context.Activity.Name)
            {
            case Events.DeviceStart:
            {
                var activity = dc.Context.Activity;
                if (activity.SemanticAction != null && activity.SemanticAction.Entities != null && activity.SemanticAction.Entities.Count > 0)
                {
                    state.Keyword            = activity.SemanticAction.Entities["keyword"].Properties["Keyword"].ToString();
                    state.CurrentCoordinates = new LatLng
                    {
                        Latitude  = double.Parse(activity.SemanticAction.Entities["location"].Properties["Latitude"].ToString()),
                        Longitude = double.Parse(activity.SemanticAction.Entities["location"].Properties["Longitude"].ToString())
                    };
                }

                await dc.BeginDialogAsync(nameof(FindPointOfInterestDialog));

                break;
            }

            case Events.Location:
            {
                // Test trigger with
                // /event:{ "Name": "Location", "Value": "34.05222222222222,-118.2427777777777" }
                var value = dc.Context.Activity.Value.ToString();

                if (!string.IsNullOrEmpty(value))
                {
                    var coords = value.Split(',');
                    if (coords.Length == 2)
                    {
                        if (double.TryParse(coords[0], out var lat) && double.TryParse(coords[1], out var lng))
                        {
                            var coordinates = new LatLng
                            {
                                Latitude  = lat,
                                Longitude = lng,
                            };
                            state.CurrentCoordinates = coordinates;
                        }
                    }
                }

                break;
            }

            case Events.ActiveLocation:
            {
                var activeLocationName = dc.Context.Activity.Value.ToString();

                // Set ActiveLocation if one w/ matching name is found in FoundLocations
                var activeLocation = state.LastFoundPointOfInterests?.FirstOrDefault(x => x.Name.Contains(activeLocationName, StringComparison.InvariantCultureIgnoreCase));
                if (activeLocation != null)
                {
                    state.Destination = activeLocation;
                    state.LastFoundPointOfInterests = null;
                }

                // Activity should have text to trigger next intent, update Type & Route again
                if (!string.IsNullOrEmpty(dc.Context.Activity.Text))
                {
                    dc.Context.Activity.Type = ActivityTypes.Message;
                    await RouteAsync(dc);
                }

                break;
            }

            case Events.ActiveRoute:
            {
                int.TryParse(dc.Context.Activity.Value.ToString(), out var routeId);
                var activeRoute = state.FoundRoutes[routeId];
                if (activeRoute != null)
                {
                    state.ActiveRoute = activeRoute;
                    state.FoundRoutes = null;
                }

                var replyMessage = _responseManager.GetResponse(RouteResponses.SendingRouteDetails);
                await dc.Context.SendActivityAsync(replyMessage);

                // Send event with active route data
                var replyEvent = dc.Context.Activity.CreateReply();
                replyEvent.Type  = ActivityTypes.Event;
                replyEvent.Name  = "ActiveRoute.Directions";
                replyEvent.Value = state.ActiveRoute.Legs;
                await dc.Context.SendActivityAsync(replyEvent);

                break;
            }
            }
        }
        protected override async Task OnEventAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Check if there was an action submitted from intro card
            var value = dc.Context.Activity.Value;

            if (value.GetType() == typeof(JObject))
            {
                var submit = JObject.Parse(value.ToString());
                if (value != null && (string)submit["action"] == "startOnboarding")
                {
                    await dc.BeginDialogAsync(nameof(OnboardingDialog));

                    return;
                }
                if (value != null && (string)submit["action"] == "pizzaOrdering")
                {
                    await dc.BeginDialogAsync(nameof(PizzaOrderDialog));

                    return;
                }
                if (value != null && (string)submit["action"] == "orderStatus")
                {
                    await dc.BeginDialogAsync(nameof(PizzaStatusDialog));

                    return;
                }
                if (value != null && (string)submit["action"] == "pizza_base_tops")
                {
                    var pizzaOrderState = await _pizzaOrderingState.GetAsync(dc.Context);

                    pizzaOrderState.Base = (string)submit["BaseChoice"];

                    var vegTops    = (string)submit[$"{pizzaOrderState.Base}VegTops"];
                    var nonVegTops = (string)submit[$"{pizzaOrderState.Base}NonVegTops"];

                    if (!string.IsNullOrEmpty(vegTops))
                    {
                        pizzaOrderState.VegTops = vegTops.Split(",");
                    }
                    if (!string.IsNullOrEmpty(nonVegTops))
                    {
                        pizzaOrderState.NonVegTops = nonVegTops.Split(",");
                    }

                    await dc.ContinueDialogAsync();

                    return;
                }
                if (value != null && (string)submit["action"] == "specialPizza")
                {
                    var pizzaOrderState = await _pizzaOrderingState.GetAsync(dc.Context);

                    pizzaOrderState.IsSpecialPizza = false;
                    if ((string)submit["PizzaChoice"] != "customize")
                    {
                        var fact = 1.0;
                        if (pizzaOrderState.Size == "small")
                        {
                            fact = 0.5;
                        }
                        else if (pizzaOrderState.Size == "medium")
                        {
                            fact = 3.0 / 4.0;
                        }
                        //pizzaOrderState.Toppings = (string)submit["Toppings"];
                        pizzaOrderState.IsSpecialPizza = true;
                        pizzaOrderState.PizzaName      = (string)submit["PizzaChoice"];
                        var connect = new DataBaseOperations("Server=tcp:yoyopizzaserver.database.windows.net,1433;Initial Catalog=PizzaOrderdb;Persist Security Info=False;User ID=shubham;Password=Dota365365;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
                        var pizza   = connect.GetByName(pizzaOrderState.PizzaName);
                        pizzaOrderState.Base       = (string)pizza["base"];
                        pizzaOrderState.Cheese     = (string)pizza["cheese"];
                        pizzaOrderState.Sauce      = (string)pizza["sauce"];
                        pizzaOrderState.Rating     = (string)pizza["rating"];
                        pizzaOrderState.ImageURL   = (string)pizza["imageurl"];
                        pizzaOrderState.VegTops    = ((string)pizza["vegtops"]).Split(", ");
                        pizzaOrderState.NonVegTops = ((string)pizza["nonvegtops"]).Split(", ");
                        pizzaOrderState.Price      = (Convert.ToDouble(pizza["price"]) * fact);
                    }
                    else
                    {
                        pizzaOrderState.PizzaName = "Your Pizza";
                    }

                    await dc.ContinueDialogAsync();

                    return;
                }
                if (value != null && (string)submit["action"] == "confirmOrder")
                {
                    var pizzaOrderState = await _pizzaOrderingState.GetAsync(dc.Context);

                    var onboardingState = await _onboardingState.GetAsync(dc.Context);

                    pizzaOrderState.Ordered = false;
                    var connect = new DataBaseOperations("Server=tcp:yoyopizzaserver.database.windows.net,1433;Initial Catalog=PizzaOrderdb;Persist Security Info=False;User ID=shubham;Password=Dota365365;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
                    pizzaOrderState.OrderId = connect.Add(pizzaOrderState, onboardingState.Number);
                    pizzaOrderState.Ordered = true;
                    await dc.ContinueDialogAsync();

                    return;
                }
            }

            var forward = true;
            var ev      = dc.Context.Activity.AsEventActivity();

            if (!string.IsNullOrWhiteSpace(ev.Name))
            {
                switch (ev.Name)
                {
                case Events.TimezoneEvent:
                {
                    try
                    {
                        var timezone    = ev.Value.ToString();
                        var tz          = TimeZoneInfo.FindSystemTimeZoneById(timezone);
                        var timeZoneObj = new JObject();
                        timeZoneObj.Add(TimeZone, JToken.FromObject(tz));

                        var skillContext = await _skillContextAccessor.GetAsync(dc.Context, () => new SkillContext());

                        if (skillContext.ContainsKey(TimeZone))
                        {
                            skillContext[TimeZone] = timeZoneObj;
                        }
                        else
                        {
                            skillContext.Add(TimeZone, timeZoneObj);
                        }

                        await _skillContextAccessor.SetAsync(dc.Context, skillContext);
                    }
                    catch
                    {
                        await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Timezone passed could not be mapped to a valid Timezone. Property not set."));
                    }

                    forward = false;
                    break;
                }

                case Events.LocationEvent:
                {
                    var location    = ev.Value.ToString();
                    var locationObj = new JObject();
                    locationObj.Add(Location, JToken.FromObject(location));

                    var skillContext = await _skillContextAccessor.GetAsync(dc.Context, () => new SkillContext());

                    if (skillContext.ContainsKey(Location))
                    {
                        skillContext[Location] = locationObj;
                    }
                    else
                    {
                        skillContext.Add(Location, locationObj);
                    }

                    await _skillContextAccessor.SetAsync(dc.Context, skillContext);

                    forward = false;
                    break;
                }

                case TokenEvents.TokenResponseEventName:
                {
                    forward = true;
                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Unknown Event {ev.Name} was received but not processed."));

                    forward = false;
                    break;
                }
                }
            }

            if (forward)
            {
                var result = await dc.ContinueDialogAsync();

                if (result.Status == DialogTurnStatus.Complete)
                {
                    await CompleteAsync(dc);
                }
            }
        }
Beispiel #14
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 #15
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.CognitiveModelSets[locale];

            await PopulateStateFromSemanticAction(dc.Context);

            // If dispatch result is General luis model
            localeConfig.LuisServices.TryGetValue("PointOfInterest", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var turnResult = EndOfTurn;
                var result     = await luisService.RecognizeAsync <PointOfInterestLuis>(dc.Context, CancellationToken.None);

                var intent = result?.TopIntent().intent;

                if (intent != PointOfInterestLuis.Intent.None)
                {
                    var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

                    state.LuisResult = result;
                    await DigestLuisResult(dc, state.LuisResult);
                }

                // switch on General intents
                switch (intent)
                {
                case PointOfInterestLuis.Intent.NAVIGATION_ROUTE_FROM_X_TO_Y:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(RouteDialog));

                    break;
                }

                case PointOfInterestLuis.Intent.NAVIGATION_CANCEL_ROUTE:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(CancelRouteDialog));

                    break;
                }

                case PointOfInterestLuis.Intent.NAVIGATION_FIND_POINTOFINTEREST:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(FindPointOfInterestDialog));

                    break;
                }

                case PointOfInterestLuis.Intent.NAVIGATION_FIND_PARKING:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(FindParkingDialog));

                    break;
                }

                case PointOfInterestLuis.Intent.None:
                {
                    await dc.Context.SendActivityAsync(_responseManager.GetResponse(POISharedResponses.DidntUnderstandMessage));

                    turnResult = new DialogTurnResult(DialogTurnStatus.Complete);

                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(_responseManager.GetResponse(POIMainResponses.FeatureNotAvailable));

                    turnResult = new DialogTurnResult(DialogTurnStatus.Complete);

                    break;
                }
                }

                if (turnResult != EndOfTurn)
                {
                    await CompleteAsync(dc);
                }
            }
        }
Beispiel #16
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new CalendarSkillState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.LocaleConfigurations[locale];

            // If dispatch result is general luis model
            localeConfig.LuisServices.TryGetValue("calendar", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var result = await luisService.RecognizeAsync <Luis.Calendar>(dc.Context, CancellationToken.None);

                var intent           = result?.TopIntent().intent;
                var generalTopIntent = state.GeneralLuisResult?.TopIntent().intent;

                var skillOptions = new CalendarSkillDialogOptions
                {
                    SkillMode = _skillMode,
                };

                // switch on general intents
                switch (intent)
                {
                case Luis.Calendar.Intent.FindMeetingRoom:
                case Luis.Calendar.Intent.CreateCalendarEntry:
                {
                    await dc.BeginDialogAsync(nameof(CreateEventDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.DeleteCalendarEntry:
                {
                    await dc.BeginDialogAsync(nameof(DeleteEventDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.ChangeCalendarEntry:
                {
                    await dc.BeginDialogAsync(nameof(UpdateEventDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.ConnectToMeeting:
                {
                    await dc.BeginDialogAsync(nameof(ConnectToMeetingDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.FindCalendarEntry:
                {
                    await dc.BeginDialogAsync(nameof(SummaryDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.TimeRemaining:
                {
                    await dc.BeginDialogAsync(nameof(TimeRemainingDialog), skillOptions);

                    break;
                }

                case Luis.Calendar.Intent.None:
                {
                    if (generalTopIntent == General.Intent.Next || generalTopIntent == General.Intent.Previous)
                    {
                        await dc.BeginDialogAsync(nameof(SummaryDialog), skillOptions);
                    }
                    else
                    {
                        await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(CalendarSharedResponses.DidntUnderstandMessage));

                        if (_skillMode)
                        {
                            await CompleteAsync(dc);
                        }
                    }

                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(CalendarMainResponses.FeatureNotAvailable));

                    if (_skillMode)
                    {
                        await CompleteAsync(dc);
                    }

                    break;
                }
                }
            }
        }
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new NewsSkillState());

            // If dispatch result is general luis model
            _services.CognitiveModelSets["en"].LuisServices.TryGetValue("news", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var turnResult = EndOfTurn;
                var result     = await luisService.RecognizeAsync <newsLuis>(dc.Context, CancellationToken.None);

                state.LuisResult = result;

                var intent = result?.TopIntent().intent;

                // switch on general intents
                switch (intent)
                {
                case newsLuis.Intent.TrendingArticles:
                {
                    // send articles in response
                    turnResult = await dc.BeginDialogAsync(nameof(TrendingArticlesDialog));

                    break;
                }

                case newsLuis.Intent.SetFavoriteTopics:
                case newsLuis.Intent.ShowFavoriteTopics:
                {
                    // send favorite news categories
                    turnResult = await dc.BeginDialogAsync(nameof(FavoriteTopicsDialog));

                    break;
                }

                case newsLuis.Intent.FindArticles:
                {
                    // send greeting response
                    turnResult = await dc.BeginDialogAsync(nameof(FindArticlesDialog));

                    break;
                }

                case newsLuis.Intent.None:
                {
                    // No intent was identified, send confused message
                    await _responder.ReplyWith(dc.Context, MainResponses.Confused);

                    turnResult = new DialogTurnResult(DialogTurnStatus.Complete);

                    break;
                }

                default:
                {
                    // intent was identified but not yet implemented
                    await dc.Context.SendActivityAsync("This feature is not yet implemented in this skill.");

                    turnResult = new DialogTurnResult(DialogTurnStatus.Complete);

                    break;
                }
                }

                if (turnResult != EndOfTurn)
                {
                    await CompleteAsync(dc);
                }
            }
        }
Beispiel #18
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Check dispatch result
            var dispatchResult = await _services.DispatchRecognizer.RecognizeAsync <Dispatch>(dc, true, CancellationToken.None);

            var intent = dispatchResult.TopIntent().intent;

            if (intent == Dispatch.Intent.l_general)
            {
                // If dispatch result is general luis model
                _services.LuisServices.TryGetValue("general", out var luisService);

                if (luisService == null)
                {
                    throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
                }
                else
                {
                    var result = await luisService.RecognizeAsync <General>(dc, true, CancellationToken.None);

                    var generalIntent = result?.TopIntent().intent;

                    // switch on general intents
                    switch (generalIntent)
                    {
                    case General.Intent.Cancel:
                    {
                        // send cancelled response
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Cancelled);

                        // Cancel any active dialogs on the stack
                        await dc.CancelAllDialogsAsync();

                        break;
                    }

                    case General.Intent.Escalate:
                    {
                        // start escalate dialog
                        await dc.BeginDialogAsync(nameof(EscalateDialog));

                        break;
                    }

                    case General.Intent.Help:
                    {
                        // send help response
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Help);

                        break;
                    }

                    case General.Intent.None:
                    default:
                    {
                        // No intent was identified, send confused message
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);

                        break;
                    }
                    }
                }
            }
            else if (intent == Dispatch.Intent.q_faq)
            {
                _services.QnAServices.TryGetValue("faq", out var qnaService);

                if (qnaService == null)
                {
                    throw new Exception("The specified QnA Maker Service could not be found in your Bot Services configuration.");
                }
                else
                {
                    var answers = await qnaService.GetAnswersAsync(dc.Context);

                    if (answers != null && answers.Count() > 0)
                    {
                        await dc.Context.SendActivityAsync(answers[0].Answer);
                    }
                }
            }
            else if (intent == Dispatch.Intent.q_chitchat)
            {
                _services.QnAServices.TryGetValue("chitchat", out var qnaService);

                if (qnaService == null)
                {
                    throw new Exception("The specified QnA Maker Service could not be found in your Bot Services configuration.");
                }
                else
                {
                    var answers = await qnaService.GetAnswersAsync(dc.Context);

                    if (answers != null && answers.Count() > 0)
                    {
                        await dc.Context.SendActivityAsync(answers[0].Answer);
                    }
                }
            }
            else
            {
                // If dispatch intent does not map to configured models, send "confused" response.
                await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);
            }
        }
Beispiel #19
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get cognitive models for locale
            var locale          = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var cognitiveModels = _services.CognitiveModelSets[locale];

            // Check dispatch result
            var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync <DispatchLuis>(dc.Context, CancellationToken.None);

            var intent = dispatchResult.TopIntent().intent;

            // Identify if the dispatch intent matches any Action within a Skill if so, we pass to the appropriate SkillDialog to hand-off
            var identifiedSkill = SkillRouter.IsSkill(_settings.Skills, intent.ToString());

            if (identifiedSkill != null)
            {
                // We have identiifed a skill so initialize the skill connection with the target skill
                var result = await dc.BeginDialogAsync(identifiedSkill.Id);

                if (result.Status == DialogTurnStatus.Complete)
                {
                    await CompleteAsync(dc);
                }
            }
            else if (intent == DispatchLuis.Intent.l_General)
            {
                // If dispatch result is General luis model
                cognitiveModels.LuisServices.TryGetValue("General", out var luisService);

                if (luisService == null)
                {
                    throw new Exception("The General LUIS Model could not be found in your Bot Services configuration.");
                }
                else
                {
                    var result = await luisService.RecognizeAsync <GeneralLuis>(dc.Context, CancellationToken.None);

                    var generalIntent = result?.TopIntent().intent;

                    // switch on general intents
                    switch (generalIntent)
                    {
                    case GeneralLuis.Intent.Escalate:
                    {
                        // start escalate dialog
                        await dc.BeginDialogAsync(nameof(EscalateDialog));

                        break;
                    }

                    case GeneralLuis.Intent.None:
                    default:
                    {
                        // No intent was identified, send confused message
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);

                        break;
                    }
                    }
                }
            }
            else if (intent == DispatchLuis.Intent.q_Faq)
            {
                cognitiveModels.QnAServices.TryGetValue("Faq", out var qnaService);

                if (qnaService == null)
                {
                    throw new Exception("The specified QnA Maker Service could not be found in your Bot Services configuration.");
                }
                else
                {
                    var answers = await qnaService.GetAnswersAsync(dc.Context, null, null);

                    if (answers != null && answers.Count() > 0)
                    {
                        await dc.Context.SendActivityAsync(answers[0].Answer, speak : answers[0].Answer);
                    }
                    else
                    {
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);
                    }
                }
            }
            else if (intent == DispatchLuis.Intent.q_Chitchat)
            {
                cognitiveModels.QnAServices.TryGetValue("Chitchat", out var qnaService);

                if (qnaService == null)
                {
                    throw new Exception("The specified QnA Maker Service could not be found in your Bot Services configuration.");
                }
                else
                {
                    var answers = await qnaService.GetAnswersAsync(dc.Context, null, null);

                    if (answers != null && answers.Count() > 0)
                    {
                        await dc.Context.SendActivityAsync(answers[0].Answer, speak : answers[0].Answer);
                    }
                    else
                    {
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);
                    }
                }
            }
            else
            {
                // If dispatch intent does not map to configured models, send "confused" response.
                // Alternatively as a form of backup you can try QnAMaker for anything not understood by dispatch.
                await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);
            }
        }
Beispiel #20
0
        private async Task <DialogTurnResult> ForwardToSkill(DialogContext innerDc, Activity activity)
        {
            try
            {
                if (!_skillInitialized)
                {
                    await InitializeSkill(innerDc);
                }

                _inProcAdapter.ProcessActivity(activity, async(skillContext, ct) =>
                {
                    await _activatedSkill.OnTurnAsync(skillContext);
                }, async(activities) =>
                {
                    foreach (var response in activities)
                    {
                        await innerDc.Context.Adapter.ContinueConversationAsync(_endpointService.AppId, response.GetConversationReference(), CreateCallback(response), default(CancellationToken));
                    }
                }).Wait();

                var queue             = new List <Activity>();
                var endOfConversation = false;
                var skillResponse     = _inProcAdapter.GetNextReply();

                while (skillResponse != null)
                {
                    if (skillResponse.Type == ActivityTypes.EndOfConversation)
                    {
                        endOfConversation = true;
                    }
                    else if (skillResponse?.Name == Events.TokenRequestEventName)
                    {
                        // Send trace to emulator
                        await innerDc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"<--Received a Token Request from a skill"));

                        if (!_useCachedTokens)
                        {
                            var adapter = innerDc.Context.Adapter as BotFrameworkAdapter;
                            var tokens  = await adapter.GetTokenStatusAsync(innerDc.Context, innerDc.Context.Activity.From.Id);

                            foreach (var token in tokens)
                            {
                                await adapter.SignOutUserAsync(innerDc.Context, token.ConnectionName, innerDc.Context.Activity.From.Id, default(CancellationToken));
                            }
                        }

                        var authResult = await innerDc.BeginDialogAsync(nameof(MultiProviderAuthDialog));

                        if (authResult.Result?.GetType() == typeof(ProviderTokenResponse))
                        {
                            var tokenEvent = skillResponse.CreateReply();
                            tokenEvent.Type  = ActivityTypes.Event;
                            tokenEvent.Name  = Events.TokenResponseEventName;
                            tokenEvent.Value = authResult.Result as ProviderTokenResponse;

                            return(await ForwardToSkill(innerDc, tokenEvent));
                        }
                        else
                        {
                            return(authResult);
                        }
                    }
                    else
                    {
                        if (skillResponse.Type == ActivityTypes.Trace)
                        {
                            // Write out any trace messages from the skill to the emulator
                            await innerDc.Context.SendActivityAsync(skillResponse);
                        }
                        else
                        {
                            queue.Add(skillResponse);
                        }
                    }

                    skillResponse = _inProcAdapter.GetNextReply();
                }

                // send skill queue to User
                if (queue.Count > 0)
                {
                    // if the conversation id from the activity is the same as the context activity, it's reactive message
                    await innerDc.Context.SendActivitiesAsync(queue.ToArray());
                }

                // handle ending the skill conversation
                if (endOfConversation)
                {
                    await innerDc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"<--Ending the skill conversation"));

                    return(await innerDc.EndDialogAsync());
                }
                else
                {
                    return(EndOfTurn);
                }
            }
            catch
            {
                // something went wrong forwarding to the skill, so end dialog cleanly and throw so the error is logged.
                // NOTE: errors within the skill itself are handled by the OnTurnError handler on the adapter.
                await innerDc.EndDialogAsync();

                throw;
            }
        }
Beispiel #21
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _conversationStateAccessor.GetAsync(dc.Context, () => new SkillConversationState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.LocaleConfigurations[locale];

            // Get skill LUIS model from configuration
            localeConfig.LuisServices.TryGetValue("$safeprojectname$", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var skillOptions = new SkillTemplateDialogOptions
                {
                    SkillMode = _skillMode,
                };

                var turnResult = EndOfTurn;
                var result     = await luisService.RecognizeAsync <$safeprojectname$LU> (dc.Context, CancellationToken.None);

                var intent = result?.TopIntent().intent;

                switch (intent)
                {
                case $safeprojectname$LU.Intent.Sample:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(SampleDialog), skillOptions);

                    break;
                }

                case $safeprojectname$LU.Intent.None:
                {
                    // No intent was identified, send confused message
                    await dc.Context.SendActivityAsync(_responseManager.GetResponse(SharedResponses.DidntUnderstandMessage));

                    if (_skillMode)
                    {
                        turnResult = new DialogTurnResult(DialogTurnStatus.Complete);
                    }

                    break;
                }

                default:
                {
                    // intent was identified but not yet implemented
                    await dc.Context.SendActivityAsync(_responseManager.GetResponse(MainResponses.FeatureNotAvailable));

                    if (_skillMode)
                    {
                        turnResult = new DialogTurnResult(DialogTurnStatus.Complete);
                    }

                    break;
                }
                }

                if (turnResult != EndOfTurn)
                {
                    await CompleteAsync(dc);
                }
            }
        }
Beispiel #22
0
        private async Task <DialogTurnResult> HandleMessage(DialogContext dc, CancellationToken cancellationToken = default)
        {
            if (BreakingActionHandler.IsBreakingAction(dc.Context.Activity.Text, out BreakingAction? action))
            {
                return(await BreakingActionHandler.ExecuteBrakingAction(action.Value, dc, cancellationToken));
            }
            else if (!string.IsNullOrEmpty(dc.Context.Activity.Text))
            {
                if (dc.Context.Activity.Text != null && !IsAllCharSinhala(dc.Context.Activity.Text.Replace(" ", "")))
                {
                    dc.Context.Activity.Text = await new Translation().EnglishTOSinhala(dc.Context.Activity.Text);
                }
                var intent = await new EntityClassifier().GetResultAsync(dc, _modelApi);
                ChatLogger(dc, intent);
                var kbResult = await _messagingApi.SendMessageAsync(dc.Context.Activity.Conversation.Id, dc.Context.Activity.Text);

                switch (intent?.Intent?.Name)
                {
                case BotIntents.FoodOrder:
                    {
                        try
                        {
                            if (intent.Entities.Count > 0)
                            {
                                return(await dc.BeginDialogAsync(nameof(FoodOrderDialog), intent, cancellationToken: cancellationToken));
                            }
                            else
                            {
                                return(await dc.BeginDialogAsync(nameof(FoodOrderDialog), cancellationToken : cancellationToken));
                            }
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                    }

                case BotIntents.GetInTouch:
                {
                    return(await dc.BeginDialogAsync(nameof(ContactUsDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.AboutRestaurant:
                {
                    return(await dc.BeginDialogAsync(nameof(AboutRestaurentDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.WhatIs:
                {
                    if (intent.Entities.Count > 0)
                    {
                        await dc.Context.SendActivityAsync(await new WikiData().getWikiDataAsync(intent.Entities.FirstOrDefault().Value.ToString()) != null?await new WikiData().getWikiDataAsync(intent.Entities.FirstOrDefault().Value.ToString()) : "මට එය වෑටහුනේ නෑ.කරුණාකර නැවත පවසන්න. ", cancellationToken : cancellationToken);

                        return(EndOfTurn);
                    }
                    else
                    {
                        await dc.Context.SendActivityAsync(await new WikiData().getWikiDataAsync(dc.Context.Activity.Text) != null?await new WikiData().getWikiDataAsync(dc.Context.Activity.Text) : "මට එය වෑටහුනේ නෑ.කරුණාකර නැවත පවසන්න. ", cancellationToken : cancellationToken);

                        return(EndOfTurn);
                    }


                    //await dc.BeginDialogAsync(nameof(AboutRestaurentDialog), cancellationToken: cancellationToken);
                }

                case BotIntents.WhatCanYouDo:
                {
                    return(await dc.BeginDialogAsync(nameof(WhatCanYouDoDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.CreatedBy:
                {
                    return(await dc.BeginDialogAsync(nameof(CreatedByDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.ImBored:
                {
                    return(await dc.BeginDialogAsync(nameof(ImBoredDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.Food_Categories:
                {
                    return(await dc.BeginDialogAsync(nameof(FoodCategoriesDialog), cancellationToken : cancellationToken));
                }

                case BotIntents.Deny:
                {
                    await dc.Context.SendActivityAsync("එය වටහා ගැනීමට තරම් මගේ දැනුම ප්‍රමානවත් නැහැ.කරුණාකර මදක් පැහැදිලි කර නැවත පවසන්න.", cancellationToken : cancellationToken);

                    return(EndOfTurn);
                }

                default:
                    await ShowKBResponse(kbResult, dc.Context, cancellationToken);

                    return(EndOfTurn);
                }
            }
            else
            {
                return(EndOfTurn);
            }
        }
Beispiel #23
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var routeResult = EndOfTurn;

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.LocaleConfigurations[locale];

            // If dispatch result is general luis model
            localeConfig.LuisServices.TryGetValue("pointofinterest", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var result = await luisService.RecognizeAsync <PointOfInterest>(dc, true, CancellationToken.None);

                var intent = result?.TopIntent().intent;

                var skillOptions = new PointOfInterestSkillDialogOptions
                {
                    SkillMode = _skillMode,
                };

                // switch on general intents
                switch (intent)
                {
                case PointOfInterest.Intent.NAVIGATION_ROUTE_FROM_X_TO_Y:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(RouteDialog), skillOptions);

                    break;
                }

                case PointOfInterest.Intent.NAVIGATION_CANCEL_ROUTE:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(CancelRouteDialog), skillOptions);

                    break;
                }

                case PointOfInterest.Intent.NAVIGATION_FIND_POINTOFINTEREST:
                {
                    routeResult = await dc.BeginDialogAsync(nameof(FindPointOfInterestDialog), skillOptions);

                    break;
                }

                case PointOfInterest.Intent.None:
                {
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(POISharedResponses.DidntUnderstandMessage));

                    if (_skillMode)
                    {
                        routeResult = new DialogTurnResult(DialogTurnStatus.Complete);
                    }

                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(POIMainResponses.FeatureNotAvailable));

                    if (_skillMode)
                    {
                        routeResult = new DialogTurnResult(DialogTurnStatus.Complete);
                    }

                    break;
                }
                }
            }

            if (routeResult.Status == DialogTurnStatus.Complete)
            {
                await CompleteAsync(dc);
            }
        }
Beispiel #24
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _toDoStateAccessor.GetAsync(dc.Context, () => new ToDoSkillState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.LocaleConfigurations[locale];

            // Initialize the PageSize and ReadSize parameters in state from configuration
            InitializeConfig(state);

            // If dispatch result is general luis model
            localeConfig.LuisServices.TryGetValue("todo", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var result = await luisService.RecognizeAsync <ToDo>(dc.Context, CancellationToken.None);

                var intent           = result?.TopIntent().intent;
                var generalTopIntent = state.GeneralLuisResult?.TopIntent().intent;

                var skillOptions = new ToDoSkillDialogOptions
                {
                    SkillMode = _skillMode,
                };

                // switch on general intents
                switch (intent)
                {
                case ToDo.Intent.AddToDo:
                {
                    await dc.BeginDialogAsync(nameof(AddToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.MarkToDo:
                {
                    await dc.BeginDialogAsync(nameof(MarkToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.DeleteToDo:
                {
                    await dc.BeginDialogAsync(nameof(DeleteToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.ShowToDo:
                {
                    await dc.BeginDialogAsync(nameof(ShowToDoItemDialog), skillOptions);

                    break;
                }

                case ToDo.Intent.None:
                {
                    if (generalTopIntent == General.Intent.Next ||
                        generalTopIntent == General.Intent.Previous ||
                        generalTopIntent == General.Intent.ReadMore)
                    {
                        await dc.BeginDialogAsync(nameof(ShowToDoItemDialog), skillOptions);
                    }
                    else
                    {
                        // No intent was identified, send confused message
                        await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(ToDoMainResponses.DidntUnderstandMessage));

                        if (_skillMode)
                        {
                            await CompleteAsync(dc);
                        }
                    }

                    break;
                }

                default:
                {
                    // intent was identified but not yet implemented
                    await dc.Context.SendActivityAsync(dc.Context.Activity.CreateReply(ToDoMainResponses.FeatureNotAvailable));

                    if (_skillMode)
                    {
                        await CompleteAsync(dc);
                    }

                    break;
                }
                }
            }
        }
Beispiel #25
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await _stateAccessor.GetAsync(dc.Context, () => new CalendarSkillState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.CognitiveModelSets[locale];

            // Initialize the PageSize parameters in state from configuration
            InitializeConfig(state);

            // If dispatch result is general luis model
            localeConfig.LuisServices.TryGetValue("calendar", out var luisService);

            if (luisService == null)
            {
                throw new Exception("The specified LUIS Model could not be found in your Bot Services configuration.");
            }
            else
            {
                var turnResult       = EndOfTurn;
                var intent           = state.LuisResult?.TopIntent().intent;
                var generalTopIntent = state.GeneralLuisResult?.TopIntent().intent;

                // switch on general intents
                switch (intent)
                {
                case CalendarLuis.Intent.FindMeetingRoom:
                case CalendarLuis.Intent.CreateCalendarEntry:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(CreateEventDialog));

                    break;
                }

                case CalendarLuis.Intent.AcceptEventEntry:
                case CalendarLuis.Intent.DeleteCalendarEntry:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(ChangeEventStatusDialog));

                    break;
                }

                case CalendarLuis.Intent.ChangeCalendarEntry:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(UpdateEventDialog));

                    break;
                }

                case CalendarLuis.Intent.ConnectToMeeting:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(ConnectToMeetingDialog));

                    break;
                }

                case CalendarLuis.Intent.FindCalendarEntry:
                case CalendarLuis.Intent.FindCalendarDetail:
                case CalendarLuis.Intent.FindCalendarWhen:
                case CalendarLuis.Intent.FindCalendarWhere:
                case CalendarLuis.Intent.FindCalendarWho:
                case CalendarLuis.Intent.FindDuration:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(SummaryDialog));

                    break;
                }

                case CalendarLuis.Intent.TimeRemaining:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(TimeRemainingDialog));

                    break;
                }

                case CalendarLuis.Intent.ShowNextCalendar:
                case CalendarLuis.Intent.ShowPreviousCalendar:
                {
                    turnResult = await dc.BeginDialogAsync(nameof(SummaryDialog));

                    break;
                }

                case CalendarLuis.Intent.None:
                {
                    if (generalTopIntent == General.Intent.ShowNext || generalTopIntent == General.Intent.ShowPrevious)
                    {
                        turnResult = await dc.BeginDialogAsync(nameof(SummaryDialog));
                    }
                    else
                    {
                        await dc.Context.SendActivityAsync(_responseManager.GetResponse(CalendarSharedResponses.DidntUnderstandMessage));

                        turnResult = new DialogTurnResult(DialogTurnStatus.Complete);
                    }

                    break;
                }

                default:
                {
                    await dc.Context.SendActivityAsync(_responseManager.GetResponse(CalendarMainResponses.FeatureNotAvailable));

                    turnResult = new DialogTurnResult(DialogTurnStatus.Complete);

                    break;
                }
                }

                if (turnResult != EndOfTurn)
                {
                    await CompleteAsync(dc);
                }
            }
        }
 public async Task StockIntent(DialogContext context, RecognizerResult result, CancellationToken token)
 {
     await context.BeginDialogAsync(StockDialog.Id, result, token);
 }
Beispiel #27
0
        public async override Task <DialogTurnResult> ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var turnContext = dc.Context;
            var step        = dc.ActiveDialog.State;

            // Get reservation property.
            var newReservation = await _reservationsAccessor.GetAsync(turnContext, () => new ReservationProperty());

            // Get on turn property. This has any entities that mainDispatcher,
            // or Bot might have captured in its LUIS model.
            var onTurnProperties = await _onTurnAccessor.GetAsync(turnContext, () => new OnTurnProperty("None", new List <EntityProperty>()));

            // If on turn property has entities..
            ReservationResult updateResult = null;

            if (onTurnProperties.Entities.Count > 0)
            {
                // ...update reservation property with on turn property results.
                updateResult = newReservation.UpdateProperties(onTurnProperties);
            }

            // See if updates to reservation resulted in errors, if so, report them to user.
            if (updateResult != null &&
                updateResult.Status == ReservationStatus.Incomplete &&
                updateResult.Outcome != null &&
                updateResult.Outcome.Count > 0)
            {
                await _reservationsAccessor.SetAsync(turnContext, updateResult.NewReservation);

                // Return and do not continue if there is an error.
                await turnContext.SendActivityAsync(updateResult.Outcome[0].Message);

                return(await base.ContinueDialogAsync(dc));
            }

            // Call LUIS and get results.
            var luisResults   = await _botServices.LuisServices[LuisConfiguration].RecognizeAsync(turnContext, cancellationToken);
            var topLuisIntent = luisResults.GetTopScoringIntent();
            var topIntent     = topLuisIntent.intent;

            // If we don't have an intent match from LUIS, go with the intent available via
            // the on turn property (parent's LUIS model).
            if (luisResults.Intents.Count <= 0)
            {
                // Go with intent in onTurnProperty.
                topIntent = string.IsNullOrWhiteSpace(onTurnProperties.Intent) ? "None" : onTurnProperties.Intent;
            }

            // Update object with LUIS result.
            updateResult = newReservation.UpdateProperties(OnTurnProperty.FromLuisResults(luisResults));

            // See if update reservation resulted in errors, if so, report them to user.
            if (updateResult != null &&
                updateResult.Status == ReservationStatus.Incomplete &&
                updateResult.Outcome != null &&
                updateResult.Outcome.Count > 0)
            {
                // Set reservation property.
                await _reservationsAccessor.SetAsync(turnContext, updateResult.NewReservation);

                // Return and do not continue if there is an error.
                await turnContext.SendActivityAsync(updateResult.Outcome[0].Message);

                return(await base.ContinueDialogAsync(dc));
            }

            // Did user ask for help or said cancel or continuing the conversation?
            switch (topIntent)
            {
            case ContinuePromptIntent:
                // User does not want to make any change.
                updateResult.NewReservation.NeedsChange = false;
                break;

            case NoChangeIntent:
                // User does not want to make any change.
                updateResult.NewReservation.NeedsChange = false;
                break;

            case HelpIntent:
                // Come back with contextual help.
                var helpReadOut = updateResult.NewReservation.HelpReadOut();
                await turnContext.SendActivityAsync(helpReadOut);

                break;

            case CancelIntent:
                // Start confirmation prompt.
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        Text = "Are you sure you want to cancel?",
                    },
                };

                return(await dc.PromptAsync(ConfirmCancelPrompt, opts));

            case InterruptionsIntent:
            default:
                // If we picked up new entity values, do not treat this as an interruption.
                if (onTurnProperties.Entities.Count != 0 || luisResults.Entities.Count > 1)
                {
                    break;
                }

                // Handle interruption.
                var onTurnProperty = await _onTurnAccessor.GetAsync(dc.Context);

                return(await dc.BeginDialogAsync(InterruptionDispatcher, onTurnProperty));
            }

            // Set reservation property based on OnTurn properties.
            await _reservationsAccessor.SetAsync(turnContext, updateResult.NewReservation);

            return(await base.ContinueDialogAsync(dc));
        }
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parameters = await _parametersAccessor.GetAsync(dc.Context, () => new Dictionary <string, object>());

            var virtualAssistantState = await _virtualAssistantState.GetAsync(dc.Context, () => new VirtualAssistantState());

            // get current activity locale
            var locale       = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var localeConfig = _services.LocaleConfigurations[locale];

            // No dialog is currently on the stack and we haven't responded to the user
            // Check dispatch result
            var dispatchResult = await localeConfig.DispatchRecognizer.RecognizeAsync <Dispatch>(dc, CancellationToken.None);

            var intent = dispatchResult.TopIntent().intent;

            switch (intent)
            {
            case Dispatch.Intent.l_General:
            {
                // If dispatch result is general luis model
                var luisService = localeConfig.LuisServices["general"];
                var luisResult  = await luisService.RecognizeAsync <General>(dc, CancellationToken.None);

                var luisIntent = luisResult?.TopIntent().intent;

                // switch on general intents
                if (luisResult.TopIntent().score > 0.5)
                {
                    switch (luisIntent)
                    {
                    case General.Intent.Help:
                    {
                        // send help response
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Help);

                        break;
                    }

                    case General.Intent.Cancel:
                    {
                        // if this was triggered, then there is no active dialog
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.NoActiveDialog);

                        break;
                    }

                    case General.Intent.Escalate:
                    {
                        // start escalate dialog
                        await dc.BeginDialogAsync(nameof(EscalateDialog));

                        break;
                    }

                    case General.Intent.Logout:
                    {
                        await LogoutAsync(dc);

                        break;
                    }

                    case General.Intent.ShowNext:
                    case General.Intent.ShowPrevious:
                    {
                        var lastExecutedIntent = virtualAssistantState.LastIntent;
                        if (lastExecutedIntent != null)
                        {
                            var matchedSkill = _skillRouter.IdentifyRegisteredSkill(lastExecutedIntent);
                            await RouteToSkillAsync(dc, new SkillDialogOptions()
                                    {
                                        SkillDefinition = matchedSkill,
                                        Parameters      = parameters,
                                    });
                        }

                        break;
                    }

                    case General.Intent.None:
                    default:
                    {
                        // No intent was identified, send confused message
                        await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);

                        break;
                    }
                    }
                }

                break;
            }

            case Dispatch.Intent.l_Calendar:
            case Dispatch.Intent.l_Email:
            case Dispatch.Intent.l_ToDo:
            case Dispatch.Intent.l_PointOfInterest:
            {
                virtualAssistantState.LastIntent = intent.ToString();
                var matchedSkill = _skillRouter.IdentifyRegisteredSkill(intent.ToString());

                await RouteToSkillAsync(dc, new SkillDialogOptions()
                    {
                        SkillDefinition = matchedSkill,
                        Parameters      = parameters,
                    });

                break;
            }

            case Dispatch.Intent.q_FAQ:
            {
                var qnaService = localeConfig.QnAServices["faq"];
                var answers    = await qnaService.GetAnswersAsync(dc.Context);

                if (answers != null && answers.Count() > 0)
                {
                    await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Qna, answers[0].Answer);
                }

                break;
            }

            case Dispatch.Intent.q_Chitchat:
            {
                var qnaService = localeConfig.QnAServices["chitchat"];
                var answers    = await qnaService.GetAnswersAsync(dc.Context);

                if (answers != null && answers.Count() > 0)
                {
                    await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Qna, answers[0].Answer);
                }

                break;
            }

            case Dispatch.Intent.None:
            {
                // No intent was identified, send confused message
                await _responder.ReplyWith(dc.Context, MainResponses.ResponseIds.Confused);

                break;
            }
            }
        }
        public override async Task <DialogTurnResult> ContinueDialogAsync(DialogContext dc, CancellationToken cancellationToken = default)
        {
            var lastaskedquestion = await LastAskedAccessor.GetAsync(dc.Context, cancellationToken : cancellationToken);

            switch (lastaskedquestion)
            {
            case "anythingelse":
            {
                var phraseType = Helper.GetPhraseType(dc.Context.Activity.Text);
                switch (phraseType)
                {
                case PhraseType.Positive:
                {
                    await LastAskedAccessor.DeleteAsync(dc.Context, cancellationToken : cancellationToken);

                    return(await dc.ReplaceDialogAsync(nameof(FoodOrderDialog), cancellationToken : cancellationToken));
                }

                case PhraseType.Negative:
                {
                    //var cart = await Mediator.Send(new Application.Queries.ViewCartQuery(dc.Context.Activity.GetConversationReference()));
                    //if (cart != null && cart.NumberOfItems > 0)
                    //{
                    //    await Helper.SendConfirmationPrompt("Do You want to checkout?", dc.Context, cancellationToken);
                    //    await LastAskedAccessor.SetAsync(dc.Context, "wanttocheckout", cancellationToken: cancellationToken);
                    //    return EndOfTurn;
                    //}
                    //else
                    //{
                    await dc.Context.SendActivityAsync("මට ඔබට සහය විය හැක්කේ කෙසේද ?", cancellationToken : cancellationToken);

                    return(await dc.EndDialogAsync(cancellationToken : cancellationToken));

                    //}
                }

                default:
                {
                    await LastAskedAccessor.DeleteAsync(dc.Context, cancellationToken : cancellationToken);

                    await dc.CancelAllDialogsAsync(cancellationToken);

                    return(await dc.BeginDialogAsync(nameof(MainDialog), "no_intro_msg", cancellationToken : cancellationToken));
                }
                }
            }

            case "wanttocheckout":
            {
                var phraseType = Helper.GetPhraseType(dc.Context.Activity.Text);
                switch (phraseType)
                {
                case PhraseType.Positive:
                {
                    // return await dc.ReplaceDialogAsync(nameof(ViewCartDialog), cancellationToken: cancellationToken);
                    return(EndOfTurn);
                }

                case PhraseType.Negative:
                {
                    await dc.Context.SendActivityAsync("Is there anything else I can do for you?", cancellationToken : cancellationToken);

                    return(await dc.EndDialogAsync(cancellationToken : cancellationToken));
                }

                default:
                {
                    await dc.CancelAllDialogsAsync(cancellationToken);

                    return(await dc.BeginDialogAsync(nameof(MainDialog), "no_intro_msg", cancellationToken : cancellationToken));
                }
                }
            }

            default:
            {
                await LastAskedAccessor.DeleteAsync(dc.Context, cancellationToken : cancellationToken);

                await dc.CancelAllDialogsAsync(cancellationToken);

                return(await dc.BeginDialogAsync(nameof(MainDialog), "no_intro_msg", cancellationToken : cancellationToken));
            }
            }
            return(EndOfTurn);
        }
Beispiel #30
0
        protected override async Task RouteAsync(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the conversation state from the turn context
            var state = await _accessors.PointOfInterestSkillState.GetAsync(dc.Context, () => new PointOfInterestSkillState());

            var dialogState = await _accessors.ConversationDialogState.GetAsync(dc.Context, () => new DialogState());

            PointOfInterest luisResult = null;

            if (_services?.LuisRecognizer != null)
            {
                // When run in normal mode or 2+ turn of a skill we use LUIS ourselves as the parent Dispatcher doesn't do this
                luisResult = await _services.LuisRecognizer.RecognizeAsync <PointOfInterest>(dc.Context, cancellationToken);
            }
            else if (_skillMode && state.LuisResultPassedFromSkill != null)
            {
                // If invoked by a Skill we get the Luis IRecognizerConvert passed to us on first turn so we don't have to do that locally
                luisResult = (PointOfInterest)state.LuisResultPassedFromSkill;
            }
            else
            {
                throw new Exception("PointOfInterestSkill: Could not get Luis Recognizer result.");
            }

            await DigestPointOfInterestLuisResult(dc, luisResult);

            var intent = luisResult?.TopIntent().intent;

            var skillOptions = new PointOfInterestSkillDialogOptions
            {
                SkillMode = _skillMode,
            };

            var result = EndOfTurn;

            switch (intent)
            {
            case PointOfInterest.Intent.NAVIGATION_ROUTE_FROM_X_TO_Y:
            {
                result = await dc.BeginDialogAsync(nameof(RouteDialog), skillOptions);

                break;
            }

            case PointOfInterest.Intent.NAVIGATION_CANCEL_ROUTE:
            {
                result = await dc.BeginDialogAsync(nameof(CancelRouteDialog), skillOptions);

                break;
            }

            case PointOfInterest.Intent.NAVIGATION_FIND_POINTOFINTEREST:
            {
                result = await dc.BeginDialogAsync(nameof(FindPointOfInterestDialog), skillOptions);

                break;
            }

            case PointOfInterest.Intent.None:
            case null:
            default:
            {
                result = new DialogTurnResult(DialogTurnStatus.Complete);
                await _responder.ReplyWith(dc.Context, PointOfInterestSkillResponses.Confused);

                break;
            }
            }

            if (result.Status == DialogTurnStatus.Complete)
            {
                await CompleteAsync(dc);
            }
        }