Exemple #1
0
        public async Task QnA(IDialogContext context, LuisResult result)
        {
            QnAService  qNa     = new QnAService();
            QnAResponse reponse = await qNa.GetAnswerAsync(result.Query);

            await context.PostAsync(reponse.Answer);

            context.Wait(this.MessageReceived);
        }
Exemple #2
0
        public QnAStoryDialog(QnAService qnaService, LuisRecognizer luisRecognizer) : base(nameof(QnAStoryDialog), luisRecognizer)
        {
            _qnAService = qnaService;

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
            {
                GetQnAAsync,
                SendVideoAsync,
                SendQuestionAsync
            }));
            InitialDialogId = nameof(WaterfallDialog);
        }
Exemple #3
0
        public HeroDialog(QnAService qnaService) : base(nameof(HeroDialog))
        {
            AddDialog(new TextPrompt(nameof(TextPrompt)));

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
            {
                GetQnAAsync,
                SendQuestionAsync
            }));

            InitialDialogId = nameof(WaterfallDialog);
            _qnaService     = qnaService;
        }
        private static async Task <bool> SearchQnA(IDialogContext context, string query)
        {
            await context.SendTyping();

            var qnA          = new QnAService();
            var searchResult = await qnA.Search(query);

            if (searchResult == null || Math.Abs(searchResult.Score) < double.Epsilon)
            {
                return(false);
            }

            await context.PostAsync(searchResult.Answer);

            return(true);
        }
Exemple #5
0
        private async Task OnOptionSelected(IDialogContext context, IAwaitable <string> result)
        {
            HelpAnswer answerResult = new HelpAnswer {
                Type = HelpDialogResultTypes.QnA
            };

            var question = await result;

            if (question.Contains("to other options"))
            {
                answerResult.Type = HelpDialogResultTypes.RootDialog;
            }
            else
            {
                answerResult.QnAnswer = QnAService.GetAnswer(question).Answer;
            }

            context.Done(answerResult);
        }
Exemple #6
0
        public async Task QnaService_Update()
        {
            var service      = new QnAService();
            var existingData = await service.Get();

            await service.Update(
                pairsToDelete : existingData,
                pairsToAdd : new List <QuestionWithAnswer>
            {
                new QuestionWithAnswer
                {
                    Question = "Hello",
                    Answer   = "Hello, how can I be of assistance?"
                },
                new QuestionWithAnswer
                {
                    Question = "What is Oslo?",
                    Answer   = "A city"
                }
            });
        }
        public QnAMakerDialog(string dialogId) : base(dialogId)
        {
            // ID of the child dialog that should be started anytime the component is started.
            this.InitialDialogId = dialogId;

            this.AddDialog(new TextPrompt("textPrompt"));

            // Define the conversation flow using the waterfall model.
            this.AddDialog(
                new WaterfallDialog(dialogId, new WaterfallStep[]
            {
                async(stepContext, ct) =>
                {
                    return(await stepContext.PromptAsync(
                               "textPrompt",
                               new PromptOptions
                    {
                        Prompt = MessageFactory.Text("[QnA Maker Dialog] What do you want to know about this event?"),
                    },
                               ct
                               ).ConfigureAwait(false));
                },
                async(stepContext, ct) =>
                {
                    var userAnswer = (string)stepContext.Result;

                    //Ask QNA Maker here.
                    var qnaAnswer = await QnAService.PostQuestion(userAnswer);

                    JObject json  = JObject.Parse(qnaAnswer);
                    string answer = (json["answers"] as JArray)[0]["answer"].Value <string>();

                    await stepContext.Context.SendActivityAsync(answer);

                    return(await stepContext.NextAsync().ConfigureAwait(false));
                }
            }
                                    )
                );
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasicBot"/> class.
        /// </summary>
        /// <param name="botServices">Bot services.</param>
        /// <param name="accessors">Bot State Accessors.</param>
        public BasicBot(BotServices services, UserState userState, ConversationState conversationState, ILoggerFactory loggerFactory, IConfiguration configuration)
        {
            _configuration = configuration;

            // Initialize our QnA Service
            _qnaService = new QnAService(_configuration);

            // Initialize required services and other info
            _services          = services ?? throw new ArgumentNullException(nameof(services));
            _userState         = userState ?? throw new ArgumentNullException(nameof(userState));
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));

            _greetingStateAccessor = _userState.CreateProperty <GreetingState>(nameof(GreetingState));
            _dialogStateAccessor   = _conversationState.CreateProperty <DialogState>(nameof(DialogState));

            // Verify LUIS configuration.
            if (!_services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"The bot configuration does not contain a service type of `luis` with the id `{LuisConfiguration}`.");
            }

            Dialogs = new DialogSet(_dialogStateAccessor);
            Dialogs.Add(new GreetingDialog(_greetingStateAccessor, loggerFactory));
        }
Exemple #9
0
        public async Task QnaService_Publish()
        {
            //Read contets of existing markdown files
            var reader = new MarkdownReader();
            await reader.ReadMarkdownFiles(@"C:\VS2015\pp-git\DigitalAssistant.Documentation\Helpcenter\docs");

            if (reader.QuestionWithAnswers.Any())
            {
                //Sdk on top of QnAMaker - V2.0 Rest api
                var service = new QnAService();

                //Get all existing QnA pairs
                var existingData = await service.Get();

                //Remove all existing entries, and add the ones generated from the markdown files
                await service.Update(
                    pairsToDelete : existingData,
                    pairsToAdd : reader.QuestionWithAnswers
                    );

                //Republish
                var published = await service.Publish();
            }
        }
Exemple #10
0
 public QnABot(ILogger <QnABot> logger, QnAService qnaService)
 {
     _logger     = logger;
     _qnAService = qnaService;
 }
Exemple #11
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var activity = await argument as Activity;

            await PrivacyPolicyAsync(context);

            User user = await GetUser(context, argument);

            Order         order           = StorageManager.Instance.Get(user.RowKey);
            var           customerName    = user.PartitionKey;
            bool          IsSubscriped    = order != null;
            string        messageRecieved = activity.Text.ToLower();
            List <string> welcomeMessages = new List <string>()
            {
                "hi", "hello", "welcome", "dear"
            };
            var match = welcomeMessages.FirstOrDefault(stringToCheck => stringToCheck.Contains(messageRecieved));

            if (messageRecieved.Equals("privacy"))
            {
                await context.PostAsync($"Hi {customerName} kindly check our cosnumer terms and privacy policy \r\nif you continue to use our service you agree and bind to them");

                await context.PostAsync($"Privacy policy : http://uscisbot2017.azurewebsites.net/privacy/PrivacyPolicy.txt");

                await context.PostAsync($"Consumer Terms : http://uscisbot2017.azurewebsites.net/privacy/ConsumerTerms.txt");
            }
            else if (messageRecieved.Contains("help") || messageRecieved.Equals("?"))
            {
                await SendWelcomeMessage(context, customerName);

                await context.PostAsync($"simply type the following:");

                await context.PostAsync($"status for [name] cases [list of cases separated by ;] ");

                await context.PostAsync($"example : status for {customerName} cases 1234;1234");

                await context.PostAsync($"avilable commands : list , clear , status , help, privacy");
            }
            else if (messageRecieved.Equals("clear"))
            {
                user.Cases = null;
                StorageManager.Instance.Update(user);
                await context.PostAsync("cleared all tracking data !");
            }
            else if (messageRecieved.Equals("list"))
            {
                if (!string.IsNullOrWhiteSpace(user.Cases))
                {
                    string decrypt = AESCrypto.DecryptText(user.Cases, user.RowKey);
                    var    dic     = ToDictionary(decrypt);
                    foreach (var item in dic)
                    {
                        await context.PostAsync(item.Key + " :");

                        string[] arr = item.Value.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var r in arr)
                        {
                            await context.PostAsync(r);
                        }
                    }
                    //don't show offer if subscriped
                    if (!IsSubscriped)
                    {
                        await this.PaymentMessageAsync(context, argument);
                    }
                }
                else
                {
                    await context.PostAsync("nothing there ! , type help for more details");
                }
            }
            else if (messageRecieved.Contains("status") || messageRecieved.Equals("check"))
            {
                Dictionary <string, string> dic = new Dictionary <string, string>();
                if (!string.IsNullOrWhiteSpace(user.Cases))
                {
                    dic = ToDictionary(AESCrypto.DecryptText(user.Cases, user.RowKey));
                }

                List <string> statuses = new List <string>();
                if (messageRecieved.Equals("check"))
                {
                    statuses = new List <string>(dic.Keys);
                }
                else
                {
                    statuses.Add(messageRecieved);
                }
                foreach (var status in statuses)
                {
                    string[] arr = status.Split(new string[] { "cases" }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length < 2)
                    {
                        await context.PostAsync($"try this : status for {customerName} cases 1234;1234");

                        return;
                    }
                    string        name      = arr[0].Replace("status for", "").Trim();
                    string        cases     = arr[1].Trim();
                    List <string> casesList = cases.Split(';').ToList();

                    List <string> casesResultList = new List <string>();
                    string        casesResult     = string.Empty;

                    foreach (var c in casesList)
                    {
                        string uscisstatus, summary = string.Empty;
                        USCIS.UscisService.GetCaseStatus(c, out uscisstatus, out summary);
                        casesResult += $"{uscisstatus}$$${summary}$$$";
                        casesResultList.Add($"{uscisstatus}\r\n{summary}");
                    }

                    if (dic.ContainsKey(status))
                    {
                        string dicResult = dic[status];
                        if (casesResult.Equals(dicResult))
                        {
                            await context.PostAsync($"{status} \r\n No new updates for your cases , will keep an eye on it !");

                            continue;
                        }
                        else
                        {
                            dic[status] = casesResult;
                        }
                    }
                    else
                    {
                        dic.Add(status, casesResult);
                    }

                    user.Cases = AESCrypto.EncryptText(ToString(dic), user.RowKey);

                    // send result
                    await context.PostAsync($"{name} status :");

                    foreach (var c in casesResultList)
                    {
                        await context.PostAsync(c);
                    }

                    await context.PostAsync($"I will keep an eye for {name} with cases {cases} and update you if there are any changes." + (IsSubscriped ? "" : " , if you buy our offer !"));

                    //don't show offer if subscriped
                    if (!IsSubscriped)
                    {
                        await this.PaymentMessageAsync(context, argument);
                    }

                    StorageManager.Instance.Update(user);
                }
            }
            else if (match != null)
            {
                await SendWelcomeMessage(context, customerName);

                await context.PostAsync($"what I can do for you today ? type help for more info.");
            }
            else// chat mode
            {
                string result = QnAService.GetAnswer(messageRecieved);
                if (result.Equals("No good match found in the KB"))
                {
                    result = "Still building my knowledge ask questions related to immigration , will troll with you once I became 1 year old";
                }

                await context.PostAsync(result);
            }
        }
Exemple #12
0
 public async Task QnaService_Get()
 {
     var service = new QnAService();
     var tsvData = await service.Get();
 }