예제 #1
0
        private async Task AddStudentAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;

            if (newStudentStep == 0)
            {
                // Name
                string newName = activity.Text.Substring(0, 1).ToUpper() + activity.Text.Substring(1).ToLower();

                if (digraph.Contains(newName))
                {
                    newName = StudentGraphGenerator.GenerateUniqueName(digraph, newName);
                    await context.PostAsync($"Because the system already contains a student with the given name, it has been changed to { newName }.");
                }

                newStudent     = new Student(newName);
                newStudentStep = 1;
                await context.PostAsync($"What subject does { newStudent } study?");

                context.Wait(AddStudentAsync);
            }
            else if (newStudentStep == 1)
            {
                // Study
                newStudent.Study = activity.Text.Substring(0, 1).ToUpper() + activity.Text.Substring(1);
                newStudentStep   = 2;
                PromptDialog.Confirm(context, StudyGroupAsync, $"Does { newStudent } seek a study group?");
            }
            else if (newStudentStep == 2)
            {
                // SeeksGroup (has already been handled in separate method - this code should never be reached)
                newStudentStep = 3;
                context.Wait(AddStudentAsync);
            }
            else if (newStudentStep == 3)
            {
                // Attributes
                if (activity.Text == "-")
                {
                    activity.Text = "";
                }
                newStudent.Attributes = new HashSet <string>(activity.Text.ToUpper().Split(' '));
                newStudentStep        = 4;
                await context.PostAsync($"Enter { newStudent }'s study attributes separated by spaces. Type '-' if there are none.");

                context.Wait(AddStudentAsync);
            }
            else if (newStudentStep == 4)
            {
                // StudyAttributes
                if (activity.Text == "-")
                {
                    activity.Text = "";
                }
                newStudent.StudyAttributes = new HashSet <string>(activity.Text.ToUpper().Split(' '));
                newStudentStep             = 5;
                await context.PostAsync($"Enter { newStudent }'s neighbors separated by spaces. Type '-' if there are none.");

                context.Wait(AddStudentAsync);
            }
            else if (newStudentStep == 5)
            {
                // Neighbors
                string[] rawNeighbors;

                if (activity.Text == "-")
                {
                    rawNeighbors = new string[] { };
                }
                else
                {
                    rawNeighbors = activity.Text.Split(' ');
                }

                newNeighbors = new string[rawNeighbors.Length];

                for (int i = 0; i < rawNeighbors.Length; i++)
                {
                    newNeighbors[i] = rawNeighbors[i].Substring(0, 1).ToUpper() + rawNeighbors[i].Substring(1).ToLower();
                }

                newStudentStep = 0;
                await context.PostAsync($"The new student's details are: { newStudent.GetDetails() }, Neighbors: [{ newNeighbors.ToSeparatedString() }]");

                PromptDialog.Confirm(context, NewStudentAsync, $"Can you confirm the details?");
            }
            else
            {
                // Error
                await context.PostAsync($"I am a bit confused, sorry. Please try again.");

                context.Wait(MessageReceived);
            }
        }
예제 #2
0
 protected virtual Task NoResultsConfirmRetry(IDialogContext context)
 {
     PromptDialog.Confirm(context, this.ShouldRetry, "Sorry, I didn't find any matches. Do you want to retry your search?");
     return(Task.CompletedTask);
 }
예제 #3
0
 /// <summary>
 /// Ask if the user wants to take a survey after the trivia game.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 private async Task AfterTrivia(IDialogContext context, IAwaitable <string> result)
 {
     PromptDialog.Confirm(context, AfterAskingAboutSurvey, "Would you like to take a survey?");
 }
예제 #4
0
 public async Task PromptSuccess_Confirm_No_CaseInsensitive()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText), "No", false);
 }
        private async Task DisambiguateFoodAsync(IDialogContext context, IAwaitable <object> result)
        {
            string disambiguatedFood = null;

            //grab the incoming message text
            if (result != null)
            {
                object awaitedResultObject = await result;

                if (awaitedResultObject is Activity)
                {
                    disambiguatedFood = (awaitedResultObject as Activity).Text;
                }
                else if (awaitedResultObject is string)
                {
                    disambiguatedFood = awaitedResultObject as string;
                }
            }

            //add the incoming message to the disambiguated foods list and remove from the orginal entities list
            if (!string.IsNullOrEmpty(disambiguatedFood))
            {
                _disambiguatedFoods.Add(disambiguatedFood);
                //This is null after the first button is shown which is what ia causing the exception
                _foodEntitiesFromLuis.Remove(_foodEntitiesFromLuis.First());
            }

            if (_foodEntitiesFromLuis.Count > 0)
            {
                //Create card to present specific food choices
                IMessageActivity messageButtons = (Activity)context.MakeMessage();
                messageButtons.Recipient   = messageButtons.From;
                messageButtons.Type        = "message";
                messageButtons.Attachments = new List <Attachment>();
                List <CardAction> cardButtons = new List <CardAction>();
                var disambiguatedFoods        = FoodService.GetFoods(_foodEntitiesFromLuis.First());
                foreach (var food in disambiguatedFoods)
                {
                    cardButtons.Add(new CardAction()
                    {
                        Value = food, Type = "imBack", Title = food
                    });
                }
                HeroCard plCard = new HeroCard()
                {
                    Title    = null,
                    Subtitle = string.Format("You said {0}, which one did you mean?", _foodEntitiesFromLuis.First()),
                    Images   = null,
                    Buttons  = cardButtons
                };
                messageButtons.Attachments.Add(plCard.ToAttachment());
                await context.PostAsync(messageButtons);

                //wait for repsonse
                context.Wait(null);
            }
            else
            {
                //Store disambiguated foods in bot state so other dialogs can access it
                context.ConversationData.SetValue("DisambiguatedFoods", _disambiguatedFoods);

                //check that the user is happy to log the meal, if not start again
                PromptDialog.Confirm(
                    context,
                    AfterSummaryAsync,
                    $"You selected {string.Join(" ", _disambiguatedFoods)}... Is that correct?",
                    "Didn't get that!",
                    promptStyle: PromptStyle.None);
            }
        }
 public async Task Conversation_End(IDialogContext context, LuisResult luisResult)
 {
     PromptDialog.Confirm(context, onEndMessage, "Do you want to exit?");
 }
