Esempio n. 1
0
        private async Task <DialogTurnResult> FinalStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            Console.WriteLine("+++++++FinalStepAsync+++++++++++");
            var message = (string)stepContext.Result;

            string status = "🎊🎊🎊  The game ends, " + message + "!  🎊🎊🎊";
            await stepContext.Context.SendActivityAsync(status);

            var accessor = _conversationState.CreateProperty <ConversationData>(nameof(ConversationData));
            var gameData = await accessor.GetAsync(stepContext.Context, () => new ConversationData());

            await stepContext.Context.SendActivityAsync("What to know who were the special players?");

            foreach (var pair in gameData.RoleToUsers)
            {
                Logger.LogInformation("The role is {0}", pair.Key);
                if (pair.Key != Role.Villager.ToString())
                {
                    var roleNames = pair.Value.Select(pid => gameData.UserProfileMap.GetValueOrDefault(pid, pid));
                    await stepContext.Context.SendActivityAsync($"{pair.Key}: {string.Join(", ", roleNames)}");
                }
            }
            // await stepContext.Context.SendActivityAsync($"{player.Name}: {player.Role.ToString()}");

            // Clean up the Property Data
            await accessor.SetAsync(stepContext.Context, new ConversationData(), cancellationToken);

            await _conversationState.SaveChangesAsync(stepContext.Context, false, cancellationToken);

            return(await stepContext.EndDialogAsync("Official End", cancellationToken));
        }
Esempio n. 2
0
        public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            await base.OnTurnAsync(turnContext, cancellationToken);

            await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);

            await _userState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
        public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            await base.OnTurnAsync(turnContext, cancellationToken);

            // Save any state changes that might have occurred during the turn.
            await ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);

            await UserState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
Esempio n. 4
0
        /// <summary>
        /// Every conversation turn for our Basic Bot will call this method.
        /// </summary>
        /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed
        /// for processing this conversation turn. </param>
        /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            // See https://aka.ms/about-bot-activity-message to learn more about message and other activity types.
            switch (turnContext.Activity.Type)
            {
            case ActivityTypes.Message:
                // Process on turn input (card or NLP) and gather new properties.
                // OnTurnProperty object has processed information from the input message activity.
                var onTurnProperties = await DetectIntentAndEntitiesAsync(turnContext);

                if (onTurnProperties == null)
                {
                    break;
                }

                // Set the state with gathered properties (intent/ entities) through the onTurnAccessor.
                await _onTurnAccessor.SetAsync(turnContext, onTurnProperties);

                // Create dialog context.
                var dc = await _dialogs.CreateContextAsync(turnContext);

                // Continue outstanding dialogs.
                await dc.ContinueDialogAsync();

                // Begin main dialog if no outstanding dialogs/ no one responded.
                if (!dc.Context.Responded)
                {
                    await dc.BeginDialogAsync(nameof(MainDispatcher));
                }

                break;

            case ActivityTypes.ConversationUpdate:
                if (turnContext.Activity.MembersAdded != null)
                {
                    await SendWelcomeMessageAsync(turnContext);
                }

                break;

            default:
                // Handle other activity types as needed.
                await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected");

                break;
            }

            await ConversationState.SaveChangesAsync(turnContext);

            await UserState.SaveChangesAsync(turnContext);
        }
