Ejemplo n.º 1
0
        /// <summary>
        /// Process result from question prompt
        /// </summary>
        /// <param name="stepContext">The context of the waterfall dialog</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="Task"/> from processing the result</returns>
        private async Task <DialogTurnResult> QuestionPromptResultAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Sends activity indicator
            await SendTypingAsync(stepContext.Context, cancellationToken);

            if (recognizer != null && recognizer.IsConfigured)
            {
                await SendTypingAsync(stepContext.Context, cancellationToken);

                CareerAdvise luisResult = await recognizer.RecognizeAsync <CareerAdvise>(stepContext.Context, cancellationToken);

                switch (luisResult.TopIntent(0.8).Intent)
                {
                case CareerAdvise.Intent.Finish:
                    // Ends the current dialog
                    return(await stepContext.EndDialogAsync());

                case CareerAdvise.Intent.CareerQuestionType:
                    switch (luisResult.Organization)
                    {
                    case Companies.Deloitte:
                    case Companies.EY:
                    case Companies.PWC:
                        // User is asking question for another organization, we end the dialog
                        return(await stepContext.EndDialogAsync(luisResult.Organization.ToString()));
                    }

                    if (luisResult.QuestionType == null)
                    {
                        stepContext.Values.Remove(QuestionType);
                    }
                    else
                    {
                        stepContext.Values[QuestionType] = luisResult.QuestionType;
                    }
                    break;
                }
            }

            string answer = null;

            if (qnaMaker != null)
            {
                QnAMakerOptions options = new QnAMakerOptions()
                {
                    Top            = 3,
                    ScoreThreshold = 0.5F,
                };

                if (stepContext.Values.ContainsKey(QuestionType))
                {
                    options.MetadataBoost = new Metadata[]
                    {
                        new Metadata()
                        {
                            Name  = "type",
                            Value = stepContext.Values[QuestionType]?.ToString(),
                        }
                    };
                }

                var response = await qnaMaker.GetAnswersAsync(stepContext.Context, options);

                if (response != null && response.Length > 0)
                {
                    answer = response[0].Answer;
                }
            }

            if (answer != null)
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(answer), cancellationToken);
            }
            else
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text(stringResource.ErrorHelpNotFound), cancellationToken);
            }

            var opts = stepContext.Values.ContainsKey(QuestionType) ? stepContext.Values[QuestionType]?.ToString() : null;

            return(await stepContext.ReplaceDialogAsync(InitialDialogId, opts, cancellationToken));
        }
Ejemplo n.º 2
0
        private async Task <DialogTurnResult> CallGenerateAnswerAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var qnaMakerOptions = new QnAMakerOptions
            {
                ScoreThreshold = DefaultThreshold,
                Top            = DefaultTopN,
                Context        = new QnARequestContext()
            };

            var dialogOptions = GetDialogOptionsValue(stepContext);

            // Getting options
            if (dialogOptions.ContainsKey(QnAOptions))
            {
                qnaMakerOptions = dialogOptions[QnAOptions] as QnAMakerOptions;
                qnaMakerOptions.ScoreThreshold = qnaMakerOptions?.ScoreThreshold ?? DefaultThreshold;
                qnaMakerOptions.Top            = DefaultTopN;
            }

            // Storing the context info
            stepContext.Values[CurrentQuery] = stepContext.Context.Activity.Text;

            // -Check if previous context is present, if yes then put it with the query
            // -Check for id if query is present in reverse index.
            if (!dialogOptions.ContainsKey(QnAContextData))
            {
                dialogOptions[QnAContextData] = new Dictionary <string, int>();
            }
            else
            {
                var previousContextData = dialogOptions[QnAContextData] as Dictionary <string, int>;
                if (dialogOptions[PreviousQnAId] != null)
                {
                    var previousQnAId = Convert.ToInt32(dialogOptions[PreviousQnAId]);

                    if (previousQnAId > 0)
                    {
                        qnaMakerOptions.Context = new QnARequestContext
                        {
                            PreviousQnAId = previousQnAId
                        };

                        if (previousContextData.TryGetValue(stepContext.Context.Activity.Text.ToLower(), out var currentQnAId))
                        {
                            qnaMakerOptions.QnAId = currentQnAId;
                        }
                    }
                }
            }

            // Calling QnAMaker to get response.
            var response = await _services.QnAMakerService.GetAnswersRawAsync(stepContext.Context, qnaMakerOptions).ConfigureAwait(false);

            // Resetting previous query.
            dialogOptions[PreviousQnAId] = -1;
            stepContext.ActiveDialog.State["options"] = dialogOptions;

            // Take this value from GetAnswerResponse
            var isActiveLearningEnabled = response.ActiveLearningEnabled;

            stepContext.Values[QnAData] = new List <QueryResult>(response.Answers);

            // Check if active learning is enabled.
            if (isActiveLearningEnabled && response.Answers.Any() && response.Answers.First().Score <= maximumScoreForLowScoreVariation)
            {
                // Get filtered list of the response that support low score variation criteria.
                response.Answers = _services.QnAMakerService.GetLowScoreVariation(response.Answers);

                if (response.Answers.Count() > 1)
                {
                    var suggestedQuestions = new List <string>();
                    foreach (var qna in response.Answers)
                    {
                        suggestedQuestions.Add(qna.Questions[0]);
                    }

                    // Get active learning suggestion card activity.
                    var qnaDialogResponseOptions = dialogOptions[QnADialogResponseOptions] as QnADialogResponseOptions;
                    var message = QnACardBuilder.GetSuggestionsCard(suggestedQuestions, qnaDialogResponseOptions.ActiveLearningCardTitle, qnaDialogResponseOptions.CardNoMatchText);
                    await stepContext.Context.SendActivityAsync(message).ConfigureAwait(false);

                    return(new DialogTurnResult(DialogTurnStatus.Waiting));
                }
            }

            var result = new List <QueryResult>();

            if (response.Answers.Any())
            {
                result.Add(response.Answers.First());
            }

            stepContext.Values[QnAData] = result;

            // If card is not shown, move to next step with top qna response.
            return(await stepContext.NextAsync(result, cancellationToken).ConfigureAwait(false));
        }
Ejemplo n.º 3
0
        private QnAMaker GetQnAMaker(HttpMessageHandler messageHandler, QnAMakerEndpoint endpoint, QnAMakerOptions options = null)
        {
            var client = new HttpClient(messageHandler);

            return(new QnAMaker(endpoint, options, client));
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Reading settings
            Settings.MicrosoftAppId       = Configuration.GetSection("MicrosoftAppId")?.Value;
            Settings.MicrosoftAppPassword = Configuration.GetSection("MicrosoftAppPassword")?.Value;

            Settings.BotConversationStorageConnectionString = Configuration.GetSection("BotConversationStorageConnectionString")?.Value;
            Settings.BotConversationStorageKey                    = Configuration.GetSection("BotConversationStorageKey")?.Value;
            Settings.BotConversationStorageDatabaseId             = Configuration.GetSection("BotConversationStorageDatabaseId")?.Value;
            Settings.BotConversationStorageUserCollection         = Configuration.GetSection("BotConversationStorageUserCollection")?.Value;
            Settings.BotConversationStorageConversationCollection = Configuration.GetSection("BotConversationStorageConversationCollection")?.Value;
            Settings.LuisAppId01               = Configuration.GetSection("LuisAppId01")?.Value;
            Settings.LuisName01                = Configuration.GetSection("LuisName01")?.Value;
            Settings.LuisAuthoringKey01        = Configuration.GetSection("LuisAuthoringKey01")?.Value;
            Settings.LuisEndpoint01            = Configuration.GetSection("LuisEndpoint01")?.Value;
            Settings.QnAKbId01                 = Configuration.GetSection("QnAKbId01")?.Value;
            Settings.QnAName01                 = Configuration.GetSection("QnAName01")?.Value;
            Settings.QnAEndpointKey01          = Configuration.GetSection("QnAEndpointKey01")?.Value;
            Settings.QnAHostname01             = Configuration.GetSection("QnAHostname01")?.Value;
            Settings.TotalBestNextAnswers      = Configuration.GetSection("TotalBestNextAnswers")?.Value;
            Settings.HighConfidenceThreshold   = Configuration.GetSection("threshold1")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.MediumConfidenceThreshold = Configuration.GetSection("threshold2")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.LowConfidenceThreshold    = Configuration.GetSection("threshold3")?.Value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
            Settings.TotalBestNextAnswers      = Configuration.GetSection("TotalBestNextAnswers")?.Value;


            // Add Application Insights services into service collection
            services.AddApplicationInsightsTelemetry();

            // Add the standard telemetry client
            services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>();

            // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items
            // This will be picked by the TelemetryBotIdInitializer
            services.AddTransient <TelemetrySaveBodyASPMiddleware>();

            // Add telemetry initializer that will set the correlation context for all telemetry items
            services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>();

            // Add telemetry initializer that sets the user ID and session ID (in addition to other
            // bot-specific properties, such as activity ID)
            services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>();

            // Adding storage
            CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageUserCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions
            {
                AuthKey          = Settings.BotConversationStorageKey,
                CollectionId     = Settings.BotConversationStorageConversationCollection,
                CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString),
                DatabaseId       = Settings.BotConversationStorageDatabaseId,
            });

            var userState         = new UserState(userstorage);
            var conversationState = new ConversationState(conversationstorage);

            services.AddSingleton(userState);
            services.AddSingleton(conversationState);


            // Adding MVC compatibility
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Adding the credential provider to be used with the Bot Framework Adapter
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();

            // Adding the channel provider to be used with the Bot Framework Adapter
            services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>();

            // Adding the Bot Framework Adapter with error handling enabled
            services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

            // Adding middlewares
            services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState));
            services.AddSingleton(new ShowTypingMiddleware());

            // Adding accessors
            services.AddSingleton(sp =>
            {
                // We need to grab the conversationState we added on the options in the previous step
                var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value;
                if (options == null)
                {
                    throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors");
                }

                var luisServices = new Dictionary <string, LuisRecognizer>();
                var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
                var recognizer   = new LuisRecognizer(app);
                luisServices.Add(Settings.LuisName01, recognizer);

                var qnaEndpoint = new QnAMakerEndpoint()
                {
                    KnowledgeBaseId = Settings.QnAKbId01,
                    EndpointKey     = Settings.QnAEndpointKey01,
                    Host            = Settings.QnAHostname01,
                };

                var qnaOptions = new QnAMakerOptions
                {
                    ScoreThreshold = 0.3F
                };

                var qnaServices = new Dictionary <string, QnAMaker>();
                var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);
                qnaServices.Add(Settings.QnAName01, qnaMaker);

                // Create the custom state accessor.
                // State accessors enable other components to read and write individual properties of state.
                var accessors = new BotAccessors(loggerFactory, conversationState, userState, luisServices, qnaServices)
                {
                    ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                    LastSearchPreference      = userState.CreateProperty <string>("LastSearchPreference"),
                    LastAnswerPreference      = userState.CreateProperty <string>("LastAnswerPreference"),
                    IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAu`thenticatedPreference")
                };

                return(accessors);
            });

            services.AddTransient <IBot, BotAppBot>();
        }
Ejemplo n.º 5
0
        private async Task <DialogTurnResult> CallGenerateAnswerAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var qnaMakerOptions = new QnAMakerOptions
            {
                ScoreThreshold = DefaultThreshold,
                Top            = DefaultTopN,
                Context        = new QnARequestContext(),
                QnAId          = 0
            };

            var dialogOptions = GetDialogOptionsValue(stepContext);

            // Getting options
            if (dialogOptions.ContainsKey(QnAOptions))
            {
                qnaMakerOptions = dialogOptions[QnAOptions] as QnAMakerOptions;
                qnaMakerOptions.ScoreThreshold = qnaMakerOptions?.ScoreThreshold ?? DefaultThreshold;
                qnaMakerOptions.Top            = DefaultTopN;
            }

            // Storing the context info
            stepContext.Values[CurrentQuery] = stepContext.Context.Activity.Text;

            // -Check if previous context is present, if yes then put it with the query
            // -Check for id if query is present in reverse index.
            if (!dialogOptions.ContainsKey(QnAContextData))
            {
                dialogOptions[QnAContextData] = new Dictionary <string, int>();
            }
            else
            {
                var previousContextData = dialogOptions[QnAContextData] as Dictionary <string, int>;
                if (dialogOptions[PreviousQnAId] != null)
                {
                    var previousQnAId = Convert.ToInt32(dialogOptions[PreviousQnAId]);

                    if (previousQnAId > 0)
                    {
                        qnaMakerOptions.Context = new QnARequestContext
                        {
                            PreviousQnAId = previousQnAId
                        };

                        qnaMakerOptions.QnAId = 0;
                        if (previousContextData.TryGetValue(stepContext.Context.Activity.Text.ToLower(), out var currentQnAId))
                        {
                            qnaMakerOptions.QnAId = currentQnAId;
                        }
                    }
                }
            }

            // Calling QnAMaker to get response.
            var response = await _qnaService.GetAnswersRawAsync(stepContext.Context, qnaMakerOptions).ConfigureAwait(false);

            // Resetting previous query.
            dialogOptions[PreviousQnAId] = -1;
            stepContext.ActiveDialog.State["options"] = dialogOptions;

            stepContext.Values[QnAData] = new List <QueryResult>(response.Answers);

            var result = new List <QueryResult>();

            if (response.Answers.Any())
            {
                result.Add(response.Answers.First());
            }

            stepContext.Values[QnAData] = result;

            // If card is not shown, move to next step with top qna response.
            return(await stepContext.NextAsync(result, cancellationToken).ConfigureAwait(false));
        }
        public async void AskForATopicSampleTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            var luisServices = new Dictionary <string, LuisRecognizer>();
            var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
            var recognizer   = new LuisRecognizer(app);

            luisServices.Add(Settings.LuisName01, recognizer);

            var qnaEndpoint = new QnAMakerEndpoint()
            {
                KnowledgeBaseId = Settings.QnAKbId01,
                EndpointKey     = Settings.QnAEndpointKey01,
                Host            = Settings.QnAHostname01,
            };

            var qnaOptions = new QnAMakerOptions
            {
                ScoreThreshold = 0.3F
            };

            var qnaServices = new Dictionary <string, QnAMaker>();
            var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);

            qnaServices.Add(Settings.QnAName01, qnaMaker);

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState, luisServices, qnaServices)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                NamePreference            = userState.CreateProperty <string>("NamePreference"),
                LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            List <MediaUrl> mediaList = new List <MediaUrl>();

            mediaList.Add(new MediaUrl("https://www.youtube.com/watch?v=CmTSY9oO3dw"));

            VideoCard videoCard = new VideoCard
            {
                Title     = "Interview Sample",
                Text      = "Each interview takes on a life of its own, but there are certain standard questions that arise. By reviewing them in advance, you can arrive confident and ready to articulate your skills and qualifications. Take a look at the sample questions here, and then bolster them with those specific to your goals and the organization. Both your answers to the interviewer's questions and those you post to them can provide a mechanism by which to communicate your qualifications.",
                Autostart = false,
                Media     = mediaList
            };

            Activity activity = new Activity
            {
                Type        = ActivityTypes.Message,
                Attachments = new List <Attachment> {
                    videoCard.ToAttachment()
                }
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("i would like to see a sample about the considerations for a human resources interview")
            .AssertReply((ac) =>
            {
                if (ac.AsMessageActivity().Attachments != null)
                {
                    var contentType = ac.AsMessageActivity().Attachments[0].ContentType;
                    Assert.Equal("application/vnd.microsoft.card.video", contentType);
                }
                else
                {
                    Assert.NotNull(ac.AsMessageActivity().Attachments);
                }
            })
            .StartTestAsync();
        }
        public async Task <(MultiturnQnAState newState, IEnumerable <Activity> output)> GetAnswersAsync(MultiturnQnAState oldState, ITurnContext turnContext, QnAMakerOptions options, Dictionary <string, string> telemetryProperties, Dictionary <string, double> telemetryMetrics = null)
        {
            Activity          outputActivity = null;
            MultiturnQnAState newState       = null;

            var query     = turnContext.Activity.Text;
            var qnaResult = await QueryQnAServiceAsync(query, oldState);

            var qnaAnswer = qnaResult[0].Answer;
            var prompts   = qnaResult[0].Context?.Prompts;

            if (prompts == null || prompts.Length < 1)
            {
                outputActivity = MessageFactory.Text(qnaAnswer);
            }
            else
            {
                // Set bot state only if prompts are found in QnA result
                newState = new MultiturnQnAState
                {
                    PreviousQnaId     = qnaResult[0].Id,
                    PreviousUserQuery = query
                };

                outputActivity = CardHelper.GetHeroCard(qnaAnswer, prompts);
            }

            return(newState, new Activity[] { outputActivity });
Ejemplo n.º 8
0
        private async Task AnswerPOQnA(ITurnContext <IMessageActivity> turnContext, LuisResult luisResult, CancellationToken cancellationToken)
        {
            var card = new AdaptiveCards.AdaptiveCard(new AdaptiveSchemaVersion(1, 0));

            //var pictureUrl = "";

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text = "Purchase Order Help"
            });

            //card.Body.Add(new AdaptiveImage()
            //{
            //    Type = "Image",
            //    Url = new Uri(pictureUrl),
            //    Size = AdaptiveImageSize.Medium
            //});

            card.Body.Add(new AdaptiveTextBlock()
            {
                Text  = "Thank you, hope this helps...",
                Color = AdaptiveTextColor.Accent
            });

            var options = new QnAMakerOptions {
                Top = 1
            };
            var response = await myBotServices.POHowToQnA.GetAnswersAsync(turnContext, options);

            if (response != null && response.Length > 0)
            {
                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text  = response[0].Answer,
                    Color = AdaptiveTextColor.Accent
                });

                Attachment attach = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card
                };

                var msg = MessageFactory.Attachment(new Attachment
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card
                });

                await turnContext.SendActivityAsync(msg, cancellationToken);
            }
            else
            {
                await turnContext.SendActivityAsync(MessageFactory.Text("No anwers found from KB"), cancellationToken);
            }

            //Attachment attach = new Attachment()
            //{
            //    ContentType = AdaptiveCard.ContentType,
            //    Content = card
            //};

            //var options = new QnAMakerOptions { Top = 1 };
            //var response = await myBotServices.POHowToQnA.GetAnswersAsync(turnContext, options);

            //if (response != null && response.Length > 0)
            //{
            //    await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
            //}
            //else
            //{
            //    await turnContext.SendActivityAsync(MessageFactory.Text("No anwers found from KB"), cancellationToken);
            //}
        }
 public async Task <QueryResult[]> GetAnswersAsync(ITurnContext turnContext, QnAMakerOptions options = null)
 {
     return(await _maker.GetAnswersAsync(turnContext));
 }
Ejemplo n.º 10
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var welcomeUserStateAccessor = UserState.CreateProperty <WelcomeUserState>(nameof(WelcomeUserState));
            var didBotWelcomeUser        = await welcomeUserStateAccessor.GetAsync(turnContext, () => new WelcomeUserState());

            var options = new QnAMakerOptions {
                Top = 1
            };

            var text = "";

            if (turnContext.Activity.Text == null)
            {
                text = "null";
            }
            else
            {
                text = turnContext.Activity.Text.ToLowerInvariant();
            }
            switch (text)
            {
            case "intro":
            case "help":
                await SendIntroCardAsync(turnContext, cancellationToken);

                break;

            case "file an incident":
                await turnContext.SendActivityAsync(MessageFactory.Attachment(CreateAdaptiveCardAttachment()));

                break;

            case "null":
                if (turnContext.Activity.Value != null)
                {
                    var ticket     = JsonConvert.SerializeObject(turnContext.Activity.Value);
                    var ticket_num = 123456789;

                    JObject jObject = JObject.Parse(ticket);

                    string t_date    = (string)jObject.SelectToken("dateinput");
                    string t_name    = (string)jObject.SelectToken("nameinput");
                    string t_issue   = (string)jObject.SelectToken("issueinput");
                    string t_urgency = "";
                    if ((int)jObject.SelectToken("urgencyinput") == 1)
                    {
                        t_urgency = "Normal";
                    }
                    else
                    {
                        t_urgency = "Urgent";
                    }

                    try {
                        string resourceId = "https://graph.microsoft.com/";
                        string authString = "https://login.microsoftonline.com/" + "8ad25bda-a157-4eda-a940-b1069931e221";
                        //secret - BO.7~0daznFl84x-3B0_79X9OMMpwH.UYM
                        //tenant id- 8ad25bda-a157-4eda-a940-b1069931e221
                        //app id - e6679829-27ac-4d4e-ae24-f752ab77755a

                        var authenticationContext = new AuthenticationContext(authString, false);
                        IdentityModel.Clients.ActiveDirectory.ClientCredential     clientCred           = new IdentityModel.Clients.ActiveDirectory.ClientCredential("e6679829-27ac-4d4e-ae24-f752ab77755a", "BO.7~0daznFl84x-3B0_79X9OMMpwH.UYM");
                        IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, clientCred);

                        var acc = "eyJ0eXAiOiJKV1QiLCJub25jZSI6Ijg1SEkzRE5Ob3ZERDFRb2dhcDdQaEczTk1qTVJhbUlXZEoxWTNsWjltZEEiLCJhbGciOiJSUzI1NiIsIng1dCI6IlNzWnNCTmhaY0YzUTlTNHRycFFCVEJ5TlJSSSIsImtpZCI6IlNzWnNCTmhaY0YzUTlTNHRycFFCVEJ5TlJSSSJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC82NTgzNjM2Yi1kMTU2LTQ5MmUtODZjZS1iOGZjY2I3OTBkZjEvIiwiaWF0IjoxNTkxOTc4NzAxLCJuYmYiOjE1OTE5Nzg3MDEsImV4cCI6MTU5MTk4MjYwMSwiYWNjdCI6MCwiYWNyIjoiMSIsImFpbyI6IjQyZGdZTkR5NkM2YVdkWDMrOGJFNjJ0U0h3bTJSYmIyMWt6VDJ0UjU4ck1NWXlxVFpBSUEiLCJhbXIiOlsicHdkIl0sImFwcF9kaXNwbGF5bmFtZSI6IkdyYXBoIGV4cGxvcmVyIiwiYXBwaWQiOiJkZThiYzhiNS1kOWY5LTQ4YjEtYThhZC1iNzQ4ZGE3MjUwNjQiLCJhcHBpZGFjciI6IjAiLCJmYW1pbHlfbmFtZSI6IkthcmRhIiwiZ2l2ZW5fbmFtZSI6IlVkZGVzaCIsImlwYWRkciI6IjY4LjE4MC44Ni4yMyIsIm5hbWUiOiJVZGRlc2ggS2FyZGEiLCJvaWQiOiI2NWI5NmZkNS1hNTcxLTQ3MTktODlkMC0wMmQ1ZDA3M2Y5MTIiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzIwMDBCRTYyM0FCMSIsInNjcCI6IkFjY2Vzc1Jldmlldy5SZWFkLkFsbCBBY2Nlc3NSZXZpZXcuUmVhZFdyaXRlLkFsbCBDYWxlbmRhcnMuUmVhZFdyaXRlIENvbnRhY3RzLlJlYWRXcml0ZSBEZXZpY2VNYW5hZ2VtZW50QXBwcy5SZWFkLkFsbCBEZXZpY2VNYW5hZ2VtZW50QXBwcy5SZWFkV3JpdGUuQWxsIERldmljZU1hbmFnZW1lbnRDb25maWd1cmF0aW9uLlJlYWQuQWxsIERldmljZU1hbmFnZW1lbnRDb25maWd1cmF0aW9uLlJlYWRXcml0ZS5BbGwgRGV2aWNlTWFuYWdlbWVudE1hbmFnZWREZXZpY2VzLlByaXZpbGVnZWRPcGVyYXRpb25zLkFsbCBEZXZpY2VNYW5hZ2VtZW50TWFuYWdlZERldmljZXMuUmVhZC5BbGwgRGV2aWNlTWFuYWdlbWVudE1hbmFnZWREZXZpY2VzLlJlYWRXcml0ZS5BbGwgRGV2aWNlTWFuYWdlbWVudFJCQUMuUmVhZC5BbGwgRGV2aWNlTWFuYWdlbWVudFJCQUMuUmVhZFdyaXRlLkFsbCBEZXZpY2VNYW5hZ2VtZW50U2VydmljZUNvbmZpZy5SZWFkLkFsbCBEZXZpY2VNYW5hZ2VtZW50U2VydmljZUNvbmZpZy5SZWFkV3JpdGUuQWxsIERpcmVjdG9yeS5BY2Nlc3NBc1VzZXIuQWxsIERpcmVjdG9yeS5SZWFkLkFsbCBEaXJlY3RvcnkuUmVhZFdyaXRlLkFsbCBGaWxlcy5SZWFkV3JpdGUuQWxsIEdyb3VwLlJlYWRXcml0ZS5BbGwgSWRlbnRpdHlSaXNrRXZlbnQuUmVhZC5BbGwgTWFpbC5SZWFkV3JpdGUgTWFpbC5TZW5kIE1haWxib3hTZXR0aW5ncy5SZWFkV3JpdGUgTm90ZXMuUmVhZFdyaXRlLkFsbCBvcGVuaWQgUGVvcGxlLlJlYWQgcHJvZmlsZSBSZXBvcnRzLlJlYWQuQWxsIFNpdGVzLlJlYWRXcml0ZS5BbGwgVGFza3MuUmVhZFdyaXRlIFVzZXIuUmVhZCBVc2VyLlJlYWRCYXNpYy5BbGwgVXNlci5SZWFkV3JpdGUgVXNlci5SZWFkV3JpdGUuQWxsIGVtYWlsIiwic2lnbmluX3N0YXRlIjpbImttc2kiXSwic3ViIjoiZUFpZUNLaF9TNEhUcXMwUDVWa2FXVURKRE0wY05DSVJWV3QtRVM1dVFZayIsInRlbmFudF9yZWdpb25fc2NvcGUiOiJOQSIsInRpZCI6IjY1ODM2MzZiLWQxNTYtNDkyZS04NmNlLWI4ZmNjYjc5MGRmMSIsInVuaXF1ZV9uYW1lIjoidWRkZXNoQGN5Y2xvdHJvbmdyb3VwLmNvbSIsInVwbiI6InVkZGVzaEBjeWNsb3Ryb25ncm91cC5jb20iLCJ1dGkiOiIwU3IwYTNjc3pVV2Nockg2V0VjN0FBIiwidmVyIjoiMS4wIiwieG1zX3N0Ijp7InN1YiI6IkN4UWtzeV9DMXVVaUtlRGNkMmVzT0pIeHh2b20xMU5UektrOXI4SzJlWlUifSwieG1zX3RjZHQiOjE0MTgwNjc3Njl9.FPDziisnCX9KHEpLTslWYFN6bLYI6GyUjMecZL9ZKdT-mcCPMFsVcsFcl2qQnXcnKxLeKl4LZexLFD-wlk5a7rJCNhrp92k3guxrLmFXF0z398ksu_QcP1lc0na___WQOjOB4wmB1ak-1-6nAvedjSQfSV6RwCGFRCpkYLQIR6BsjN3agE9h88ik9covtAi-QYQNgooqaxF4OmjJWGv-6QvijhtrLMZXsoU2ev3giQ0bwsHmqN4gp3Amc1S7gFoTgCR4qIjncOUxZ_KBdQA22M09U3t-SMAiYKAvHV_EMxA8yPtVKTh5bVd_tf-obuad4hTgRmS2clmWYom1TjIocA";
                        GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                                                    (requestMessage) => {
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", acc);
                            return(Task.FromResult(0));
                        }));

                        AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0))
                        {
                            Body = new List <AdaptiveElement>()
                            {
                                new AdaptiveContainer
                                {
                                    Items = new List <AdaptiveElement>()
                                    {
                                        new AdaptiveColumnSet()
                                        {
                                            Columns = new List <AdaptiveColumn>()
                                            {
                                                new AdaptiveColumn {
                                                    Width = AdaptiveColumnWidth.Auto,
                                                    Items = new List <AdaptiveElement>()
                                                    {
                                                        new AdaptiveTextBlock {
                                                            Text = "Ticket Date " + t_date,
                                                            Size = AdaptiveTextSize.Small,
                                                        },
                                                        new AdaptiveTextBlock {
                                                            Text = "Ticket By " + t_name,
                                                            Size = AdaptiveTextSize.Small
                                                        },
                                                        new AdaptiveTextBlock {
                                                            Text = "Issue : " + t_issue,
                                                            Size = AdaptiveTextSize.Small
                                                        },
                                                        new AdaptiveTextBlock {
                                                            Text = "Assistance urgency : " + t_urgency,
                                                            Size = AdaptiveTextSize.Small
                                                        },
                                                        new AdaptiveTextBlock {
                                                            Text = "Ticket number : " + ticket_num,
                                                            Size = AdaptiveTextSize.Small
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            Actions = new List <AdaptiveAction>()
                            {
                                new AdaptiveSubmitAction
                                {
                                    Title = "Resolved",
                                    Id    = "resolvedticket",
                                    Data  = new AdaptiveShowCardAction {
                                    }
                                }
                            }
                        };

                        string  cardstr  = card.ToJson();
                        JObject cardobj  = JObject.Parse(cardstr);
                        var     cardType = "application/adaptivecard+json";
                        //cardobj.SelectToken("type");
                        var content = string.Format(File.ReadAllText(@".\Message.html"), cardType, cardobj.ToString());

                        var message = new Message
                        {
                            Subject = "Ticket request",
                            Body    = new ItemBody
                            {
                                ContentType = BodyType.Html,
                                Content     = content
                            },

                            Attachments = new MessageAttachmentsCollectionPage(),

                            ToRecipients = new List <Recipient>()
                            {
                                new Recipient
                                {
                                    EmailAddress = new EmailAddress
                                    {
                                        Address = "*****@*****.**"
                                    }
                                }
                            }
                        };
                        await graphClient.Users["*****@*****.**"]
                        .SendMail(message, null)
                        .Request()
                        .PostAsync();
                    }
                    catch (MsalException)
                    {
                        await turnContext.SendActivityAsync($"broken");
                    }
                }
                else
                {
                    await turnContext.SendActivityAsync($"No Input");
                }
                break;

            case "thank you":
            case "bye":
                await turnContext.SendActivityAsync($"Bye");

                break;

            default:
                var qnaMaker = _services.QnAMakerService;
                var response = await qnaMaker.GetAnswersAsync(turnContext, options);

                string[] split_response = (response[0].Answer).Split(';');
                if (split_response.Length > 1)
                {
                    var card = new HeroCard();
                    card.Title = split_response[0];
                    card.Text  = split_response[1];
                    if (split_response.Length == 3)
                    {
                        card.Buttons = new List <CardAction>()
                        {
                            new CardAction(ActionTypes.OpenUrl, split_response[0], null, split_response[0], split_response[0], split_response[2]),
                        };
                    }
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(card.ToAttachment()));
                }
                else
                {
                    await turnContext.SendActivityAsync(split_response[0]);
                }

                break;
            }
            await UserState.SaveChangesAsync(turnContext);
        }
Ejemplo n.º 11
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Value == null)
            {
                var typing = new Activity()
                {
                    Type = ActivityTypes.Typing, Text = null, Value = null
                };
                await turnContext.SendActivityAsync(typing);


                var httpClient = _httpClientFactory.CreateClient();

                var qnaMaker = new QnAMaker(new QnAMakerEndpoint
                {
                    KnowledgeBaseId = "4368eb8d-e200-4e81-a301-31aa12e58de0",
                    Host            = "https://qnamakerinstapp.azurewebsites.net/qnamaker",
                    EndpointKey     = "e4bd7921-d6bc-4005-89ec-ae7a558a4da2"
                },
                                            null,
                                            httpClient);;
                /////////////////// ******* USING TEST KB!!!!! CHANGE BEFORE DEPLOYMENT & Change email adress to sales *********** //////////////
                _logger.LogInformation("Calling QnA Maker");

                var options = new QnAMakerOptions {
                    Top = 1
                };
                // Returns no accurate answer found on any questions below 70 score
                options.ScoreThreshold = 0.6F;



                // The actual call to the QnA Maker service.
                var response = await qnaMaker.GetAnswersAsync(turnContext, options);



                if (response != null && response.Length > 0)
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);

                    if (Convert.ToString(turnContext.Activity.Text).Contains("Insurance") ^ Convert.ToString(turnContext.Activity.Text).Contains("insurance"))
                    {
                        if (Convert.ToString(turnContext.Activity.Text).Contains("NIC") ^ Convert.ToString(turnContext.Activity.Text).Contains("nic") ^ Convert.ToString(turnContext.Activity.Text).Contains("national") ^ Convert.ToString(turnContext.Activity.Text).Contains("National"))
                        {
                        }
                        else
                        {
                            var _InsuranceCard = ((Activity)turnContext.Activity).CreateReply();
                            _InsuranceCard.Attachments = new List <Microsoft.Bot.Schema.Attachment>()
                            {
                                InsuranceCard()
                            };
                            await turnContext.SendActivityAsync(_InsuranceCard);
                        }
                    }



                    //offer 'ddi this answer your question'
                    if (turnContext.Activity.Text.Length > 10)
                    {
                        // var reply = ((Activity)turnContext.Activity).CreateReply();
                        // reply.Attachments = new List<Microsoft.Bot.Schema.Attachment>() { YesNoCard() };
                        // await turnContext.SendActivityAsync(reply);
                        var finalmsg = "We hope this has answered your question. If it hasn't, let us know at [email protected]. Otherwise, feel free to ask another question.";

                        await turnContext.SendActivityAsync(finalmsg);
                    }
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, my AI engine can't process that question. Please re-phrase your question and try again. Thank you for your patience!"), cancellationToken);
                }
            }
            else // value contains JSON result of card entries
            {
                var jobj = JObject.Parse(turnContext.Activity.Value.ToString());

                if (jobj.ContainsKey("YesNo"))
                {
                    var reply = (string)jobj["YesNo"];


                    try
                    {
                        if (reply == "yes" ^ reply == "yeah" ^ reply == "yep" ^ reply == "ye" ^ reply == "y" ^ reply == "Yes")
                        {
                            string success = "We are glad to be of help. Please continue to ask another question or check out the other features on our website";
                            await turnContext.SendActivityAsync(success);
                        }
                        else if (reply == "no" ^ reply == "on" ^ reply == "narp" ^ reply == "nah" ^ reply == "nope" ^ reply == "noo" ^ reply == "No")
                        {
                            var reply_ = ((Activity)turnContext.Activity).CreateReply();
                            reply_.Attachments = new List <Microsoft.Bot.Schema.Attachment>()
                            {
                                wrongAnswerCard()
                            };

                            await turnContext.SendActivityAsync(reply_);
                        }
                        else
                        {
                            string fail = "Please only enter 'yes' or 'no', or ask another question";
                            await turnContext.SendActivityAsync(fail);
                        }
                    }
                    catch
                    {
                        string fail = "Please only enter 'yes' or 'no', or ask another question";
                        await turnContext.SendActivityAsync(fail);
                    }
                }
                else if (jobj.ContainsKey("welcomeQCard"))
                {
                    var reply = (string)jobj["welcomeQCard"];


                    try
                    {
                        if (reply == "1")
                        {
                            string answer = "Employers that want to reopen their business have a legal responsibility to protect their employees and other people on site. Use this guidance to help you carry out a risk assessment and make sensible adjustments to the site and workforce. If you do not carry out a risk assessment, the Health and Safety Executive(HSE) or your local council can issue an enforcement notice. Employees can use this guidance to check what their workplace needs to do to keep people safe. This guidance is only for businesses that are allowed to reopen in England.Guidance from the Scottish Government, Welsh Government and Northern Ireland Assembly is also available. If you are in an area affected by coronavirus outbreak, check Local restrictions: areas with an outbreak of coronavirus guidance. https://www.gov.uk/coronavirus-business-reopening/y ";
                            await turnContext.SendActivityAsync(answer);
                        }
                        else if (reply == "2")
                        {
                            string answer = "The Coronavirus Job Retention Scheme will close on 31 October 2020. From 1 July, employers can bring furloughed employees back to work for any amount of time and any shift pattern, while still being able to claim CJRS grant for the hours not worked. From 1 August 2020, the level of grant will be reduced each month.To be eligible for the grant employers must pay furloughed employees 80 % of their wages, up to a cap of £2, 500 per month for the time they are being furloughed. The timetable for changes to the scheme is set out below.Wage caps are proportional to the hours an employee is furloughed. For example, an employee is entitled to 60 % of the £2, 500 cap if they are placed on furlough for 60 % of their usual hours: there are no changes to grant levels in June for June and July, the government will pay 80 % of wages up to a cap of £2, 500 for the hours the employee is on furlough, as well as employer National Insurance Contributions(ER NICS) and pension contributions for the hours the employee is on furlough. Employers will have to pay employees for the hours they work for August, the government will pay 80 % of wages up to a cap of £2, 500 for the hours an employee is on furlough and employers will pay ER NICs and pension contributions for the hours the employee is on furlough for September, the government will pay 70 % of wages up to a cap of £2, 187.50 for the hours the employee is on furlough. Employers will pay ER NICs and pension contributions and top up employees’ wages to ensure they receive 80 % of their wages up to a cap of £2, 500, for time they are furloughed for October, the government will pay 60 % of wages up to a cap of £1, 875 for the hours the employee is on furlough. Employers will pay ER NICs and pension contributions and top up employees’ wages to ensure they receive 80 % of their wages up to a cap of £2, 500, for time they are furloughed. Employers will continue to able to choose to top up employee wages above the 80 % total and £2,500 cap for the hours not worked at their own expense if they wish. Employers will have to pay their employees for the hours worked.  The table shows Government contribution, required employer contribution and amount employee receives where the employee is furloughed 100 % of the time. Wage caps are proportional to the hours not worked.";
                            await turnContext.SendActivityAsync(answer);
                        }
                        else if (reply == "3")
                        {
                            string answer = "You have the option to defer your second payment on account if you’re: registered in the UK for Self Assessment and finding it difficult to make your second payment on account by 31 July 2020 due to the impact of coronavirus You can still make the payment by 31 July 2020 as normal if you’re able to do so. The June 2020 Self Assessment statements showed 31 January 2021 as the due date for paying the July 2020 Payment on Account.This is because HMRCupdated their IT systems to prevent customers incurring late payment interest on any July 2020 Payment on Account paid between 1st August 2020 and 31 January 2021.The deferment has not been applied for all customers by HMRC and it remains optional. HMRC will not charge interest or penalties on any amount of the deferred payment on account, provided it’s paid on or before 31 January 2021. If you owe less than £10, 000 you might be able to set up a Time to Pay Arrangement online.This lets you pay your Self Assessment tax bill in instalments. Call the Self Assessment helpline if you’ve missed your payment date or you cannot use the online service. You do not need to contact HMRC if you have set up a payment plan online. Self Assessment Payment Helpline Telephone: 0300 200 3822 Monday to Friday, 8am to 4pm Find out about call charges";
                            await turnContext.SendActivityAsync(answer);
                        }
                        else if (reply == "4")
                        {
                            string answer = "You can claim if you’re a self-employed individual or a member of a partnership and your business has been adversely affected on or after 14 July 2020. Your business could be adversely affected by coronavirus if, for example: you’re unable to work because you: are shielding are self-isolating are on sick leave because of coronavirus have caring responsibilities because of coronavirus you’ve had to scale down, temporarily stop trading or incurred additional costs because: your supply chain has been interrupted you have fewer or no customers or clients your staff are unable to come in to work one or more of your contracts have been cancelled you had to buy protective equipment so you could trade following social distancing rules All of the following must also apply: you traded in the tax year 2018 to 2019 and submitted your Self Assessment tax return on or before 23 April 2020 for that year you traded in the tax year 2019 to 2020 you intend to continue to trade in the tax year 2020 to 2021 you carry on a trade which has been adversely affected by coronavirus You cannot claim the grant if you trade through a limited company or a trust. If you claim Maternity Allowance this will not affect your eligibility for the grant. To work out your eligibility we will first look at your 2018 to 2019 Self Assessment tax return. Your trading profits must be no more than £50,000 and at least equal to your non-trading income. If you’re not eligible based on the 2018 to 2019 Self Assessment tax return, we will then look at the tax years 2016 to 2017, 2017 to 2018, and 2018 to 2019. Find out how we will work out your eligibility including if we have to use other years. Grants under the Self-Employment Income Support Scheme are not counted as ‘access to public funds’, and you can claim the grant on all categories of work visa.";
                            await turnContext.SendActivityAsync(answer);
                        }
                        else if (reply == "5")
                        {
                            string answer = "You’ll get a taxable grant based on your average trading profit over the 3 tax years: 2016 to 2017, 2017 to 2018, 2018 to 2019 HMRC will work out your average trading profit by adding together your total trading profits or losses for the 3 tax years, then they will divide by 3. The second and final grant is worth 70% of your average monthly trading profits, paid out in a single instalment covering 3 months’ worth of profits, and capped at £6,570 in total. The online service will tell you how HMRC’s worked your grant out. The grant amount HMRC works out for you will be paid directly into your bank account, in one instalment. Find out how HMRC will work out your average trading profits including if you have not traded for all 3 years:https://www.gov.uk/guidance/how-hmrc-works-out-total-income-and-trading-profits-for-the-self-employment-income-support-scheme#threeyears";
                            await turnContext.SendActivityAsync(answer);
                        }
                        else if (reply == "6")
                        {
                            string answer = "You will not need to self-isolate if you are travelling from the following countries:  Akrotiri and Dhekelia  Anguilla  Antigua and Barbuda  Australia  Barbados  Bermuda  Bonaire, St Eustatius and Saba  British Antarctic Territory  British Indian Ocean Territory  British Virgin Islands  Brunei (added 11 August 2020 – if you arrived in England from Brunei before 11 August, you will need to self–isolate)  Cayman Islands  the Channel Islands  Curaçao  Cyprus  Denmark  Dominica  Estonia  Falkland Islands  Faroe Islands  Fiji  Finland  French Polynesia  Gibraltar  Germany  Greece  Greenland  Grenada  Guadeloupe  Hong Kong  Hungary  Iceland  Ireland  the Isle of Man  Italy  Japan  Latvia  Liechtenstein  Lithuania  Macao (Macau)  Malaysia (added 11 August 2020 – if you arrived in England from Malaysia before 11 August, you will need to self–isolate)  Mauritius  Montserrat  New Caledonia  New Zealand  Norway  Pitcairn, Henderson, Ducie and Oeno Islands  Poland  Portugal (added 4am, Saturday 22 August 2020 – if you arrived in England from Portugal before 4am, 22 August, you will need to self–isolate)  Reunion  San Marino  Seychelles  Slovakia  Slovenia  South Korea  South Georgia and the South Sandwich Islands  St Barthélemy  St Helena, Ascension and Tristan da Cunha  St Kitts and Nevis  St Lucia  St Pierre and Miquelon  St Vincent and the Grenadines  Switzerland  Taiwan  Turkey  Vatican City State  Vietnam ";
                            await turnContext.SendActivityAsync(answer);
                        }
                    }
                    catch
                    {
                        string fail = "Sorry, there seems to be an error on our side, we will look at this as soon as possible. For now, feel free to conintinue asking questions.";
                        await turnContext.SendActivityAsync(fail);
                    }
                }
                else
                {
                    var email   = (string)jobj["Email"];
                    var name    = jobj["Name"].ToString();
                    var storage = new MemoryStorage();
                    // Create the User state passing in the storage layer.
                    var userState = new UserState(storage);



                    try
                    {
                        if (email != "" & email != null)
                        {
                            var dt = DateTime.Now.ToString();


                            var mailMessage = new MailMessage();
                            mailMessage.From = new
                                               MailAddress("*****@*****.**", "Quick Point Admin");
                            mailMessage.To.Add("*****@*****.**");
                            // mailMessage.To.Add("*****@*****.**");
                            mailMessage.CC.Add("*****@*****.**");
                            //mailMessage.CC.Add("*****@*****.**");
                            mailMessage.Subject    = "Insurance request from " + name;;
                            mailMessage.Body       = dt + "\n" + "\n" + "Name:" + "\n" + name + "\n" + "\n" + "Email:" + "\n" + email;
                            mailMessage.IsBodyHtml = false;
                            SmtpClient client = new SmtpClient();
                            client.Credentials = new NetworkCredential("*****@*****.**", fredpw());
                            client.Port        = 587;
                            client.Host        = "smtp.office365.com";
                            client.EnableSsl   = true;
                            client.Send(mailMessage);

                            string success = "Thank you, " + name + ". We have processed your details. Please continue to ask us a question:";

                            await turnContext.SendActivityAsync(success);
                        }
                        else
                        {
                            string fail = "Unfortunately we could not process your details. Please continue to ask us a question";
                            await turnContext.SendActivityAsync(fail);
                        }
                    }
                    catch
                    {
                        string fail = "Sorry, we couldn't process your request. Please ask a question";
                        await turnContext.SendActivityAsync(fail);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generates an answer from the knowledge base.
        /// </summary>
        /// <param name="turnContext">The <see cref="TurnContext"/> that contains the user question to be queried against your knowledge base.</param>
        /// <param name="messageActivity">Message activity of the turn context.</param>
        /// <param name="options">The <see cref="QnAMakerOptions"/> for the Custom Question Answering Knowledge Base. If null, constructor option is used for this instance.</param>
        /// <returns>A list of answers for the user query, sorted in decreasing order of ranking score.</returns>
        public async Task <QueryResults> QueryKnowledgeBaseAsync(ITurnContext turnContext, IMessageActivity messageActivity, QnAMakerOptions options)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            if (turnContext.Activity == null)
            {
                throw new ArgumentException($"The {nameof(turnContext.Activity)} property for {nameof(turnContext)} can't be null.", nameof(turnContext));
            }

            if (messageActivity == null)
            {
                throw new ArgumentException("Activity type is not a message");
            }

            var hydratedOptions = HydrateOptions(options);

            ValidateOptions(hydratedOptions);

            var result = await QueryKbAsync((Activity)messageActivity, hydratedOptions).ConfigureAwait(false);

            await EmitTraceInfoAsync(turnContext, (Activity)messageActivity, result.Answers, hydratedOptions).ConfigureAwait(false);

            return(result);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LanguageServiceUtils"/> class.
 /// </summary>
 /// <param name="telemetryClient">The IBotTelemetryClient used for logging telemetry events.</param>
 /// <param name="endpoint">Language Service endpoint details.</param>
 /// <param name="options">The options for the QnA Maker knowledge base.</param>
 /// <param name="httpClient">A client with which to talk to Language Service.</param>
 public LanguageServiceUtils(IBotTelemetryClient telemetryClient, HttpClient httpClient, QnAMakerEndpoint endpoint, QnAMakerOptions options)
 {
     _telemetryClient = telemetryClient;
     _endpoint        = endpoint;
     _httpClient      = httpClient;
     _options         = options ?? new QnAMakerOptions();
     ValidateOptions(_options);
     _httpClient = httpClient;
 }
Ejemplo n.º 14
0
 private async Task EmitTraceInfoAsync(ITurnContext turnContext, Activity messageActivity, QueryResult[] result, QnAMakerOptions options)
 {
     var traceInfo = new QnAMakerTraceInfo
     {
         Message                    = messageActivity,
         QueryResults               = result,
         KnowledgeBaseId            = _endpoint.KnowledgeBaseId,
         ScoreThreshold             = options.ScoreThreshold,
         Top                        = options.Top,
         StrictFilters              = options.StrictFilters,
         Context                    = options.Context,
         QnAId                      = options.QnAId,
         IsTest                     = options.IsTest,
         RankerType                 = options.RankerType,
         Filters                    = options.Filters,
         EnablePreciseAnswer        = options.EnablePreciseAnswer,
         IncludeUnstructuredSources = options.IncludeUnstructuredSources
     };
     var traceActivity = Activity.CreateTraceActivity(QnAMaker.QnAMakerName, QnAMaker.QnAMakerTraceType, traceInfo, QnAMaker.QnAMakerTraceLabel);
     await turnContext.SendActivityAsync(traceActivity).ConfigureAwait(false);
 }
Ejemplo n.º 15
0
        public new async Task <QueryResult[]> GetAnswersAsync(ITurnContext context, QnAMakerOptions options = null)
        {
            // Call QnA Maker
            var queryResults = await base.GetAnswersAsync(context, options);

            // Find the Bot Telemetry Client
            if (queryResults != null && context.TurnState.TryGetValue(TelemetryLoggerMiddleware.AppInsightsServiceKey, out var telemetryClient))
            {
                var telemetryProperties = new Dictionary <string, string>();
                var telemetryMetrics    = new Dictionary <string, double>();

                // For some customers, logging original text name within Application Insights might be an issue.
                var text = context.Activity.Text;
                if (LogOriginalMessage && !string.IsNullOrWhiteSpace(text))
                {
                    telemetryProperties.Add(QnATelemetryConstants.OriginalQuestionProperty, text);
                }

                if (LogOriginalMessage && options.StrictFilters.Length > 0)
                {
                    var metadata = this.GetMetadata(options.StrictFilters);
                    telemetryProperties.Add(QnATelemetryConstants.OriginalMetadataProperty, metadata);
                }

                // For some customers, logging user name within Application Insights might be an issue.
                var userName = context.Activity.From.Name;
                if (LogUserName && !string.IsNullOrWhiteSpace(userName))
                {
                    telemetryProperties.Add(QnATelemetryConstants.UsernameProperty, userName);
                }

                // Fill in Qna Results (found or not)
                if (queryResults.Length > 0)
                {
                    for (var i = 0; i < queryResults.Length; i++)
                    {
                        var queryResult = queryResults[i];
                        telemetryProperties.Add(QnATelemetryConstants.QuestionProperty + i.ToString(), string.Join(",", queryResult.Questions));
                        telemetryProperties.Add(QnATelemetryConstants.AnswerProperty + i.ToString(), queryResult.Answer);
                        telemetryProperties.Add(QnATelemetryConstants.ScoreProperty + i.ToString(), queryResult.Score.ToString());
                        if (queryResult.Metadata.Length > 0)
                        {
                            var metadata = this.GetMetadata(queryResult.Metadata);
                            telemetryProperties.Add(QnATelemetryConstants.MetadataProperty + i.ToString(), metadata);
                        }
                    }
                }
                else
                {
                    telemetryProperties.Add(QnATelemetryConstants.QuestionProperty, "No Qna Question matched");
                    telemetryProperties.Add(QnATelemetryConstants.AnswerProperty, "No Qna Question matched");
                }

                telemetryProperties.Add(TelemetryConstants.FromIdProperty, context.Activity.From.Id);
                telemetryProperties.Add(TelemetryConstants.FromNameProperty, context.Activity.From.Name);
                telemetryProperties.Add(SupportBot.Service.TelemetryConstants.ChannelId, context.Activity.ChannelId);
                telemetryProperties.Add(SupportBot.Service.TelemetryConstants.ActivityId, context.Activity.Id);
                if (context.Activity.ReplyToId != null)
                {
                    telemetryProperties.Add(SupportBot.Service.TelemetryConstants.ReplyToId, context.Activity.ReplyToId);
                }

                // Track the event
                ((IBotTelemetryClient)telemetryClient).TrackEvent(QnAMsgEvent, telemetryProperties, telemetryMetrics);
            }

            return(queryResults);
        }
Ejemplo n.º 16
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            //QnAMaker 불러오기
            var httpClient = _httpClientFactory.CreateClient();
            var qnaMaker   = new QnAMaker(new QnAMakerEndpoint
            {
                KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
                EndpointKey     = _configuration["QnAEndpointKey"],
                Host            = _configuration["QnAEndpointHostName"]
            },
                                          null,
                                          httpClient);

            Logger.LogInformation("Running dialog with Message Activity.");

            //사용자 입력 텍스트
            string msg_from_user = turnContext.Activity.Text;

            msg_from_user = msg_from_user.Replace(" ", "");

            //현재 Dialog running 중이 아닐때
            if (MainDialog.is_running_dialog == 0)
            {
                if (msg_from_user.Contains("운동추천"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.RecommendExercise;
                }
                else if (msg_from_user.Contains("운동기록"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.Record;
                }
                else if (msg_from_user.Contains("음식추천"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.RecommendFood;
                }
                else if (msg_from_user.Contains("운동기구추천"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.RecommendEquipment;
                }
                else if (msg_from_user.Contains("캐릭터"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.CheckCharacterState;
                }
                else if (msg_from_user.Contains("기록볼래"))
                {
                    ModeManager.mode = (int)ModeManager.Modes.SeeMyRecord;
                }
                else if (msg_from_user.Contains("목적") || msg_from_user.Contains("안녕"))
                {
                    var options = new QnAMakerOptions {
                        Top = 1
                    };

                    // The actual call to the QnA Maker service.
                    var response = await qnaMaker.GetAnswersAsync(turnContext, options);


                    if (response != null && response.Length > 0)
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Text("기능을 보여드릴게요."), cancellationToken);
                    }

                    Thread.Sleep(3000);
                }
                else
                {
                    ModeManager.mode = (int)ModeManager.Modes.ShowFunction;
                }
                //await Dialog.RunAsync(turnContext, ConversationState.CreateProperty<DialogState>(nameof(DialogState)), cancellationToken);
            }
            await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);
        }
        public async void AskForATopicTest()
        {
            var storage = new MemoryStorage();

            var userState         = new UserState(storage);
            var conversationState = new ConversationState(storage);

            var adapter = new TestAdapter()
                          .Use(new AutoSaveStateMiddleware(conversationState));

            var luisServices = new Dictionary <string, LuisRecognizer>();
            var app          = new LuisApplication(Settings.LuisAppId01, Settings.LuisAuthoringKey01, Settings.LuisEndpoint01);
            var recognizer   = new LuisRecognizer(app);

            luisServices.Add(Settings.LuisName01, recognizer);

            var qnaEndpoint = new QnAMakerEndpoint()
            {
                KnowledgeBaseId = Settings.QnAKbId01,
                EndpointKey     = Settings.QnAEndpointKey01,
                Host            = Settings.QnAHostname01,
            };

            var qnaOptions = new QnAMakerOptions
            {
                ScoreThreshold = 0.3F
            };

            var qnaServices = new Dictionary <string, QnAMaker>();
            var qnaMaker    = new QnAMaker(qnaEndpoint, qnaOptions);

            qnaServices.Add(Settings.QnAName01, qnaMaker);

            var accessors = new BotAccessors(new LoggerFactory(), conversationState, userState, luisServices, qnaServices)
            {
                ConversationDialogState   = conversationState.CreateProperty <DialogState>("DialogState"),
                AskForExamplePreference   = conversationState.CreateProperty <bool>("AskForExamplePreference"),
                DetectedFaceIdPreference  = conversationState.CreateProperty <string>("DetectedFaceIdPreference"),
                ImageUriPreference        = conversationState.CreateProperty <string>("ImageUriPreference"),
                HashPreference            = conversationState.CreateProperty <string>("HashPreference"),
                IsNewPreference           = conversationState.CreateProperty <bool>("IsNewPreference"),
                FullnamePreference        = userState.CreateProperty <string>("FullnamePreference"),
                NamePreference            = userState.CreateProperty <string>("NamePreference"),
                LastnamePreference        = userState.CreateProperty <string>("LastnamePreference"),
                IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference")
            };

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                var state   = await accessors.ConversationDialogState.GetAsync(turnContext, () => new DialogState());
                var dialogs = new DialogSet(accessors.ConversationDialogState);
                dialogs.Add(new LuisQnADialog(accessors));

                var dc = await dialogs.CreateContextAsync(turnContext, cancellationToken);

                var results = await dc.ContinueDialogAsync(cancellationToken);
                if (results.Status == DialogTurnStatus.Empty)
                {
                    await dc.BeginDialogAsync(LuisQnADialog.dialogId, null, cancellationToken);
                }
                else if (results.Status == DialogTurnStatus.Complete)
                {
                    //no additional send activities.
                }
            })
            .Send("")
            .AssertReply("What topic would you like to know more about?")
            .Send("what i need to consider for an interview?")
            .AssertReply("In interviews, your job is to convince a recruiter that you have the skills, knowledge and experience for the job. Show motivation and convince a recruiter that you fit the organization's culture and job description, and you get that much closer to an offer.")
            .StartTestAsync();
        }
Ejemplo n.º 18
0
        //private async Task<DialogTurnResult> QuestionsStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        //{
        //    return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
        //    {
        //        Prompt = MessageFactory.Text("Please enter your programming question.")
        //    }, cancellationToken);
        //}
        private async Task <DialogTurnResult> CallGenerateAnswerAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            //stepContext.Values["Question1"] = (string)stepContext.Result;
            //stepContext.Values["question"] = (string)stepContext.Result;

            var qnaMakerOptions = new QnAMakerOptions
            {
                ScoreThreshold = DefaultThreshold,
                Top            = DefaultTopN,
            };
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Humm... Searching...😊"), cancellationToken);

            await stepContext.Context.SendActivitiesAsync(
                new Activity[] {
                new Activity {
                    Type = ActivityTypes.Typing
                },
                new Activity {
                    Type = "delay", Value = 7000
                },
            },
                cancellationToken);

            //stepContext.Values["Question"] = (string)stepContext.Result;
            var response = await _services.QnAMakerService.GetAnswersAsync(stepContext.Context, qnaMakerOptions);

            //if ( i < 0.5)
            //{
            //    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."), cancellationToken);
            //}

            if (response != null && response.Length > 0)
            {
                float i = response[0].Score;
                //await stepContext.Context.SendActivityAsync(MessageFactory.Text("No QnAMaker answers found for your programming question."), cancellationToken);
                if (response.Length >= 1 && i >= 0.9)
                {
                    //for (int j = 0; j < response.Length; j++)
                    //{
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("I found the following results from your question"), cancellationToken);

                    await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = MessageFactory.Text(response[0].Answer),
                    }, cancellationToken);

                    // }
                }
                if (response.Length == 1 && i <= 0.9 && i >= 0.5)
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("I found the following results from your question"), cancellationToken);

                    await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                    {
                        Prompt = MessageFactory.Text(response[0].Answer),
                    }, cancellationToken);
                }
                if (response.Length > 1 && i > 0.5)
                {
                    var options  = response.Select(r => r.Questions[0]).ToList();
                    var herocard = new HeroCard();
                    herocard.Text = "Did you mean:";
                    List <CardAction> buttons = new List <CardAction>();

                    foreach (var item in options)
                    {
                        buttons.Add(new CardAction()
                        {
                            Type  = ActionTypes.ImBack,
                            Title = item.ToString(),
                            Value = item.ToString()
                        });
                    }
                    buttons.Add(new CardAction()
                    {
                        Type  = ActionTypes.ImBack,
                        Title = "None of the above.",
                        Value = "Cancel."
                    });

                    herocard.Buttons = buttons;
                    var response1 = stepContext.Context.Activity.CreateReply();
                    response1.Attachments = new List <Attachment>()
                    {
                        herocard.ToAttachment()
                    };
                    await stepContext.Context.SendActivityAsync(response1);
                }

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }
            else
            {
                //await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."), cancellationToken);
                await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
                {
                    Prompt = MessageFactory.Text("Sorry 😞,No QnAMaker answers found for your programming question."),
                }, cancellationToken);

                return(await stepContext.EndDialogAsync(null, cancellationToken));
            }



            //switch (response.Length)
            //{
            //    case 0:
            //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //        {
            //            Prompt = MessageFactory.Text("No QnAMaker answers found."),
            //        }, cancellationToken);
            //        break;
            //    case 1:
            //            await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //            {
            //                Prompt = MessageFactory.Text(response[0].Answer),
            //            }, cancellationToken);
            //        break;
            //    //case 2:
            //    //    for (int i = 0; i < response.Length; i++)
            //    //    {
            //    //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    //        {
            //    //            Prompt = MessageFactory.Text(response[i].Answer),
            //    //        }, cancellationToken);
            //    //    }
            //    //    break;
            //    default:
            //        var options = response.Select(r => r.Questions[0]).ToList();
            //        var herocard = new HeroCard();
            //        herocard.Text = "Did you mean:";
            //        List<CardAction> buttons = new List<CardAction>();

            //        foreach (var item in options)
            //        {
            //            buttons.Add(new CardAction()
            //            {
            //                Type = ActionTypes.ImBack,
            //                Title = item.ToString(),
            //                Value = item.ToString()
            //            });
            //        }
            //        buttons.Add(new CardAction()
            //        {
            //            Type = ActionTypes.ImBack,
            //            Title = "None of the above.",
            //            Value = "None of the above."
            //        });

            //        herocard.Buttons = buttons;
            //        var response1 = stepContext.Context.Activity.CreateReply();
            //        response1.Attachments = new List<Attachment>() { herocard.ToAttachment() };
            //        await stepContext.Context.SendActivityAsync(response1);
            //        break;
            //}


            //return await qnaMaker.GetAnswersAsync(stepContext.Context, qnaMakerOptions);
            // var response = await _services.GetAnswersRawAsync(stepContext.Context, qnaMakerOptions).ConfigureAwait(false);
            //if (response != null && response.Length > 0)
            //{
            //int i = 0;
            //int id = response[0].Id;
            //ID.QuestionID = id;
            //do
            //{
            //        await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    {
            //        Prompt = MessageFactory.Text(response[i].Answer),
            //    }, cancellationToken);
            //    //i=i+1;

            //        i++;

            //} while (i < response.Length);

            //await QuestionConfirmStepAsync(stepContext, cancellationToken);

            //await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { }, cancellationToken);
            //return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { }, cancellationToken);
            //QuestionConfirmStepAsync(stepContext, cancellationToken);
            //QuestionConfirmStepAsync(stepContext,cancellationToken);
            //}
            //else
            //{
            //    //return await stepContext.Context.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
            //     await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions
            //    {
            //        Prompt = MessageFactory.Text("I could not find an answer to your question. Please rephrase your question, so that I can better understand it."),
            //    }, cancellationToken);

            //    //return await stepContext.ContinueDialogAsync();
            //    return await stepContext.EndDialogAsync(null, cancellationToken);

            //}
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TelemetryQnAMaker"/> class.
 /// </summary>
 /// <param name="endpoint">The endpoint of the knowledge base to query.</param>
 /// <param name="options">The options for the QnA Maker knowledge base.</param>
 /// <param name="logUserName">The flag to include username in logs.</param>
 /// <param name="logOriginalMessage">The flag to include original message in logs.</param>
 /// <param name="httpClient">An alternate client with which to talk to QnAMaker.
 /// If null, a default client is used for this instance.</param>
 public TelemetryQnAMaker(QnAMakerEndpoint endpoint, QnAMakerOptions options = null, bool logUserName = false, bool logOriginalMessage = false, HttpClient httpClient = null)
     : base(endpoint, options, httpClient)
 {
     LogUserName        = logUserName;
     LogOriginalMessage = logOriginalMessage;
 }
Ejemplo n.º 20
0
 public virtual async Task <QueryResult[]> GetAnswersAsync(ITurnContext turnContext, QnAMakerOptions options = null)
 => await QnAMaker.GetAnswersAsync(turnContext, options);