예제 #7
0
 public async Task PromptSuccess_Confirm_Yes()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText), "yes", true);
 }
        private async Task CloseIssueIssueResume(IDialogContext context, IAwaitable <double> issue)
        {
            _lastIssue = (int)await issue;

            PromptDialog.Confirm(context, CloseIssueConfirmResume, $"Are you sure you want to close issue **{_lastIssue}** in the **{_lastRepo}** repo?", "I didn't catch that...try again?", 3, PromptStyle.AutoText);
        }
예제 #9
0
        // Method not been used in the class

        /*private async Task <double> getSentimentScore(string DocumentText)
         * {
         *  string queryUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
         *  HttpClient client = new HttpClient()
         *  {
         *      DefaultRequestHeaders =
         *      {
         *          {
         *             "Ocp-Apim-Subscription-Key",
         *             ""
         *          },
         *
         *          {
         *              "Accept",
         *              "application/json"
         *          }
         *      }
         *  };
         *
         *  var textInput = new BatchInput
         *  {
         *      documents = new List<DocumentInput>
         *      {
         *          new DocumentInput
         *          {
         *              Id = 1,
         *              Text = DocumentText,
         *          }
         *      }
         *  };
         *
         *  var jsonInput = JsonConvert.SerializeObject(textInput);
         *  HttpResponseMessage postMessage;
         *  BatchResult response;
         *  try
         *  {
         *      postMessage = await client.PostAsync(queryUri, new StringContent(jsonInput, Encoding.UTF8, "application/json"));
         *      response = JsonConvert.DeserializeObject<BatchResult>(await postMessage.Content.ReadAsStringAsync());
         *  }
         *  catch(Exception e)
         *  {
         *      return 0.0;
         *  }
         *  return response?.documents[0]?.score ?? 0.0;
         * }*/

        /**
         * Method tonhandle the interaction with the HP Service Manager - 9.0
         **/

        // method not used it is defined in the Ticket Model

        /**
         * Method to calculate the user sentiment score
         **/

        private async Task getUserSentiment(IDialogContext context, IAwaitable <TicketModel> result)
        {
            var sentence = await result;
            // string sentenceString = sentence.DatabaseName + "-" + sentence.MiddlewareName + "-" + sentence.ServerName;
            string sentenceString = sentence.Desc + "-" + sentence.DBName + "-" + sentence.ServerName + "-" + sentence.MiddlewareName;
            //string sentenceString = sentence.Desc;

            /**
             * To call the GetQnAMakerResponse to get the responses to the user queries from QnA Maker KB
             * The QnA maker sends the appropriate response to the user queries
             **/

            await context.PostAsync("Let me search my database for a solution to your problem");

            try
            {
                var activity = (Activity)context.MakeMessage();
                activity.Text = sentenceString;

                /**
                 * Call to the sentiment analytics api
                 **/

                var sentiment = await TextAnalyticsService.DetermineSentimentAsync(sentence.ToString());

                var sentimentScore = Math.Round(sentiment * 100, 1) / 10;

                /**
                 * Query to check the user issue in the QnA maker knowledge base
                 **/

                var subscriptionKey = ConfigurationManager.AppSettings["QnaSubscriptionkey"];
                var knowledgeBaseId = ConfigurationManager.AppSettings["QnaKnowledgebaseId"];

                var responseQuery = new QnAMakerDailog.QnAMakerDialog().GetQnAMakerResponse(sentenceString, subscriptionKey, knowledgeBaseId);

                var responseAnswers = responseQuery.answers.FirstOrDefault();

                /**
                 * If the solution to the issue is found in the Kb then send the result to the user
                 **/

                if (responseAnswers != null && responseAnswers.score >= double.Parse(ConfigurationManager.AppSettings["QnAScore"]))
                {
                    await context.PostAsync(responseAnswers.answer);
                }

                /**
                 * If no solution is found then the user response from TicketModel is sent to the Dtabase APRDB and stored in dbo.BotDetails Table
                 **/

                else
                {
                    await context.PostAsync("Could not find a solution to you problem . I have raised a ticket for it, revert to you as soon as we get a solution for it");

                    try
                    {
                        string connectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                        /**
                         * Establish the connection with the SQL database
                         **/

                        SqlConnection connection = new SqlConnection(connectionEstablish);

                        /**
                         * Connection to the DB being opened
                         **/

                        connection.Open();
                        if (connection.State == System.Data.ConnectionState.Open)
                        {
                            Console.WriteLine("Connection Success");

                            /**
                             * SQL command to insert data into the table dbo.BotDetails
                             **/

                            if (sentence.Contact == null)
                            {
                                sentence.Contact = "None";
                            }

                            else if (sentence.PhoneContact == null)
                            {
                                sentence.PhoneContact = "None";
                            }

                            else
                            {
                                Console.WriteLine("Some error occured");
                            }

                            SqlCommand insertCommand = new SqlCommand(@"INSERT INTO dbo.BotDetails (TokenDescription, ServerDetails, MiddlewareDetails, DatabaseDetails, TokenDetails,
                                       SentimentScore, UserName, EmailId, ContactNo) VALUES (@TokenDescription, @ServerDetails, @MiddlewareDetails, @DatabaseDetails, @TokenDetails, @SentimentScore,
                                       @UserName, @EmailId, @ContactNo)", connection);

                            /**
                             * Commands to insert the user response to the database
                             **/

                            insertCommand.Parameters.Add(new SqlParameter("TokenDescription", sentence.Desc));
                            insertCommand.Parameters.Add(new SqlParameter("ServerDetails", sentence.ServerName));
                            insertCommand.Parameters.Add(new SqlParameter("MiddlewareDetails", sentence.MiddlewareName));
                            insertCommand.Parameters.Add(new SqlParameter("DatabaseDetails", sentence.DBName));
                            insertCommand.Parameters.Add(new SqlParameter("TokenDetails", System.DateTimeOffset.Now));
                            insertCommand.Parameters.Add(new SqlParameter("SentimentScore", sentimentScore));
                            insertCommand.Parameters.Add(new SqlParameter("UserName", sentence.Name));
                            insertCommand.Parameters.Add(new SqlParameter("EmailId", sentence.Contact));
                            insertCommand.Parameters.Add(new SqlParameter("ContactNo", sentence.PhoneContact));

                            var DBresult = insertCommand.ExecuteNonQuery();
                            if (DBresult > 0)
                            {
                                connection.Close();

                                string ReconnectionEstablish = ConfigurationManager.ConnectionStrings["APRMConnection"].ConnectionString;

                                SqlConnection conn = new SqlConnection(ReconnectionEstablish);

                                conn.Open();

                                var selectTicketId = "Select Id from dbo.BotDetails WHERE UserName = @UserName";

                                SqlCommand selectCommand = new SqlCommand(selectTicketId, conn);

                                selectCommand.Parameters.AddWithValue("@UserName", sentence.Name);

                                using (SqlDataReader queryReader = selectCommand.ExecuteReader())
                                {
                                    while (queryReader.Read())
                                    {
                                        String retrieveId = queryReader.GetInt32(0).ToString();
                                        //await context.PostAsync("Your ticket has been raised successfully, " + retrieveId + " your token id for the raised ticket");
                                    }
                                }
                            }

                            else
                            {
                                await context.PostAsync("Some problem occured, Please try again after sometime");
                            }

                            /**
                             * Close the existing connection to the DB
                             **/

                            connection.Close();
                        }
                        else
                        {
                            /**
                             * Checks wether the connection is established or not
                             **/
                            Console.WriteLine("Not connected");
                        }

                        /**
                         * Snow connection code
                         **/
                        string DetailDescription = sentence.Desc + " the services are running on server " + sentence.ServerName + ", using " + sentence.DBName + " database and the" + sentence.MiddlewareName + " service";
                        String incidentNo        = string.Empty;
                        incidentNo = SnowLogger.CreateIncidentServiceNow(sentence.Desc, sentence.Contact, DetailDescription, sentence.CategoryName);
                        Console.WriteLine(incidentNo);
                        await context.PostAsync("Your ticket has been raised successfully, " + incidentNo + " your token id for the raised ticket");

                        await context.PostAsync("Please keep the note of above token number. as it would be used for future references");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }

                    context.Done(this);
                }

                /**
                 * Method to check the user sentiment and report it to the user
                 */

                await context.PostAsync($"You rated our service as: {Math.Round(sentiment * 10, 1)}/10");

                if (sentiment <= 0.5)
                {
                    PromptDialog.Confirm(context, ResumeAfterFeedbackClarification, "I see it wasn't perfect, can we contact you about this?");
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
예제 #10
0
 public async Task StopIntent(IDialogContext context, LuisResult result)
 {
     PromptDialog.Confirm(context, AfterResetAsync, "Are you sure ?", "Didn't get that!", promptStyle: PromptStyle.Auto);
 }
예제 #11
0
 public async Task Greetings(IDialogContext context, LuisResult result)
 {
     PromptDialog.Confirm(context, ConfirmAboutPrompt, $"" + message + Environment.NewLine +
                          Environment.NewLine + "Do you want to know something about me?");
 }
예제 #12
0
        public virtual async Task MessageReceivedAsync(
            IDialogContext context,
            IAwaitable <IMessageActivity> argument)
        {
            // Set BaseURL
            context.UserData.TryGetValue <string>(
                "CurrentBaseURL", out strBaseURL);

            int intGuessedNumber;

            // Get the text passed
            var message = await argument;

            // See if a number was passed
            if (!int.TryParse(message.Text, out intGuessedNumber))
            {
                // A number was not passed

                // Create a reply Activity
                Activity replyToConversation = (Activity)context.MakeMessage();
                replyToConversation.Recipient = replyToConversation.Recipient;
                replyToConversation.Type      = "message";

                string strNumberGuesserCard =
                    String.Format(@"{0}/{1}",
                                  strBaseURL,
                                  "Images/NumberGuesserCard.png?tick=123");

                List <CardImage> cardImages = new List <CardImage>();
                cardImages.Add(new CardImage(url: strNumberGuesserCard));

                // Create the Buttons
                // Call the CreateButtons utility method
                List <CardAction> cardButtons = CreateButtons();

                // Create the Hero Card
                // Set the image and the buttons
                HeroCard plCard = new HeroCard()
                {
                    Images  = cardImages,
                    Buttons = cardButtons,
                };

                // Create an Attachment by calling the
                // ToAttachment() method of the Hero Card
                Attachment plAttachment = plCard.ToAttachment();
                // Attach the Attachment to the reply
                replyToConversation.Attachments.Add(plAttachment);
                // set the AttachmentLayout as 'list'
                replyToConversation.AttachmentLayout = "list";

                // Send the reply
                // Create text for a reply message
                replyToConversation.Text = ($"Hello {message.From.Name}!.Below is simple game.Take it easy!");

                await context.PostAsync(replyToConversation);

                context.Wait(MessageReceivedAsync);
            }

            // This code will run when the user has entered a number
            if (int.TryParse(message.Text, out intGuessedNumber))
            {
                // A number was passed
                // See if it was the correct number
                if (intGuessedNumber != this.intNumberToGuess)
                {
                    // The number was not correct
                    this.intAttempts++;

                    // Create a response
                    // This time call the ** ShowButtons ** method
                    Activity replyToConversation =
                        ShowButtons(context, "Not correct. Guess again.");

                    // *************************
                    // Log to Database
                    // *************************

                    // Instantiate the BotData dbContext
                    Models.BotDataEntities DB = new Models.BotDataEntities();
                    // Create a new UserLog object
                    Models.UserLog NewUserLog = new Models.UserLog();

                    // Set the properties on the UserLog object
                    NewUserLog.Channel  = replyToConversation.ChannelId;
                    NewUserLog.UserID   = replyToConversation.From.Id;
                    NewUserLog.UserName = replyToConversation.From.Name;
                    NewUserLog.created  = DateTime.UtcNow;
                    // This logs the message being sent to the user
                    NewUserLog.Message = replyToConversation.Text.Truncate(500);

                    // Add the UserLog object to UserLogs
                    DB.UserLogs.Add(NewUserLog);
                    // Save the changes to the database
                    DB.SaveChanges();

                    await context.PostAsync(replyToConversation);

                    context.Wait(MessageReceivedAsync);
                }
                else
                {
                    // Game completed
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Congratulations! ");
                    sb.Append("The number to guess was {0}. ");
                    sb.Append("You needed {1} attempts. ");
                    sb.Append("Would you like to play again?");

                    string CongratulationsStringPrompt =
                        string.Format(sb.ToString(),
                                      this.intNumberToGuess,
                                      this.intAttempts);

                    // *************************
                    // Log to Database
                    // *************************

                    // Create a reply Activity
                    Activity replyToConversation = (Activity)context.MakeMessage();

                    // Instantiate the BotData dbContext
                    Models.BotDataEntities DB = new Models.BotDataEntities();
                    // Create a new UserLog object
                    Models.UserLog NewUserLog = new Models.UserLog();

                    // Set the properties on the UserLog object
                    NewUserLog.Channel  = replyToConversation.ChannelId;
                    NewUserLog.UserID   = replyToConversation.From.Id;
                    NewUserLog.UserName = replyToConversation.From.Name;
                    NewUserLog.created  = DateTime.UtcNow;
                    // This logs the message being sent to the user
                    NewUserLog.Message = CongratulationsStringPrompt.Truncate(500);
                    // Log the number of turns it took to win
                    NewUserLog.CountOfTurnsToWin = this.intAttempts;
                    // Log the name of the user who won
                    NewUserLog.WinnerUserName = replyToConversation.Recipient.Name;

                    // Add the UserLog object to UserLogs
                    DB.UserLogs.Add(NewUserLog);
                    // Save the changes to the database
                    DB.SaveChanges();

                    // Put PromptDialog here
                    PromptDialog.Confirm(
                        context,
                        PlayAgainAsync,
                        CongratulationsStringPrompt,
                        "Didn't get that!");
                }
            }
        }
예제 #13
0
 private void InitialMessage(IDialogContext context)
 {
     PromptDialog.Confirm(context, ProcessAnswerAsync, "告白したい人がいるの?");
 }
예제 #14
0
 public async Task Restart(IDialogContext context, LuisResult result)
 {
     PromptDialog.Confirm(context, RestartAsync, $"Are you sure you want to restart? All changes will be lost.");
 }
예제 #15
0
 /// <summary>
 /// Called when the user has entered their preferred name after being prompted by <see cref="PromptDialog"/>.
 /// </summary>
 /// <param name="context">Mandatory. The context for the execution of a dialog's conversational process.</param>
 /// <param name="result">Mandatory. The result of the users preferred name. </param>
 private async Task ResumeAfterNameFilled(IDialogContext context, IAwaitable <string> result)
 {
     _preferredName = await result;
     PromptDialog.Confirm(context, ResumeAfterPreferredNameConfirmation, $"So you'd like me to call you {_preferredName}?", $"Sorry I don't understand - try again! Should I call you {_preferredName}?");
 }
예제 #16
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;

            if (_pizzaFlow)
            {
                if (message.Text == "abort")
                {
                    PromptDialog.Confirm(context, AfterResetAsync, "Are you sure you want to abort ordering?", "Didn't get that!", promptStyle: PromptStyle.None);
                }
                else
                {
                    context.Wait(MessageReceivedAsync);
                }
            }
            else
            {
                string resultString = "Sorry, I am not getting you...";

                QueryResult luisResult = await GetEntityFromLuis(message.Text);

                switch (luisResult.topScoringIntent.intent)
                {
                case "Coding":
                {
                    if (luisResult.entities.Any())
                    {
                        var query = luisResult.entities.FirstOrDefault(x => x.type.ToLower().Contains("topic"))?.entity ?? "";
                        var tag   = luisResult.entities.FirstOrDefault(x => x.type.ToLower().Contains("language"))?.entity ?? "";

                        //var query = luisResult.entities.OrderBy(x => x.startIndex).Select(x => x.entity).Aggregate((current, next) => current + " " + next);


                        //msg.Text = soResult.Body;
                        //msg.Attachments = new List<Attachment>()
                        //{
                        //    new Attachment()
                        //    {
                        //        ContentType = "application/vnd.microsoft.card.thumbnail",
                        //        Name = soResult.Title,
                        //        Content = "Please visit my site.",
                        //        ContentUrl = soResult.Link,

                        //    }
                        //};

                        var soResult = await StackOverflow.Query(query, tag);

                        var msg2 = context.MakeMessage();
                        msg2.Type       = "message";
                        msg2.TextFormat = "markdown";
                        //var converter = new Converter();
                        //var markdown = converter.Convert(soResult.Body);
                        //var converter = new ReverseMarkdown.Converter();
                        //string markdown = converter.Convert(soResult.Body);
                        msg2.Text = soResult.Body;

                        await context.PostAsync(msg2);

                        var msg = context.MakeMessage();
                        msg.Type        = "message";
                        msg.Attachments = new List <Attachment>();
                        List <CardImage> cardImages = new List <CardImage>();
                        cardImages.Add(new CardImage(url: "https://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]?v=73d79a89bded&a"));
                        List <CardAction> cardButtons = new List <CardAction>();
                        CardAction        plButton    = new CardAction()
                        {
                            Value = soResult.Link,
                            Type  = "openUrl",
                            Title = soResult.Title
                        };
                        cardButtons.Add(plButton);
                        ThumbnailCard plCard = new ThumbnailCard()
                        {
                            Title    = soResult.Title,
                            Subtitle = "Please click me for more information!",
                            Images   = cardImages,
                            Buttons  = cardButtons
                        };
                        Attachment plAttachment = plCard.ToAttachment();
                        msg.Attachments.Add(plAttachment);

                        //  "attachments": [
                        //  {
                        //    "contentType": "application/vnd.microsoft.card.thumbnail",
                        //    "content": {
                        //      "title": "I'm a thumbnail card",
                        //      "subtitle": "Please visit my site.",
                        //      "images": [
                        //        {
                        //          "url": "https://mydeploy.azurewebsites.net/matsu.jpg"
                        //        }
                        //      ],
                        //      "buttons": [
                        //        {
                        //          "type": "openUrl",
                        //          "title": "Go to my site",
                        //          "value": "https://blogs.msdn.microsoft.com/tsmatsuz"
                        //        }
                        //      ]
                        //    }
                        //  }
                        //]

                        await context.PostAsync(msg);
                    }
                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "Greeting":
                {
                    var rand = new Random();
                    resultString = Greetings[rand.Next(0, Greetings.Length)];
                    await context.PostAsync(resultString);

                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "xkcd":
                {
                    var reply     = context.MakeMessage();
                    var imgString = string.Empty;
                    if (luisResult.entities.Any())
                    {
                        imgString = await XkcdLib.GetComic(luisResult.entities[0].entity);
                    }
                    else
                    {
                        imgString = await XkcdLib.GetRandomComic();
                    }

                    reply.Attachments = new List <Attachment>
                    {
                        new Attachment()
                        {
                            ContentUrl  = imgString,
                            ContentType = "image/jpg",
                            Name        = $"{Guid.NewGuid()}.jpg"
                        }
                    };

                    await context.PostAsync(reply);

                    context.Wait(MessageReceivedAsync);
                    break;
                }

                case "OrderPizza":
                {
                    //await context.PostAsync($"Hmm would you like to order pizza?");
                    _pizzaFlow = true;
                    PromptDialog.Text(context, Resume, "Hmm would you like to order pizza?", "Didn't get that!");

                    break;
                }

                default:
                {
                    await context.PostAsync(resultString);

                    context.Wait(MessageReceivedAsync);
                    break;
                }
                }
            }
        }
예제 #17
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task StartAsync(IDialogContext context)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            PromptDialog.Confirm(context, AfterConfirming_OpenWorkbook, $"I don't have a workbook open. Do you want me to open a workbook?");
        }
예제 #18
0
 private async Task SelectedConfirm(IDialogContext context)
 {
     PromptDialog.Confirm(context, Confirmed, "¿Desea buscar a otro colaborador?");
 }
예제 #19
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;
            var msgText = message.RemoveRecipientMention().Replace("\n", "").TrimEnd().TrimStart();

            if (msgText == "reset")
            {
                PromptDialog.Confirm(
                    context,
                    AfterResetAsync,
                    "Are you sure you want to reset the count?",
                    "Didn't get that!",
                    promptStyle: PromptStyle.Auto);
            }
            else if (msgText.Equals("auth"))
            {
                // Initialize AuthenticationOptions and forward to AuthDialog for token
                AuthenticationOptions options = new AuthenticationOptions()
                {
                    Authority       = "https://login.microsoftonline.com/common",
                    ClientId        = "cfca18bf-9031-4fea-9e83-3a19848a3489",
                    ClientSecret    = "qWST866]%nusgggVUDV67_-",
                    Scopes          = new string[] { "User.ReadWrite" },
                    RedirectUrl     = "https://hack005.ngrok.io/callback",
                    MagicNumberView = "/magic.html#{0}"
                };

                await context.Forward(new AuthDialog(new MSALAuthProvider(), options), async (IDialogContext authContext, IAwaitable <AuthResult> authResult) =>
                {
                    var result = await authResult;
                    WebApiApplication.UserTokens.TryAdd(authContext.Activity.From.Id, result.AccessToken);

                    // Use token to call into service
                    var json = await new HttpClient().GetWithAuthAsync(result.AccessToken, "https://graph.microsoft.com/v1.0/me");
                    await authContext.PostAsync($"I'm a simple bot that doesn't do much, but I know your name is {json.Value<string>("displayName")} " +
                                                $"and your UPN is {json.Value<string>("userPrincipalName")}");
                }, message, CancellationToken.None);
            }
            else if (msgText.Equals("question"))
            {
                using (var _client = new HttpClient())
                {
                    var questionR = await _client.PostAsJsonAsync("https://msopenhackeu.azurewebsites.net/api/trivia/question", new
                    {
                        id = ((Activity)message).From.Properties.GetValue("aadObjectId")
                    });

                    var r = await questionR.Content.ReadAsAsync <QuestionDto>();

                    var opt = r.QuestionOptions.Select(x => new QuestionChoicesDto()
                    {
                        Id         = x.Id,
                        Value      = x.Text,
                        QuestionId = r.Id
                    }).ToList();

                    var promptOptions = new PromptOptions <QuestionChoicesDto>(r.Text, options: opt);

                    PromptDialog.Choice(context, OnQuestionAnsweredAsync, promptOptions);
                }
            }
            else
            {
                await context.PostAsync($"{this.count++}: You said {message.Text}");

                context.Wait(MessageReceivedAsync);
            }
        }
예제 #20
0
        async Task IDialog <object> .StartAsync(IDialogContext context)
        {
            await context.PostAsync($"The alarm with title '{this.title}' is alarming");

            PromptDialog.Confirm(context, AfterPromptForSnoozing, "Do you want to snooze this alarm?");
        }
예제 #21
0
 public async Task PromptSuccess_Confirm_No()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText), "no", false);
 }
예제 #22
0
 public async Task ResetCode(IDialogContext context, IActivity activity)
 {
     PromptDialog.Confirm(context, AfterResetPrompt, "Are you sure you want to clear you Azure trial code?");
 }
예제 #23
0
 public async Task PromptFailure_Confirm()
 {
     await PromptFailureAsync <bool>((context, resume) => PromptDialog.Confirm(context, resume, PromptText, RetryText, MaximumAttempts));
 }
예제 #24
0
        public async Task StartAsync(IDialogContext context)
        {
            await context.PostAsync(_message);

            PromptDialog.Confirm(context, Resume, "Are u ok?");
        }
예제 #25
0
 private async Task SelectedConfirm(IDialogContext context)
 {
     PromptDialog.Confirm(context, Confirmed, "¿Te puedo ayudar en algo más?");
 }
            protected virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
            {
                var nextPromptIdx = 0;

                var validationResults = default(ICollection <ValidationResult>);

                this.luisAction.IsValid(out validationResults);

                if (item != null)
                {
                    var message = await item;

                    var paramName  = validationResults.First().MemberNames.First();
                    var paramValue = message.Text;

                    var result = await LuisActionResolver.QueryValueFromLuisAsync(this.luisService, this.luisAction, paramName, paramValue, context.CancellationToken);

                    if (result.Succeed)
                    {
                        nextPromptIdx++;
                    }
                    else if (!string.IsNullOrWhiteSpace(result.NewIntent) && result.NewAction != null)
                    {
                        var currentActionDefinition = LuisActionResolver.GetActionDefinition(this.luisAction);

                        var isContextual = false;
                        if (LuisActionResolver.IsValidContextualAction(result.NewAction, this.luisAction, out isContextual))
                        {
                            var executionContextChain = new List <ActionExecutionContext> {
                                new ActionExecutionContext(result.NewIntent, result.NewAction)
                            };

                            var childDialog = new LuisActionMissingEntitiesDialog(this.luisService, executionContextChain);

                            context.Call(childDialog, this.AfterContextualActionFinished);

                            return;
                        }
                        else if (isContextual & !LuisActionResolver.IsContextualAction(this.luisAction))
                        {
                            var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);

                            await context.PostAsync($"Cannot execute action '{newActionDefinition.FriendlyName}' in the context of '{currentActionDefinition.FriendlyName}' - continuing with current action");
                        }
                        else if (!this.luisAction.GetType().Equals(result.NewAction.GetType()))
                        {
                            var newActionDefinition = LuisActionResolver.GetActionDefinition(result.NewAction);

                            var valid = LuisActionResolver.UpdateIfValidContextualAction(result.NewAction, this.luisAction, out isContextual);
                            if (!valid && isContextual)
                            {
                                await context.PostAsync($"Cannot switch to action '{newActionDefinition.FriendlyName}' from '{currentActionDefinition.FriendlyName}' due to invalid context - continuing with current action");
                            }
                            else if (currentActionDefinition.ConfirmOnSwitchingContext)
                            {
                                // serialize overrun info
                                this.overrunData = result;

                                PromptDialog.Confirm(
                                    context,
                                    this.AfterOverrunCurrentActionSelected,
                                    $"Do you want to discard the current action '{currentActionDefinition.FriendlyName}' and start executing '{newActionDefinition.FriendlyName}' action?");

                                return;
                            }
                            else
                            {
                                this.intentName = result.NewIntent;
                                this.luisAction = result.NewAction;

                                this.luisAction.IsValid(out validationResults);
                            }
                        }
                    }
                }

                if (validationResults.Count > nextPromptIdx)
                {
                    await context.PostAsync(validationResults.ElementAt(nextPromptIdx).ErrorMessage);

                    context.Wait(this.MessageReceivedAsync);
                }
                else
                {
                    context.Done(new ActionExecutionContext(this.intentName, this.luisAction));
                }
            }
예제 #27
0
 public async Task Reset(IDialogContext context, IActivity activity)
 {
     PromptDialog.Confirm(context, AfterResetAsync,
                          "Are you sure you want to reset the count?",
                          "Didn't get that!");
 }
예제 #28
0
        public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;


            message.Text = message.Text.Replace(" ", "+");

            if (message.Text.Length == 4 && (message.Text.Substring(0, 4).ToLower() == "game"))
            {
                Random random = new Random();
                in_game = true;

                l   = 1;
                h   = 100;
                num = random.Next(l, h + 1);

                await context.PostAsync($"{this.count++}: I know a game! Let's play guess a number: I'm thinking of a number between " + l + " and " +
                                        h + ". Take a guess!");

                context.Wait(MessageReceivedAsync);
            }
            else if (in_game)
            {
                int guess;
                if (Int32.TryParse(message.Text, out guess))
                {
                    if (guess < num)
                    {
                        await context.PostAsync($"{this.count++}: Guess is too low.");

                        context.Wait(MessageReceivedAsync);
                    }
                    else if (guess > num)
                    {
                        await context.PostAsync($"{this.count++}: Guess is too high.");

                        context.Wait(MessageReceivedAsync);
                    }
                    else
                    {
                        in_game = false;
                        await context.PostAsync($"{this.count++}: You win!.");

                        context.Wait(MessageReceivedAsync);
                    }
                }
                else if (message.Text.Length > 9 && (message.Text.Substring(0, 9).ToLower() == "quit+game"))
                {
                    in_game = false;
                    context.Wait(MessageReceivedAsync);
                }
                else
                {
                    await context.PostAsync($"{this.count++}: Please enter a guess or \"Quit Game\" to quit.");

                    context.Wait(MessageReceivedAsync);
                }
            }
            else if (message.Text == "reset")
            {
                PromptDialog.Confirm(
                    context,
                    AfterResetAsync,
                    "Are you sure you want to reset the count?",
                    "Didn't get that!",
                    promptStyle: PromptStyle.Auto);
            }
            else if (message.Text.Length > 7 && (message.Text.Substring(0, 6).ToLower() == "google" || message.Text.Substring(0, 6).ToLower() == "search"))
            {
                await context.PostAsync($"{this.count++}: http://lmgtfy.com/?q={message.Text.Substring(7)}");

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text.Length > 5 && (message.Text.Substring(0, 4).ToLower() == "bing"))
            {
                await context.PostAsync($"{this.count++}: http://lmgtfy.com/?s=b&q={message.Text.Substring(5)}");

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text.Length > 6 && (message.Text.Substring(0, 5).ToLower() == "yahoo"))
            {
                await context.PostAsync($"{this.count++}: http://lmgtfy.com/?s=y&q={message.Text.Substring(6)}");

                context.Wait(MessageReceivedAsync);
            }
            else if (message.Text.Length > 5 && (message.Text.Substring(0, 4).ToLower() == "duck"))
            {
                await context.PostAsync($"{this.count++}: http://lmgtfy.com/?s=d&q={message.Text.Substring(5)}");

                context.Wait(MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync($"{this.count++}: Search using \"Search\" or \"Google\" or \"Bing\" or \"Yahoo\" or \"Duck\".");

                context.Wait(MessageReceivedAsync);
            }
        }
예제 #29
0
 public async Task PromptSuccess_Confirm_Yes_CaseInsensitive()
 {
     await PromptSuccessAsync((context, resume) => PromptDialog.Confirm(context, resume, PromptText, promptStyle: PromptStyle.None), "Yes", true);
 }
예제 #30
0
        public async Task CreateOrder(IDialogContext context, IAwaitable <IMessageActivity> message, LuisResult result)
        {
            if (!await CheckForWelcome(context, message))
            {
                EntityRecommendation productRecommendation = null;
                if (result != null)
                {
                    result.TryFindEntity(EntityProductName, out productRecommendation);
                }
                var msg = await message;

                var product = result != null ? productRecommendation?.Entity : msg.Text;
                if (!string.IsNullOrWhiteSpace(product))
                {
                    if (!MemoryStorage.Products.Any(p => p.Name.ToLower().Contains(product.ToLower())))
                    {
                        await context.PostAsync($"Lo sentimos, el producto *{product}* no se encuentra en stock.");

                        context.Done <object>(null);
                    }
                    else
                    {
                        var selectedProduct =
                            MemoryStorage.Products.First(p => p.Name.ToLower().Contains(product.ToLower()));

                        PromptDialog.Confirm(
                            context,
                            AfterConfirmation,
                            $"**Confirmación pedido** \n\n" +
                            $"¿Desea comprar el producto *{selectedProduct.Name}* por un precio de **{selectedProduct.Price}€**?",
                            options: new[] { "Sí", "No" }, patterns: new string[][] { new[] { "Sí", "Confirmar", "Aceptar", "sí", "confirmar", "aceptar" }, new[] { "No", "Cancelar", "Atrás", "no", "cancelar", "atrás" } });

                        _currentOrder = new Order()
                        {
                            Product = selectedProduct.Name,
                            Date    = DateTime.Now,
                            Price   = selectedProduct.Price
                        };
                    }
                }
                else
                {
                    var reply = context.MakeMessage();
                    reply.Text             = "¿Qué te gustaría comprar? \n\n Tenemos los siguientes productos en stock:";
                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    reply.Attachments      = new List <Attachment>();

                    foreach (var stockProduct in MemoryStorage.Products)
                    {
                        List <CardAction> cardButtons = new List <CardAction>();

                        CardAction plButton = new CardAction()
                        {
                            Value = $"comprar {stockProduct.Name}",
                            Type  = "postBack",
                            Title = "Comprar"
                        };

                        cardButtons.Add(plButton);

                        byte[] imageBytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Content/" + stockProduct.Image));

                        ThumbnailCard plCard = new ThumbnailCard()
                        {
                            Title    = stockProduct.Name,
                            Subtitle = stockProduct.Price + "€",
                            Text     = stockProduct.Description,
                            Images   = new List <CardImage>()
                            {
                                new CardImage()
                                {
                                    Url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
                                }
                            },
                            Buttons = cardButtons
                        };

                        Attachment plAttachment = plCard.ToAttachment();
                        reply.Attachments.Add(plAttachment);
                    }

                    await context.PostAsync(reply, CancellationToken.None);

                    context.Done <object>(null);
                }
            }
        }