Esempio n. 5
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.

                // QnA//
                await QnAResponse(turnContext, cancellationToken);
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 6
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Recognize what the user said.
                var topIntent = await GreetingHelpCancelRecognizer(turnContext, cancellationToken);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 7
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // See if LUIS found and used an entity to determine user intent.
                var entityFound = ParseLuisForEntities(luisResults);

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            //await dc.BeginDialogAsync(nameof(GreetingDialog));
                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;

                        case BuyIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // Inform the user if LUIS used an entity.
                            if (entityFound.ToString() != string.Empty)
                            {
                                string[] cutEntity = entityFound.Split("|SEP|");
                                //await turnContext.SendActivityAsync($"==>LUIS String: {entityFound}\n");
                                int  count       = 0;
                                bool entityCheck = false;
                                foreach (var cutEntityValue in cutEntity)
                                {
                                    if (cutEntityValue != string.Empty)
                                    {
                                        count++;
                                        if (count == 3)
                                        {
                                            entityCheck = true;
                                        }
                                    }
                                }

                                if (entityCheck)
                                {
                                    /*
                                     * foreach (var cutEntityValue in cutEntity)
                                     * {
                                     *  await turnContext.SendActivityAsync($"==>LUIS Entity: {cutEntityValue}\n");
                                     * }
                                     * await turnContext.SendActivityAsync($"==>LUIS Entity Found: {entityFound}\n");
                                     */
                                    /*
                                     * // 카드는 html에서 출력
                                     * var buyCard = CreateBuyCardAttachment(@".\Dialogs\BuyIntent\Resources\buyCard.json", entityFound);
                                     * var response = CreateResponse(activity, buyCard);
                                     * await dc.Context.SendActivityAsync(response);
                                     */

                                    // html에 인텐트+엔티티 전달
                                    Activity buyReply = activity.CreateReply();
                                    buyReply.Type  = ActivityTypes.Event;
                                    buyReply.Name  = "buystock";
                                    buyReply.Value = entityFound.ToString();
                                    await dc.Context.SendActivityAsync(buyReply);
                                }
                                else
                                {
                                    await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매수해줘\")");
                                }
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매수해줘\")");
                            }



                            break;

                        case SellIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // Inform the user if LUIS used an entity.
                            if (entityFound.ToString() != string.Empty)
                            {
                                string[] cutEntity = entityFound.Split("|SEP|");
                                //await turnContext.SendActivityAsync($"==>LUIS Count: {cutEntity.Length}\n");
                                foreach (var cutEntityValue in cutEntity)
                                {
                                    //await turnContext.SendActivityAsync($"==>LUIS Entity: {cutEntityValue}\n");
                                }
                                //await turnContext.SendActivityAsync($"==>LUIS Entity Found: {entityFound}\n");

                                /*
                                 * // 카드는 html에서 출력
                                 * var sellCard = CreateSellCardAttachment(@".\Dialogs\BuyIntent\Resources\buyCard.json", entityFound);
                                 * var sell_response = CreateResponse(activity, sellCard);
                                 * await dc.Context.SendActivityAsync(sell_response);
                                 */

                                // html에 인텐트+엔티티 전달
                                Activity sellReply = activity.CreateReply();
                                sellReply.Type  = ActivityTypes.Event;
                                sellReply.Name  = "sellstock";
                                sellReply.Value = entityFound.ToString();
                                await dc.Context.SendActivityAsync(sellReply);
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"종목, 수량, 단가를 모두 입력해주세요.\n(예시:\"신한지주 1주 현재가로 매도해줘\")");
                            }


                            break;

                        case BalanceIntent:
                            //await dc.Context.SendActivityAsync(topIntent);

                            // html에 인텐트+엔티티 전달
                            Activity balanceReply = activity.CreateReply();
                            balanceReply.Type  = ActivityTypes.Event;
                            balanceReply.Name  = "balancestock";
                            balanceReply.Value = entityFound.ToString();
                            await dc.Context.SendActivityAsync(balanceReply);

                            break;

                        case SkinBalanceIntent:
                            // html에 인텐트+엔티티 전달
                            Activity balanceSkinReply = activity.CreateReply();
                            balanceSkinReply.Type  = ActivityTypes.Event;
                            balanceSkinReply.Name  = "balanceskin";
                            balanceSkinReply.Value = entityFound.ToString();
                            await dc.Context.SendActivityAsync(balanceSkinReply);

                            // 잔고인텐트 일때는 잔고 카드 전달
                            var balanceCard = CreateWelcomeCardAttachment(@".\Dialogs\BalanceIntent\Resources\balanceCard.json");
                            var response    = CreateResponse(activity, balanceCard);
                            await dc.Context.SendActivityAsync(response);

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id == activity.Recipient.Id)
                        {
                            var welcomeCard = CreateWelcomeCardAttachment(@".\Dialogs\Welcome\Resources\welcomeCard.json");
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 8
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 9
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                if (activity.Attachments != null && activity.Attachments.Any())
                {
                    // We know the user is sending an attachment as there is at least one item
                    // in the Attachments list.
                    await HandleIncomingAttachmentAsync(dc, activity);

                    return;
                }

                if (activity.Text?.Trim()?.ToLowerInvariant() == "hi")
                {
                    await turnContext.SendActivitiesAsync(
                        new IActivity[]
                    {
                        new Activity(type: ActivityTypes.Message, text: "Hi! 🙋‍"),
                        new Activity(type: ActivityTypes.Message, text: "Send me a picture of a handwritten digit and I'll tell you what the number is!"),
                        new Activity(type: ActivityTypes.Message, text: "Yeah, I'm that smart! 😎"),
                    },
                        cancellationToken);
                }

                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 10
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case PruebaIntent:
                            await dc.BeginDialogAsync(nameof(PruebaDialog));

                            break;

                        case TransactionIntent:
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response).ConfigureAwait(false);

                            break;

                        case NoneIntent:
                        default:
                            await dc.Context.SendActivityAsync("Disculpa, No te entendí lo que me quieres decir");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded.Any())
                {
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 11
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            this.turnContextResolverService.UpdateTurnContext(turnContext);
            await this.userState.LoadAsync(turnContext);

            var activity = turnContext.Activity;

            // Create a dialog context
            var dialogContext = await Dialogs.CreateContextAsync(turnContext);

            try
            {
                if (activity.Type == ActivityTypes.Message)
                {
                    // Continue the current dialog
                    var dialogResult = await dialogContext.ContinueDialogAsync();

                    // if no one has responded,
                    if (!dialogContext.Context.Responded)
                    {
                        // examine results from active dialog
                        switch (dialogResult.Status)
                        {
                        case DialogTurnStatus.Empty:
                            // Perform a call to LUIS to retrieve results for the current activity message.
                            var luisResults      = await services.LuisServices[LuisConfiguration].RecognizeAsync(dialogContext.Context, cancellationToken);
                            var topScoringIntent = luisResults?.GetTopScoringIntent();

                            var topIntent = this.Intents.FirstOrDefault(i => i.Id == topScoringIntent.Value.intent);

                            if (topIntent == null)
                            {
                                await dialogContext.Context.SendActivityAsync(MessageConstants.MessageNotUnderstood);
                            }
                            else
                            {
                                var parsedEntities = this.ParseEntities(luisResults);
                                await dialogContext.BeginDialogAsync(topIntent.DialogId, parsedEntities);
                            }

                            break;

                        case DialogTurnStatus.Waiting:
                            // The active dialog is waiting for a response from the user, so do nothing.
                            break;

                        case DialogTurnStatus.Complete:
                        default:
                            await dialogContext.CancelAllDialogsAsync();

                            break;
                        }
                    }
                }
                else if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    if (activity.MembersAdded != null)
                    {
                        // Iterate over all new members added to the conversation.
                        foreach (var member in activity.MembersAdded)
                        {
                            // Greet anyone that was not the target (recipient) of this message.
                            if (member.Id != activity.Recipient.Id)
                            {
                                var userTokens = await this.stateBotAccessors.UserTokensAccessor.GetAsync(turnContext, () => new TokensModel());

                                if (userTokens.IsAuthenticated)
                                {
                                    // Send options for what the bot can do through adaptive cards for example
                                }
                                else
                                {
                                    await dialogContext.BeginDialogAsync(nameof(LoginDialog));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await dialogContext.CancelAllDialogsAsync();

                await turnContext.SendActivityAsync(ex.Message);
            }

            await conversationState.SaveChangesAsync(turnContext);

            await userState.SaveChangesAsync(turnContext);
        }
Esempio n. 12
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            if (activity.Text == null && activity.Value != null)
            {
                turnContext.Activity.Text = turnContext.Activity.Value.ToString();
            }
            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                var          utterance = turnContext.Activity.Text;
                UtteranceLog logItems  = null;

                // see if there are previous messages saved in sstorage.
                string[] utteranceList = { "UtteranceLog" };

                //logItems = _myStorage.ReadAsync<UtteranceLog>(utteranceList).Result?.FirstOrDefault().Value;

                // If no stored messages were found, create and store a new entry.
                if (logItems is null)
                {
                    logItems = new UtteranceLog();
                }

                // add new message to list of messages to display.
                logItems.UtteranceList.Add(utterance);
                // increment turn counter.
                logItems.TurnNumber++;

                var changes = new Dictionary <string, object>();

                // show user new list of saved messages.
                //await turnContext.SendActivityAsync($"The list is now: {string.Join(", ", logItems.UtteranceList)}");

                // Create Dictionary object to hold new list of messages.

                {
                    changes.Add("UtteranceLog", logItems);
                };

                // Save new list to your Storage.
                await _myStorage.WriteAsync(changes, cancellationToken);

                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                //await UpdateGreetingState(luisResults, dc.Context);
                await UpdateMedicState(luisResults, dc.Context);


                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(MedicDialog));

                            break;

                        case MedicIntent:
                            await dc.BeginDialogAsync(nameof(MedicDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded.Any())
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response).ConfigureAwait(false);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 13
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Remove the bot mention to avoid issues with LUIS's NLP
                dc.Context.Activity.RemoveRecipientMention();

                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                // await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // for testing to view list of jobs. TODO: clean up
                var text = turnContext.Activity.Text.Trim().ToLowerInvariant();
                switch (text)
                {
                case "show":
                case "show jobs":
                    await _jobService.ListJobs(turnContext);

                    break;

                default:
                    break;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.Context.SendActivityAsync("Hello, this is Niles, your DevOps ChatBot assistant");

                            break;

                        case CreateIssueIntent:
                            await dc.BeginDialogAsync(nameof(CreateIssueDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");
                            await DisplayHelp(dc.Context);

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Debugging purposes. Remove Later
                await dc.Context.SendActivityAsync("Conversation Update occured");

                if (activity.MembersAdded.Any())
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Debugging purposes. Remove Later
                        await dc.Context.SendActivityAsync($"Member joined {member.Name} with id: {member.Id}");

                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment(@".\Dialogs\Welcome\Resources\welcomeCard.json");
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response).ConfigureAwait(false);
                        }
                        else
                        {
                            await dc.Context.SendActivityAsync($"Thanks for adding Niles. Type anything to get started.");

                            // save conversation channel
                            await _notificationService.StartChannel(turnContext);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 14
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Recognize what the user said.
                var topIntent = await GreetingHelpCancelRecognizer(turnContext, cancellationToken);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
Esempio n. 15
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Checks if status is currently inside QnA Maker multi turn situation
                if (InQnaMaker)
                {
                    var qnaResponse = await this.GetQnAResponse(activity.Text, turnContext);

                    await turnContext.SendActivityAsync(qnaResponse);

                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Perform a call to LUIS to retrieve results for the current activity message.
                // Until LUIS API v3 is integrated, we will call the v3 endpoint directly using a created service
                var luisResults = await luisServiceV3.PredictLUIS(turnContext.Activity.Text, dc.Context);

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // loop through all the LUIS predictions, these can be single or multiple if multi-intent is enabled
                    foreach (var response in luisResults)
                    {
                        var topIntent = response.Intent;

                        // examine results from active dialog
                        switch (dialogResult.Status)
                        {
                        case DialogTurnStatus.Empty:
                            switch (topIntent)
                            {
                            case PurchaseTicket:
                                var purchaseTicketResponse = laLigaBL.PurchaseTicket(response);
                                await turnContext.SendActivityAsync(CardHelper.GetLUISHeroCard(purchaseTicketResponse, LaLigaBL.PictureType.Ticket));

                                break;

                            case FindMatchIntent:
                                var findMatchResponse = laLigaBL.FindMatch(response);
                                await turnContext.SendActivityAsync(CardHelper.GetLUISHeroCard(findMatchResponse.ResponseText, findMatchResponse.PictureType));

                                break;

                            // Redirect to QnA if None intent is detected
                            case NoneIntent:
                            default:
                                var qnaResponse = await GetQnAResponse(activity.Text, turnContext);

                                await turnContext.SendActivityAsync(qnaResponse);

                                InQnaMaker = true;
                                break;
                            }

                            break;

                        case DialogTurnStatus.Waiting:
                            // The active dialog is waiting for a response from the user, so do nothing.
                            break;

                        case DialogTurnStatus.Complete:
                            await dc.EndDialogAsync();

                            break;

                        default:
                            await dc.CancelAllDialogsAsync();

                            break;
                        }
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
                InQnaMaker = false; // Reset QnA Maker
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            if (activity.Type == ActivityTypes.Message)
            {
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(turnContext, cancellationToken).ConfigureAwait(false);

                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;
                switch (topIntent)
                {
                case GreetingIntent:
                    await turnContext.SendActivityAsync("Hello.");

                    break;

                case HelpIntent:
                    await turnContext.SendActivityAsync("Let me try to provide some help.");

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

                    break;

                case CancelIntent:
                    await turnContext.SendActivityAsync("I have nothing to cancel.");

                    break;

                case ReservationIntent:
                    await turnContext.SendActivityAsync("Reservation intent found, JSON response: " + luisResults?.Entities.ToString());

                    break;

                case NoneIntent:
                default:
                    // Help or no intent identified, either way, let's provide some help.
                    // to the user
                    await turnContext.SendActivityAsync("I didn't understand what you just said to me.");

                    break;
                }
            }

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(turnContext, cancellationToken).ConfigureAwait(false);

                (string intent, double score)? topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;
                switch (topIntent)
                {
                case GreetingIntent:
                    await turnContext.SendActivityAsync("Hello.");

                    break;

                case HelpIntent:
                    await turnContext.SendActivityAsync("Let me try to provide some help.");

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

                    break;

                case CancelIntent:
                    await turnContext.SendActivityAsync("I have nothing to cancel.");

                    break;

                case ReservationIntent:

                    await turnContext.SendActivityAsync("What time do you set your reservation");

                    break;

                case NoneIntent:
                default:
                    // Help or no intent identified, either way, let's provide some help.
                    // to the user
                    await turnContext.SendActivityAsync("I didn't understand what you just said to me.");

                    break;
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await turnContext.SendActivityAsync(response).ConfigureAwait(false);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 17
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // if an image was passed we ignorr all other input and start the cognitive service to recognize the image's contents
                if (activity.Attachments != null && activity.Attachments.Count > 0)
                {
                    var attachmentURL = activity.Attachments[0].ContentUrl;

                    var result = await SendImageToBeAnalyzedAndReturnDescription(attachmentURL);

                    await turnContext.SendActivityAsync(result);

                    return;
                }

                if (activity.Text.Contains("SpellCheck") || activity.Text.Contains("Spelling"))
                {
                    var text = activity.Text;
                    HttpRequestMessage msg = new HttpRequestMessage();
                    msg.Headers.Add("Ocp-Apim-Subscription-Key", _configuration.GetValue <string>("bingSpellCheckKey"));
                    var dic = new Dictionary <string, string>();
                    text           = text.Split("SpellCheck")[1];
                    dic["Text"]    = text;
                    msg.Content    = new FormUrlEncodedContent(dic);
                    msg.RequestUri = new Uri("https://api.cognitive.microsoft.com/bing/v7.0/spellcheck/?mode=spell");
                    msg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    msg.Method = HttpMethod.Post;
                    var result = await _client.SendAsync(msg);

                    var returnObject = JsonConvert.DeserializeObject <SpellCheckModel>(await result.Content.ReadAsStringAsync());

                    // if No correction was found we return
                    if (returnObject.FlaggedTokens.Length == 0)
                    {
                        await turnContext.SendActivityAsync("Sorry coud not find any suggestions for you!");

                        return;
                    }

                    var bestResult = returnObject.FlaggedTokens[0].Suggestions[0]?.Correction;
                    await turnContext.SendActivityAsync("Did you mean: " + bestResult + "?");

                    return;
                }

                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded.Any())
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response).ConfigureAwait(false);
                        }
                    }
                }
            }


            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 18
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case SayHello:
                            await dc.BeginDialogAsync(nameof(GreetingDialog));

                            break;

                        case TellAuthorsBooks:
                            var ent = luisResults.Entities["AuthorName"];
                            if (ent != null)
                            {
                                var author    = ent.First().ToString();
                                var message   = string.Empty;
                                var solutions = _prologEngine.GetAllSolutions(null, $"book(B, \"{author}\", _, _).");
                                if (solutions.Success)
                                {
                                    message += $"{author} wrote such books: ";
                                    foreach (Solution s in solutions.NextSolution)
                                    {
                                        foreach (Variable v in s.NextVariable)
                                        {
                                            if (v.Type != "namedvar")
                                            {
                                                message += $"\n {v.Value}";
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    message = "This author is missing in the database. Please, connect bot to Internet.";
                                }

                                await turnContext.SendActivityAsync(message);
                            }
                            else
                            {
                                await turnContext.SendActivityAsync("This author is missing in the database. Please, connect bot to Internet.");
                            }
                            break;

                        case AskToRecommendBook:
                            luisResults.Entities.TryGetValue("Genre", out var genre);
                            await turnContext.SendActivityAsync(_prologBookService.RecommendBook(genre?.First().First().ToString()));

                            break;

                        case RecommendBookByPreference:
                            luisResults.Entities.TryGetValue("UserName", out var username);
                            await turnContext.SendActivityAsync(_prologBookService.RecommendBookByPreference(username.First().ToString()));

                            break;

                        case TellAuthorOfSpecificBook:
                            var bookname   = luisResults.Entities["BookName"].First().ToString().Trim('\'');
                            var authorname = _prologBookService.GetAuthorOfTheBookName(bookname);
                            var response   = string.IsNullOrEmpty(authorname)
                                        ? "There is no such book in the database. \n Please, connect bot to the Internet."
                                        : $"{authorname} wrote book {bookname}";
                            await turnContext.SendActivityAsync(response);

                            break;

                        case TellGenresOfBooks:
                            var bookGenresMessage = "These are different book genres: ";
                            var genres            = _prologEngine.GetAllSolutions(null, $"genre(G).");
                            if (genres.Success)
                            {
                                foreach (Solution s in genres.NextSolution)
                                {
                                    foreach (Variable v in s.NextVariable)
                                    {
                                        if (v.Type != "namedvar")
                                        {
                                            bookGenresMessage += $"\n {v.Value}";
                                        }
                                    }
                                }
                            }
                            else
                            {
                                bookGenresMessage = "Sorry, I can't tell you about book genres. Please, connect bot to Internet.";
                            }

                            await turnContext.SendActivityAsync(bookGenresMessage);

                            break;

                        case TellIfBookIsWorthReading:
                            var book = luisResults.Entities["BookName"].First().ToString().Replace('\'', '\"');
                            var bookIsWorthReading = _prologEngine.GetFirstSolution($"bookIsWorthReading({book}).");
                            if (bookIsWorthReading.Solved)
                            {
                                await turnContext.SendActivityAsync("I definitely recommend you this book! It's rate is pretty high.");
                            }
                            else
                            {
                                await turnContext.SendActivityAsync("I do not recommend you this book. Based on it's rate I can say that many people were disappointed.");
                            }

                            break;

                        case TellIfAuthorIsVeryFamous:
                            var name           = luisResults.Entities["AuthorName"].First().ToString();
                            var authorIsFamous = _prologEngine.GetFirstSolution($"authorIsWorldFamous({name}).");
                            if (authorIsFamous.Solved)
                            {
                                await turnContext.SendActivityAsync($"{name} is very famous all around the world. You should definitely get acquinted with his/her books.");
                            }
                            else
                            {
                                await turnContext.SendActivityAsync($"No, {name} is not very famous.");
                            }
                            break;

                        case None:
                        default:
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                if (activity.MembersAdded != null)
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment();
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Esempio n. 19
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            Activity activity = turnContext.Activity;

            // Create a dialog context
            DialogContext dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Perform a call to LUIS to retrieve results for the current activity message.
                RecognizerResult luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                (string intent, double score)? topScoringIntent = luisResults?.GetTopScoringIntent();

                string topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                await UpdateBlockchainState(luisResults, dc.Context);

                // Continue the current dialog
                DialogTurnResult dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case MarketplaceIntent:
                            await dc.BeginDialogAsync(nameof(BlockchainDialog));

                            break;

                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }