public async Task SendCardAsync(AdaptiveCard card, ITurnContext <IMessageActivity> turnContext)
 {
     card.Version = "1.0";
     var attachment = MessageFactory.Attachment(new Attachment("application/vnd.microsoft.card.adaptive", content: card));
     await turnContext.SendActivityAsync(attachment);
 }
Example #2
0
        public async static Task <bool> GetMatchedAndNotmachet(ITurnContext turnContext, CancellationToken cancellationToken, IConfiguration config)
        {
            turnContext.Activity.Text = turnContext.Activity.Text.Replace(("1qq1_"), "");
            string dishName = turnContext.Activity.Text.Substring(0, turnContext.Activity.Text.LastIndexOf("_"));

            turnContext.Activity.Text = turnContext.Activity.Text.Remove(0, turnContext.Activity.Text.LastIndexOf('_') + 1);
            IEnumerable <string> ingridients = turnContext.Activity.Text.Split(';').ToList();

            List <Matched> MachedList = new List <Matched>();
            string         Message    = "";



            Dish dish   = new Dish();
            var  client = new HttpClient();

            client.BaseAddress = new Uri(config.GetValue <string>("ConnectionStrings"));
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var danie = client.GetAsync($"/api/recipies/GetDishByName/{dishName}").Result.Content.ReadAsStringAsync();

            dish = System.Text.Json.JsonSerializer.Deserialize <Dish>(danie.Result);
            var           nonRepeat = dish.ingridients.Select(x => x.name).Distinct();
            List <string> noH2      = new List <string>();
            string        j         = "";

            foreach (var i in nonRepeat)
            {
                if ((i.Contains("<h2>")) || (i.Contains("</h2>")))
                {
                    j = i.Replace("<h2>", ("\n\n**")).Replace("</h2>", ("**\n\n"));;
                    noH2.Add(j);
                }
                else
                {
                    j = i;
                    noH2.Add(j);
                }
            }

            foreach (var item2 in noH2)
            {
                foreach (var item3 in ingridients)
                {
                    if (item3 != "")
                    {
                        Matched matched = new Matched();

                        if (item2.StartsWith(item3))
                        {
                            matched.Name      = item2;
                            matched.isMatched = true;
                            MachedList.Add(matched);
                        }
                        else
                        {
                            matched.Name      = item2;
                            matched.isMatched = false;
                            MachedList.Add(matched);
                        }
                    }
                }
            }

            foreach (var i in MachedList)
            {
                if (i.isMatched)
                {
                    Message += "**" + i.Name + "**\n\n";
                }
                else
                {
                    Message += i.Name + "\n\n";
                }
            }


            Attachment imp = new Attachment();

            imp.ContentType = "image/png";
            imp.ContentUrl  = (dish.pictUrl);
            imp.Name        = dish.name;
            var rep = MessageFactory.Attachment(imp);

            string listOfIng = string.Join("\n\n", dish.ingridients.Select(p => p.name).Distinct().ToList());

            listOfIng = listOfIng.Replace("<h2>", ("\n\n**")).Replace("</h2>", ("**\n\n"));


            await turnContext.SendActivityAsync(rep);

            await turnContext.SendActivityAsync((dish.name.ToString() + "\n\n " + "Czas przygotowania: " + dish.timeForPrepare.ToString() + "minut" + "\n" + "\n" + dish.description.ToString().Replace("  ", "") + "\n\n" + Message + "\n \n" + dish.directions1.ToString().Replace("<p style=\"text - align: justify;\">", " ")
                                                 + "\n\n" + dish.directions2.ToString().Replace("<p style=\"text - align: justify;\">", " ") + "\n\n" + dish.directions3.ToString().Replace("<p style=\"text - align: justify;\">", " ") + "\n\n" + dish.directions4.ToString().Replace("<p style=\"text - align: justify;\">", " ")));

            return(true);
        }
        public void AttachmentMultipleNull()
        {
            IMessageActivity message = MessageFactory.Attachment((IList <Attachment>)null);

            Assert.Fail("Exception not thrown");
        }
Example #4
0
        // Send a Rich Card response to the user based on their choice.
        // This method is only called when a valid prompt response is parsed from the user's response to the ChoicePrompt.
        private async Task <DialogTurnResult> ShowCardStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            _logger.LogInformation("MainDialog.ShowCardStepAsync");

            // Cards are sent as Attachments in the Bot Framework.
            // So we need to create a list of attachments for the reply activity.
            var attachments = new List <Attachment>();

            // Reply to the activity we received with an activity.
            var reply = MessageFactory.Attachment(attachments);

            // Decide which type of card(s) we are going to show the user
            switch (((FoundChoice)stepContext.Result).Value)
            {
            case "Adaptive Card":
                // Display an Adaptive Card
                reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
                break;

            case "Hero Card":
                // Display a HeroCard.
                reply.Attachments.Add(Cards.GetHeroCard().ToAttachment());
                break;

            //case "OAuth Card":
            //    // Display an OAuthCard
            //    reply.Attachments.Add(Cards.GetOAuthCard().ToAttachment());
            //    break;
            //case "Receipt Card":
            //    // Display a ReceiptCard.
            //    reply.Attachments.Add(Cards.GetReceiptCard().ToAttachment());
            //    break;
            //case "Signin Card":
            //    // Display a SignInCard.
            //    reply.Attachments.Add(Cards.GetSigninCard().ToAttachment());
            //    break;
            //case "Thumbnail Card":
            //    // Display a ThumbnailCard.
            //    reply.Attachments.Add(Cards.GetThumbnailCard().ToAttachment());
            //    break;
            //case "Video Card":
            //    // Display a VideoCard
            //    reply.Attachments.Add(Cards.GetVideoCard().ToAttachment());
            //    break;
            default:
                // Display a carousel of all the rich card types.
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments.Add(Cards.CreateAdaptiveCardAttachment());
                //reply.Attachments.Add(Cards.GetAnimationCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetAudioCard().ToAttachment());
                reply.Attachments.Add(Cards.GetHeroCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetOAuthCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetReceiptCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetSigninCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetThumbnailCard().ToAttachment());
                //reply.Attachments.Add(Cards.GetVideoCard().ToAttachment());
                break;
            }

            // Send the card(s) to the user as an attachment to the activity
            await stepContext.Context.SendActivityAsync(reply, cancellationToken);

            // Give the user instructions about what to do next
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Type anything to see another card."), cancellationToken);

            return(await stepContext.EndDialogAsync());
        }
Example #5
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var     txt = turnContext.Activity.Text;
            dynamic val = turnContext.Activity.Value;

            // Check if the activity came from a submit action
            if (string.IsNullOrEmpty(txt) && val != null)
            {
                JToken resultToken = JToken.Parse(turnContext.Activity.Value.ToString());
                if (null != resultToken["Action"] && "languageselector" == resultToken["Action"].Value <string>())
                {
                    var selectedLang = resultToken["choiceset"].Value <string>();
                    var attachment   = Cards.GetCard(selectedLang, CardType.Intro);
                    if (attachment != null)
                    {
                        var reply = MessageFactory.Attachment(attachment);
                        await turnContext.SendActivityAsync(reply, cancellationToken);
                    }
                    else // debug;
                    {
                        //await turnContext.SendActivityAsync(s_ErrorMsg);
                    }
                }
                else if (null != resultToken["Consent"] && 1 == resultToken["Consent"].Value <int>())
                {
                    var lang       = resultToken["Language"].Value <string>();
                    var attachment = Cards.GetCard(lang, CardType.AfterAgreeing);
                    if (attachment != null)
                    {
                        var reply = MessageFactory.Attachment(attachment);
                        await turnContext.SendActivityAsync(reply, cancellationToken);
                    }
                    else // debug;
                    {
                        //await turnContext.SendActivityAsync(s_ErrorMsg);
                    }
                }
                else if (Util.IsRequestingUserFeedback)
                {
                    if (null != resultToken["helpful"])
                    {
                        var    helpful  = resultToken["helpful"].Value <int>();
                        var    language = resultToken["language"].Value <string>();
                        string msg      = "";
                        if (1 == helpful)
                        {
                            msg = Util.GetMessageAfterFeedbackHelpful(language);
                        }
                        else if (0 == helpful)
                        {
                            msg = Util.GetMessageAfterFeedbackNotHelpful(language);
                        }
                        await turnContext.SendActivityAsync(msg);

                        var question           = resultToken["question"].Value <string>();
                        var answer             = resultToken["answer"].Value <string>();
                        var translatedQuestion = resultToken["translatedQuestion"].Value <string>();
                        var translatedAnswer   = resultToken["translatedAnswer"].Value <string>();
                        var langRecord         = resultToken["language"].Value <string>();
                        await Util.RecordQuestionAnswerFeedback(
                            BotServices.TableDbConnectionString,
                            question,
                            answer,
                            translatedQuestion,
                            translatedAnswer,
                            helpful,
                            langRecord);
                    }
                }
            }
            else
            {
                await Dialog.RunAsync(turnContext, ConversationState.CreateProperty <DialogState>(nameof(DialogState)), cancellationToken);
            }
        }
Example #6
0
        private async Task <DialogTurnResult> AddToppingStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            stepContext.Values["menu"] = ((FoundChoice)stepContext.Result).Value;

            var attachments = new List <Attachment>();

            //치즈 카드 보여주기
            var cheeseReply = MessageFactory.Attachment(attachments);

            cheeseReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            var cheeseMsg = MessageFactory.Text("치즈 종류입니다");

            for (int i = 1; i <= 3; i++)
            {
                cheeseReply.Attachments.Add(Cards.GetCheeseCard(i).ToAttachment());
            }
            await stepContext.Context.SendActivityAsync(cheeseMsg, cancellationToken);

            await stepContext.Context.SendActivityAsync(cheeseReply, cancellationToken);

            //소스 카드 보여주기
            var sauceReply = MessageFactory.Attachment(attachments);

            sauceReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            var sauceMsg = MessageFactory.Text("소스 종류입니다");

            for (int i = 1; i <= 15; i++)
            {
                sauceReply.Attachments.Add(Cards.GetSauceCard(i).ToAttachment());
            }
            await stepContext.Context.SendActivityAsync(sauceMsg, cancellationToken);

            await stepContext.Context.SendActivityAsync(sauceReply, cancellationToken);

            //추가 토핑 카드 보여주기
            var toppingReply = MessageFactory.Attachment(attachments);

            toppingReply.AttachmentLayout = AttachmentLayoutTypes.Carousel;

            var toppingMsg = MessageFactory.Text("추가 토핑 종류입니다");

            for (int i = 1; i <= 9; i++)
            {
                toppingReply.Attachments.Add(Cards.GetToppingCard(i).ToAttachment());
            }
            await stepContext.Context.SendActivityAsync(toppingMsg, cancellationToken);

            await stepContext.Context.SendActivityAsync(toppingReply, cancellationToken);

            //야채 카드 보여주기

            //입력 tip
            var tipMsg = MessageFactory.Text("[입력 TIP] \r\n- 기본적으로 모든 야채가 추가되어 있습니다.\r\n- 제외할 토핑은 '-'(빼기)와 토핑이름을 입력하면 추가되어 있던 토핑이 빠집니다.\r\n- 많이 넣고 싶은 토핑은 토핑이름을 입력하면 토핑이 추가됩니다.\r\n- '토핑종류'를 입력하면 토핑 카드를 다시 보여줍니다.\r\n- '완성'을 입력하면 토핑추가가 종료됩니다.\r\n- '?','가이드','help'를 입력하면 입력 TIP이 다시 출력됩니다.");
            await stepContext.Context.SendActivityAsync(tipMsg, cancellationToken);

            //현재 샌드위치 상태
            var orderData = await _orderDataAccessor.GetAsync(stepContext.Context, () => new OrderData(), cancellationToken);

            orderData.Menu  = (string)stepContext.Values["menu"];
            orderData.Bread = (string)stepContext.Values["bread"];

            var Sandwich = $"[현재 샌드위치 상태] \r\n{orderData.Bread}\r\n{orderData.Menu}\r\n";

            for (int i = 0; i < orderData.Vege.Length; i++)
            {
                Sandwich += $"{orderData.Vege[i]} ";
            }
            Sandwich += $"\r\n{orderData.Bread}";
            var promptOptions = new PromptOptions {
                Prompt = MessageFactory.Text(Sandwich)
            };

            return(await stepContext.PromptAsync(nameof(TextPrompt), promptOptions, cancellationToken));

            //return await stepContext.ReplaceDialogAsync(nameof(ReviewSelectionDialog), list, cancellationToken);
        }
Example #7
0
        /// <inheritdoc/>
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            try
            {
                await this.SendTypingIndicatorAsync(turnContext);

                var    conversationType = turnContext.Activity.Conversation.ConversationType;
                string conversationId   = turnContext.Activity.Conversation.Id;

                if (string.Compare(conversationType, "groupChat", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (turnContext.Activity.Type.Equals(ActivityTypes.Message))
                    {
                        turnContext.Activity.RemoveRecipientMention();

                        switch (turnContext.Activity.Text.Trim().ToLower())
                        {
                        case Constants.Start:
                            this.telemetryClient.TrackTrace($"scrum {conversationId} started by {turnContext.Activity.From.Id}");

                            var scrum = await this.scrumProvider.GetScrumAsync(conversationId);

                            if (scrum != null && scrum.IsScrumRunning)
                            {
                                // check if member in scrum exists.
                                // A user is added during a running scrum and tries to start a new scrum.
                                var activityId = this.GetActivityIdToMatch(scrum.MembersActivityIdMap, turnContext.Activity.From.Id);
                                if (activityId == null)
                                {
                                    await turnContext.SendActivityAsync(string.Format(Resources.NoPartOfScrumStartText, turnContext.Activity.From.Name));

                                    this.telemetryClient.TrackTrace($"Member who is updating the scrum is not the part of scrum for : {conversationId}");
                                }
                                else
                                {
                                    this.telemetryClient.TrackTrace($"Scrum is already running for conversation id {conversationId}");
                                    await turnContext.SendActivityAsync(Resources.RunningScrumMessage);
                                }
                            }
                            else
                            {
                                // start a new scrum
                                this.telemetryClient.TrackTrace($"Scrum start for : {conversationId}");
                                await this.StartScrumAsync(turnContext, cancellationToken);
                            }

                            break;

                        case Constants.TakeATour:
                            var tourCards = TourCard.GetTourCards(this.configuration["AppBaseURL"]);
                            await turnContext.SendActivityAsync(MessageFactory.Carousel(tourCards));

                            break;

                        case Constants.CompleteScrum:
                            var scrumInfo = await this.scrumProvider.GetScrumAsync(conversationId);

                            if (scrumInfo.IsScrumRunning)
                            {
                                var activityId = this.GetActivityIdToMatch(scrumInfo.MembersActivityIdMap, turnContext.Activity.From.Id);

                                // check if member in scrum exists.
                                // A user is added during a running scrum and tries to complete the running scrum.
                                if (activityId == null)
                                {
                                    await turnContext.SendActivityAsync(string.Format(Resources.NoPartOfCompleteScrumText, turnContext.Activity.From.Name));

                                    this.telemetryClient.TrackTrace($"Member who is updating the scrum is not the part of scrum for : {conversationId}");
                                }
                                else
                                {
                                    var cardId   = scrumInfo.ScrumStartActivityId;
                                    var activity = MessageFactory.Attachment(ScrumCompleteCard.GetScrumCompleteCard());
                                    activity.Id           = cardId;
                                    activity.Conversation = turnContext.Activity.Conversation;
                                    await turnContext.UpdateActivityAsync(activity, cancellationToken);

                                    // Update the trail card
                                    var    dateString       = string.Format("{{{{TIME({0})}}}}", DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"));
                                    string cardTrailMessage = string.Format(Resources.ScrumCompletedByText, turnContext.Activity.From.Name, dateString);
                                    await this.UpdateTrailCard(cardTrailMessage, turnContext, cancellationToken);

                                    scrumInfo.IsScrumRunning       = false;
                                    scrumInfo.ThreadConversationId = conversationId;
                                    var savedData = await this.scrumProvider.SaveOrUpdateScrumAsync(scrumInfo);

                                    if (!savedData)
                                    {
                                        await turnContext.SendActivityAsync(Resources.ErrorMessage);

                                        return;
                                    }

                                    this.telemetryClient.TrackTrace($"Scrum completed by: {turnContext.Activity.From.Name} for {conversationId}");
                                }
                            }
                            else
                            {
                                await turnContext.SendActivityAsync(Resources.CompleteScrumErrorText);
                            }

                            break;

                        default:
                            await turnContext.SendActivityAsync(MessageFactory.Attachment(HelpCard.GetHelpCard()), cancellationToken);

                            break;
                        }
                    }
                }
                else
                {
                    await turnContext.SendActivityAsync(Resources.ScopeErrorMessage);
                }
            }
            catch (Exception ex)
            {
                this.telemetryClient.TrackTrace($"For {turnContext.Activity.Conversation.Id} : Message Activity failed: {ex.Message}");
                this.telemetryClient.TrackException(ex);
            }
        }
Example #8
0
 public void AttachmentNull()
 {
     Assert.Throws <ArgumentNullException>(() => MessageFactory.Attachment((Attachment)null));
 }
Example #9
0
 public void AttachmentMultipleNull()
 {
     Assert.Throws <ArgumentNullException>(() => MessageFactory.Attachment((IList <Attachment>)null));
 }
        /// <summary>
        /// When OnTurn method receives a submit invoke activity on bot turn, it calls this method.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="taskModuleRequest">Task module invoke request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents a task module response.</returns>
        protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken)
        {
            turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
            var activity = (Activity)turnContext.Activity;

            this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext);
            var valuesforTaskModule = JsonConvert.DeserializeObject <AdaptiveCardAction>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString());
            var editTicketDetail    = JsonConvert.DeserializeObject <TicketDetail>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString());

            switch (valuesforTaskModule.Command.ToUpperInvariant())
            {
            case Constants.UpdateRequestAction:
                var ticketDetail = await this.ticketDetailStorageProvider.GetTicketAsync(valuesforTaskModule.TicketId);

                if (TicketHelper.ValidateRequestDetail(editTicketDetail))
                {
                    ticketDetail.AdditionalProperties = CardHelper.ValidateAdditionalTicketDetails(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString(), turnContext.Activity.Timestamp.Value.Offset);

                    // Update request card with user entered values.
                    ticketDetail = TicketHelper.GetUpdatedTicketDetails(turnContext, ticketDetail, editTicketDetail);
                    bool result = await this.ticketDetailStorageProvider.UpsertTicketAsync(ticketDetail);

                    if (!result)
                    {
                        this.logger.LogError("Error in storing new ticket details in table storage.");
                        await turnContext.SendActivityAsync(this.localizer.GetString("AzureStorageErrorText"));

                        return(null);
                    }

                    // Send update audit trail message and request details card in personal chat and SME team.
                    this.logger.LogInformation($"Edited the ticket:{ticketDetail.TicketId}");
                    IMessageActivity smeEditNotification = MessageFactory.Text(string.Format(CultureInfo.InvariantCulture, this.localizer.GetString("SmeEditNotificationText"), ticketDetail.LastModifiedByName));

                    // Get card item element mappings
                    var cardElementMapping = await this.cardConfigurationStorageProvider.GetCardItemElementMappingAsync(ticketDetail.CardId);

                    IMessageActivity ticketDetailActivity = MessageFactory.Attachment(TicketCard.GetTicketDetailsForPersonalChatCard(cardElementMapping, ticketDetail, this.localizer, true));
                    ticketDetailActivity.Conversation = turnContext.Activity.Conversation;
                    ticketDetailActivity.Id           = ticketDetail.RequesterTicketActivityId;
                    await turnContext.UpdateActivityAsync(ticketDetailActivity);

                    await CardHelper.UpdateSMECardAsync(turnContext, ticketDetail, smeEditNotification, this.appBaseUrl, cardElementMapping, this.localizer, this.logger, cancellationToken);
                }
                else
                {
                    editTicketDetail.AdditionalProperties = CardHelper.ValidateAdditionalTicketDetails(additionalDetails: ((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString(), timeSpan: turnContext.Activity.Timestamp.Value.Offset);
                    return(CardHelper.GetEditTicketAdaptiveCard(cardConfigurationStorageProvider: this.cardConfigurationStorageProvider, ticketDetail: editTicketDetail, localizer: this.localizer, existingTicketDetail: ticketDetail));
                }

                break;

            case Constants.UpdateExpertListAction:
                var teamsChannelData = ((JObject)turnContext.Activity.ChannelData).ToObject <TeamsChannelData>();
                var expertChannelId  = teamsChannelData.Team == null ? this.teamId : teamsChannelData.Team.Id;
                if (expertChannelId != this.teamId)
                {
                    this.logger.LogInformation("Invalid team. Bot is not installed in this team.");
                    await turnContext.SendActivityAsync(this.localizer.GetString("InvalidTeamText"));

                    return(null);
                }

                var onCallExpertsDetail = JsonConvert.DeserializeObject <OnCallExpertsDetail>(JObject.Parse(taskModuleRequest?.Data?.ToString())?.ToString());
                await CardHelper.UpdateManageExpertsCardInTeamAsync(turnContext, onCallExpertsDetail, this.onCallSupportDetailSearchService, this.onCallSupportDetailStorageProvider, this.localizer);

                await ActivityHelper.SendMentionActivityAsync(onCallExpertsEmails : onCallExpertsDetail.OnCallExperts, turnContext : turnContext, logger : this.logger, localizer : this.localizer, cancellationToken : cancellationToken);

                this.logger.LogInformation("Expert List has been updated");
                return(null);

            case Constants.CancelCommand:
                return(null);
            }

            return(null);
        }
Example #11
0
        private async Task <DialogTurnResult> ActStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if (!_luisRecognizer.IsConfigured)
            {
                // LUIS is not configured, we just run the BookingDialog path with an empty BookingDetailsInstance.
                return(await stepContext.BeginDialogAsync(nameof(BookingDialog), new BookingDetails(), cancellationToken));
            }

            // Call LUIS and gather any potential booking details. (Note the TurnContext has the response to the prompt.)
            var luisResult = await _luisRecognizer.RecognizeAsync <FlightBooking>(stepContext.Context, cancellationToken);

            switch (luisResult.TopIntent().intent)
            {
            case FlightBooking.Intent.BookFlight:
                await ShowWarningForUnsupportedCities(stepContext.Context, luisResult, cancellationToken);

                // Initialize BookingDetails with any entities we may have found in the response.
                var bookingDetails = new BookingDetails()
                {
                    // Get destination and origin from the composite entities arrays.
                    Destination = luisResult.ToEntities.Airport,
                    Origin      = luisResult.FromEntities.Airport,
                    TravelDate  = luisResult.TravelDate,
                };

                // Run the BookingDialog giving it whatever details we have from the LUIS call, it will fill out the remainder.
                return(await stepContext.BeginDialogAsync(nameof(BookingDialog), bookingDetails, cancellationToken));

            case FlightBooking.Intent.GetWeather:
                // We haven't implemented the GetWeatherDialog so we just display a TODO message.
                var getWeatherMessageText = "TODO: get weather flow here";
                var getWeatherMessage     = MessageFactory.Text(getWeatherMessageText, getWeatherMessageText, InputHints.IgnoringInput);
                await stepContext.Context.SendActivityAsync(getWeatherMessage, cancellationToken);

                break;

            case FlightBooking.Intent.Introduction:
                await stepContext.Context.SendActivityAsync("Hi Jessica, It’s a pleasure to serve you.  May I please have the number that the account is associated with ?");

                break;

            case FlightBooking.Intent.SecondLevel:
                HeroCard secondlevel = new HeroCard()
                {
                    Text    = "Oh no problem. Can you please select the area in which you are looking help for?",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "Home Insurance", value: "Looking for Home Insurance"),
                        new CardAction(ActionTypes.PostBack, "Auto Insurance", value: "Looking for Auto Insurance"),
                        new CardAction(ActionTypes.PostBack, "Health Insurance ", value: "Looking for Health Insurance "),
                        new CardAction(ActionTypes.PostBack, "Others", value: "Looking for Others")
                    }
                };

                var secondlevelreply = MessageFactory.Attachment(secondlevel.ToAttachment());
                await stepContext.Context.SendActivityAsync(secondlevelreply, cancellationToken);

                break;

            case FlightBooking.Intent.HomeInsurance:
                await stepContext.Context.SendActivityAsync("Wonderful.I’d be happy to help you with that.  I’m here to help you find the best price for your home insurance. In order to proceed can you please help us with your Property location and Zip Code");

                break;

            case FlightBooking.Intent.Zipcode:
                await stepContext.Context.SendActivityAsync("Okay Jessica. Let me find the best rates for you.");

                await Task.Delay(3000);

                await stepContext.Context.SendActivityAsync("We have passed your requirement to our Actuary & Insurance-Advisor. Here is the details of the Insurance-Advisor assigned to help you with the Quote.");

                await Task.Delay(3000);

                await stepContext.Context.SendActivityAsync("Graham Smith has been assigned to assist you with your quote. He is reachable on +1 223.233.2341. He shall be getting back to you within 48 hrs.");

                HeroCard zipcode = new HeroCard()
                {
                    Text    = "Please select your preferred slot for the Insurance-Advisor to call you?",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "9 AM – 11 AM", value: "Time Slot is 9 to 11"),
                        new CardAction(ActionTypes.PostBack, "2 PM – 4 PM", value: "Time Slot is 9 to 11"),
                        new CardAction(ActionTypes.PostBack, "5 PM – 6 PM", value: "Time Slot is 9 to 11 "),
                        new CardAction(ActionTypes.PostBack, "6 PM - 7 PM", value: "Time Slot is 9 to 11")
                    }
                };

                var zipcodereply = MessageFactory.Attachment(zipcode.ToAttachment());
                await stepContext.Context.SendActivityAsync(zipcodereply, cancellationToken);

                break;

            case FlightBooking.Intent.Timeslot:
                await stepContext.Context.SendActivityAsync("Thanks Jessica for selecting the morning slot of 9 AM – 11 AM. We look forward to help you with the best quotation for insuring your house.");

                await stepContext.Context.SendActivityAsync("While we are there..");

                HeroCard timeslot = new HeroCard()
                {
                    Text    = "Well, we provide auto insurance to over 10 million drivers each year and have saved them an average of $500 by bundling their home and auto insurance.  Would you be interested in saving an extra 20% today??",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "YES", value: "Only Auto Insurance"),
                        new CardAction(ActionTypes.PostBack, "NO", value: "Both Home and Auto Insurance")
                    }
                };

                var timeslotreply = MessageFactory.Attachment(timeslot.ToAttachment());
                await stepContext.Context.SendActivityAsync(timeslotreply, cancellationToken);

                break;


            case FlightBooking.Intent.Homenauto:
                HeroCard Homenauto = new HeroCard()
                {
                    Text    = "Jessica, this week, we are running a multi policy discount . We believe you could save upto 30% in bundling your Home and Auto insurance? Would you like to know more?",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "YES", value: "Yes both Insurances."),
                        new CardAction(ActionTypes.PostBack, "NO", value: "Only home Insurance"),
                        new CardAction(ActionTypes.PostBack, "Get back to me later", value: "Get back to me later.")
                    }
                };

                var Homenautoreply = MessageFactory.Attachment(Homenauto.ToAttachment());
                await stepContext.Context.SendActivityAsync(Homenautoreply, cancellationToken);

                break;

            case FlightBooking.Intent.Model:
                HeroCard Model = new HeroCard()
                {
                    Text    = "Thanks Jessica .What maker of the car do you want to insure ?",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "Ferrari", value: "Car Models"),
                        new CardAction(ActionTypes.PostBack, "BMW", value: "Car Models"),
                        new CardAction(ActionTypes.PostBack, "KIA", value: "Car Models"),
                        new CardAction(ActionTypes.PostBack, "Others", value: "Car Models")
                    }
                };

                var Modelreply = MessageFactory.Attachment(Model.ToAttachment());
                await stepContext.Context.SendActivityAsync(Modelreply, cancellationToken);

                break;

            case FlightBooking.Intent.Year:
                HeroCard Year = new HeroCard()
                {
                    Text    = "Can you please select the period of Manufacture",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "2018-19", value: "Manufacturing Year"),
                        new CardAction(ActionTypes.PostBack, "2016-18", value: "Manufacturing Year"),
                        new CardAction(ActionTypes.PostBack, "2014-16", value: "Manufacturing Year"),
                        new CardAction(ActionTypes.PostBack, "Others", value: "Manufacturing Year")
                    }
                };

                var Yearreply = MessageFactory.Attachment(Year.ToAttachment());
                await stepContext.Context.SendActivityAsync(Yearreply, cancellationToken);

                break;

            case FlightBooking.Intent.Photocar:
                HeroCard Photocar = new HeroCard()
                {
                    Text    = "Do you have a photo of the car ?",
                    Buttons = new List <CardAction>
                    {
                        new CardAction(ActionTypes.PostBack, "YES", value: "Select yes to the car photo"),
                        new CardAction(ActionTypes.PostBack, "NO", value: "Select No")
                    }
                };

                var Photocarreply = MessageFactory.Attachment(Photocar.ToAttachment());
                await stepContext.Context.SendActivityAsync(Photocarreply, cancellationToken);

                break;

            case FlightBooking.Intent.Uploadnoncar:
                await stepContext.Context.SendActivityAsync("Please click the image upload button to select your image.");

                break;

            case FlightBooking.Intent.Sendoff:
                await stepContext.Context.SendActivityAsync("Thanks Jessica for the information, Let me append the request for this too. Our Insurance-Advisor shall help you assess your insurance requirement for the bundle. We look forward to be your partner to mitigate your risks.");

                await Task.Delay(3000);

                await stepContext.Context.SendActivityAsync("Just to affirm: Graham Smith (Reachable over +1 223.233.2341) shall be calling you tomorrow (23 March, 2020) between 9 AM – 11 AM to take the conversation further");

                await stepContext.Context.SendActivityAsync("Have a nice day.");

                break;

            default:
                // Catch all for unhandled intents
                var didntUnderstandMessageText = $"Sorry, I didn't get that. Please try asking in a different way (intent was {luisResult.TopIntent().intent})";
                var didntUnderstandMessage     = MessageFactory.Text(didntUnderstandMessageText, didntUnderstandMessageText, InputHints.IgnoringInput);
                await stepContext.Context.SendActivityAsync(didntUnderstandMessage, cancellationToken);

                break;
            }

            return(await stepContext.NextAsync(null, cancellationToken));
        }
        private static async Task TestAutoDeactivate(
            bool useChannelWithMessageUpdates,
            string autoDeactivateInAction,
            bool autoDeactivateInOptions)
        {
            const string ActionId = "action ID";

            var botState             = CreateUserState();
            var accessor             = botState.CreateProperty <CardManagerState>(nameof(CardManagerState));
            var middleware           = new CardManagerMiddleware(new CardManager(botState));
            var adapter              = new TestAdapter().Use(middleware);
            var expectedToDeactivate = autoDeactivateInAction == BehaviorSwitch.On ||
                                       (autoDeactivateInAction != BehaviorSwitch.Off && autoDeactivateInOptions);
            var expectedInStateBefore = !useChannelWithMessageUpdates;
            var expectedInQueueBefore = true;
            var expectedInStateAfter  = !(useChannelWithMessageUpdates || expectedToDeactivate);
            var expectedInQueueAfter  = !(useChannelWithMessageUpdates && expectedToDeactivate);
            var isInState             = false;
            var isInQueue             = false;
            var activitiesProcessed   = 0;

            var cardActivity = MessageFactory.Attachment(new HeroCard(buttons: new List <CardAction>
            {
                new CardAction(ActionTypes.PostBack, value: new Dictionary <string, object>
                {
                    { Behaviors.AutoDeactivate, autoDeactivateInAction },
                }.WrapLibraryData()),
            }).ToAttachment());

            var actionActivity = new Activity(value: new JObject
            {
                { Behaviors.AutoDeactivate, autoDeactivateInAction },
                { DataIdScopes.Action, ActionId },
            }.WrapLibraryData());

            if (useChannelWithMessageUpdates)
            {
                middleware.ChannelsWithMessageUpdates.Add(Channels.Test);
                middleware.UpdatingOptions.IdOptions.Set(DataIdScopes.Action, ActionId);
                middleware.UpdatingOptions.AutoDeleteOnAction = autoDeactivateInOptions;
            }
            else
            {
                middleware.NonUpdatingOptions.IdOptions.Set(DataIdScopes.Action, ActionId);
                middleware.NonUpdatingOptions.AutoDisableOnAction    = autoDeactivateInOptions;
                middleware.NonUpdatingOptions.AutoClearEnabledOnSend = false;
            }

            void AssertCard(bool expected, bool useState) => Assert.AreEqual(
                expected,
                useState ? isInState : isInQueue,
                $"Card activity {(expected ? "wasn't" : "was")} found in {(useState ? "state" : "queue")}");

            await new TestFlow(adapter, async(turnContext, cancellationToken) =>
            {
                if (turnContext.Activity.Value == null)
                {
                    await turnContext.SendActivityAsync(cardActivity);
                }

                var state = await accessor.GetNotNullAsync(turnContext, () => new CardManagerState());

                isInState = state.DataIdsByScope.TryGetValue(DataIdScopes.Action, out var set) && set.Contains(ActionId);
                isInQueue = adapter.ActiveQueue.Contains(cardActivity);

                activitiesProcessed++;

                await botState.SaveChangesAsync(turnContext);
            })
            .Send("hi")
            .Do(() => AssertCard(expectedInStateBefore, true))
            .Do(() => AssertCard(expectedInQueueBefore, false))
            .Send(actionActivity)
            .Do(() => AssertCard(expectedInStateAfter, true))
            .Do(() => AssertCard(expectedInQueueAfter, false))
            .StartTestAsync();

            Assert.AreEqual(2, activitiesProcessed);
        }
        /// <summary>
        /// Get the reply to a question asked by end user.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="message">Text message.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task GetQuestionAnswerReplyAsync(
            ITurnContext turnContext,
            IMessageActivity message)
        {
            string text = message.Text?.ToLower()?.Trim() ?? string.Empty;

            try
            {
                var queryResult = new QnASearchResultList();

                ResponseCardPayload payload = new ResponseCardPayload();

                if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null))
                {
                    payload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                }

                queryResult = await _qnaServiceProvider.GenerateAnswerAsync(question : text, isTestKnowledgeBase : false, payload.PreviousQuestions?.First().Id.ToString(), payload.PreviousQuestions?.First().Questions.First()).ConfigureAwait(false);

                if (queryResult.Answers.First().Id != -1)
                {
                    var answerData = queryResult.Answers.First();
                    payload.QnaPairId = answerData.Id ?? -1;

                    AnswerModel answerModel = new AnswerModel();

                    if (Validators.IsValidJSON(answerData.Answer))
                    {
                        answerModel = JsonConvert.DeserializeObject <AnswerModel>(answerData.Answer);
                    }

                    if (!string.IsNullOrEmpty(answerModel?.Title) || !string.IsNullOrEmpty(answerModel?.Subtitle) || !string.IsNullOrEmpty(answerModel?.ImageUrl) || !string.IsNullOrEmpty(answerModel?.RedirectionUrl))
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(MessagingExtensionQnaCard.GetEndUserRichCard(text, answerData, payload.QnaPairId))).ConfigureAwait(false);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(answerData, text, _appBaseUri, payload))).ConfigureAwait(false);
                    }

                    _telemetryClient.TrackEvent(
                        FaqPlusPlusBot.EVENT_ANSWERED_QUESTION_SINGLE,
                        new Dictionary <string, string>
                    {
                        { "QuestionId", payload.QnaPairId.ToString() },
                        { "QuestionAnswered", queryResult.Answers[0].Questions[0] },
                        { "QuestionAsked", text },
                        { "UserName", turnContext.Activity.From.Name },
                        { "UserAadId", turnContext.Activity.From?.AadObjectId ?? "" },
                        { "Product", _options.ProductName },
                    });
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                // Check if knowledge base is empty and has not published yet when end user is asking a question to bot.
                if (((Azure.CognitiveServices.Knowledge.QnAMaker.Models.ErrorResponseException)ex).Response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var knowledgeBaseId = await _configurationProvider.GetSavedEntityDetailAsync(Constants.KnowledgeBaseEntityId).ConfigureAwait(false);

                    var hasPublished = await _qnaServiceProvider.GetInitialPublishedStatusAsync(knowledgeBaseId).ConfigureAwait(false);

                    // Check if knowledge base has not published yet.
                    if (!hasPublished)
                    {
                        this._telemetryClient.TrackException(ex, new Dictionary <string, string> {
                            {
                                "message", "Error while fetching the qna pair: knowledge base may be empty or it has not published yet."
                            },
                        });
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text))).ConfigureAwait(false);

                        return;
                    }
                }

                // Throw the error at calling place, if there is any generic exception which is not caught.
                throw;
            }
        }
Example #14
0
        public async Task UpdateAsync([FromBody] MatchUpdatePayload payload)
        {
            var convoId = payload.ConversationId;

            IMessageActivity activity;

            if (string.IsNullOrEmpty(payload.Replay))
            {
                activity = MessageFactory.Text(payload.Message);
            }
            else
            {
                // HACK HACK HACK
                var content = gameUpdateTemplate
                              .Replace("${Title}", payload.Title)
                              .Replace("${Score}", payload.Score)
                              .Replace("${Message}", payload.Message)
                              .Replace("${Replay}", payload.Replay);

                activity = MessageFactory.Attachment(CreateAttachment(content));
            }

            var replacementContent = gameStartTemplate
                                     .Replace("${Title}", payload.Title)
                                     .Replace("${Score}", payload.Score);

            await client.Conversations.UpdateActivityAsync(convoId, convos[convoId], (Activity)MessageFactory.Attachment(CreateAttachment(replacementContent)));

            await client.Conversations.ReplyToActivityAsync(convoId, convos[convoId], (Activity)activity);
        }
Example #15
0
        // Handle adaptive card submit in channel
        // Updates the ticket status based on the user submission
        private async Task OnAdaptiveCardSubmitInChannelAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var payload = ((JObject)message.Value).ToObject <ChangeTicketStatusPayload>();

            this.telemetryClient.TrackTrace($"Received submit: ticketId={payload.TicketId} action={payload.Action}");

            // Get the ticket from the data store
            var ticket = await this.ticketsProvider.GetTicketAsync(payload.TicketId);

            if (ticket == null)
            {
                this.telemetryClient.TrackTrace($"Ticket {payload.TicketId} was not found in the data store");
                await turnContext.SendActivityAsync(MessageFactory.Text($"Ticket {payload.TicketId} was not found in the data store"));

                return;
            }

            // Update the ticket based on the payload
            switch (payload.Action)
            {
            case ChangeTicketStatusPayload.ReopenAction:
                ticket.Status             = (int)TicketState.Open;
                ticket.DateAssigned       = null;
                ticket.AssignedToName     = null;
                ticket.AssignedToObjectId = null;
                ticket.DateClosed         = null;
                break;

            case ChangeTicketStatusPayload.CloseAction:
                ticket.Status     = (int)TicketState.Closed;
                ticket.DateClosed = DateTime.UtcNow;
                break;

            case ChangeTicketStatusPayload.AssignToSelfAction:
                ticket.Status             = (int)TicketState.Open;
                ticket.DateAssigned       = DateTime.UtcNow;
                ticket.AssignedToName     = message.From.Name;
                ticket.AssignedToObjectId = message.From.AadObjectId;
                ticket.DateClosed         = null;
                break;

            default:
                this.telemetryClient.TrackTrace($"Unknown status command {payload.Action}", SeverityLevel.Warning);
                await turnContext.SendActivityAsync(MessageFactory.Text($"Unknown status command {payload.Action}"));

                return;
            }

            ticket.LastModifiedByName     = message.From.Name;
            ticket.LastModifiedByObjectId = message.From.AadObjectId;

            await this.ticketsProvider.SaveOrUpdateTicketAsync(ticket);

            this.telemetryClient.TrackTrace($"Ticket {ticket.TicketId} updated to status ({ticket.Status}, {ticket.AssignedToObjectId}) in store");

            // Update the card in the SME team
            var updateCardActivity = new Activity(ActivityTypes.Message)
            {
                Id           = ticket.SmeCardActivityId,
                Conversation = new ConversationAccount {
                    Id = ticket.SmeThreadConversationId
                },
                Attachments = new List <Attachment> {
                    new SmeTicketCard(ticket).ToAttachment(message.LocalTimestamp)
                },
            };
            var updateResponse = await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

            this.telemetryClient.TrackTrace($"Card for ticket {ticket.TicketId} updated to status ({ticket.Status}, {ticket.AssignedToObjectId}), activityId = {updateResponse.Id}");

            // Post update to user and SME team thread
            string           smeNotification  = null;
            IMessageActivity userNotification = null;

            switch (payload.Action)
            {
            case ChangeTicketStatusPayload.ReopenAction:
                smeNotification = string.Format(Resource.SMEOpenedStatus, message.From.Name);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.ReopenedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.ReopenedTicketUserNotification;
                break;

            case ChangeTicketStatusPayload.CloseAction:
                smeNotification = string.Format(Resource.SMEClosedStatus, ticket.LastModifiedByName);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.ClosedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.ClosedTicketUserNotification;
                break;

            case ChangeTicketStatusPayload.AssignToSelfAction:
                smeNotification = string.Format(Resource.SMEAssignedStatus, ticket.AssignedToName);

                userNotification         = MessageFactory.Attachment(new UserNotificationCard(ticket).ToAttachment(Resource.AssignedTicketUserNotification, message.LocalTimestamp));
                userNotification.Summary = Resource.AssignedTicketUserNotification;
                break;
            }

            if (smeNotification != null)
            {
                var smeResponse = await turnContext.SendActivityAsync(smeNotification);

                this.telemetryClient.TrackTrace($"SME team notified of update to ticket {ticket.TicketId}, activityId = {smeResponse.Id}");
            }

            if (userNotification != null)
            {
                userNotification.Conversation = new ConversationAccount {
                    Id = ticket.RequesterConversationId
                };
                var userResponse = await turnContext.Adapter.SendActivitiesAsync(turnContext, new Activity[] { (Activity)userNotification }, cancellationToken);

                this.telemetryClient.TrackTrace($"User notified of update to ticket {ticket.TicketId}, activityId = {userResponse.FirstOrDefault()?.Id}");
            }
        }
Example #16
0
        private async Task <DialogTurnResult> ShowCardStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            // Cards are sent as Attachments in the Bot Framework.
            // So we need to create a list of attachments for the reply activity.
            var attachments = new List <Attachment>(); //la variable en laque se guardaan las tarjetas para despues mostrarse

            // Reply to the activity we received with an activity.
            var reply = MessageFactory.Attachment(attachments); //la variable repl, que sera la encargada de mostrat los mensajes

            // Segun la opcion elegida, se despliegan las tarjetas corresponientes
            switch (((FoundChoice)stepContext.Result).Value)
            {
            case "Soda":
                // Display an Adaptive Card
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;     //le decimos que se envien en forma de carrucel
                ///reply.Attachments.Add(Cards.Cards.CreateAdaptiveCardAttachment()); //se añade al "carrucel" cada tarjeta, segun la bebida
                reply.Attachments.Add(Cards.Cards.mojitoCard());
                reply.Attachments.Add(Cards.Cards.Shirleytemple());
                reply.Attachments.Add(Cards.Cards.sanClementeCard());
                break;

            case "Jugo":
                // Display an AnimationCard.
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;     //le decimos que se envien en forma de carrucel
                //reply.Attachments.Add(Cards.Cards.CreateAdaptiveCardAttachment()); //se añade al "carrucel" cada tarjeta, segun la bebida
                reply.Attachments.Add(Cards.Cards.limonadaCard());
                reply.Attachments.Add(Cards.Cards.naranjadaCard());
                reply.Attachments.Add(Cards.Cards.Verde());
                //reply.Attachments.Add(Cards.GetAnimationCard().ToAttachment());
                break;

            case "Coctel":
                // Display an AudioCard
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments.Add(Cards.Cards.mojitoCard());
                reply.Attachments.Add(Cards.Cards.sanClementeCard());
                reply.Attachments.Add(Cards.Cards.Shirleytemple());
                reply.Attachments.Add(Cards.Cards.pinadaCard());
                break;

            case "Agua":
                // Display a HeroCard.
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;     //le decimos que se envien en forma de carrucel
                //reply.Attachments.Add(Cards.Cards.CreateAdaptiveCardAttachment()); //se añade al "carrucel" cada tarjeta, segun la bebida prueba 1
                reply.Attachments.Add(Cards.Cards.Jamaica());
                reply.Attachments.Add(Cards.Cards.Orchata());
                reply.Attachments.Add(Cards.Cards.frutas());
                //reply.Attachments.Add(Cards.GetHeroCard().ToAttachment());
                break;

            case "Café":
                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments.Add(Cards.Cards.Capuccino());
                reply.Attachments.Add(Cards.Cards.CafeExpresso());
                reply.Attachments.Add(Cards.Cards.CafeAmericano());
                break;

            default:
                return(await stepContext.ReplaceDialogAsync(nameof(MainDialog), null, cancellationToken));    //Regresar al dialogo principal en caso de seleccionar la opcion de volver

                break;
            }

            await stepContext.Context.SendActivityAsync(reply, cancellationToken); //se muestra el mensaje

            // Give the user instructions about what to do next
            await stepContext.Context.SendActivityAsync(MessageFactory.Text("Disfruta tu bebida"), cancellationToken);

            string status = "Gracias por usar Barman Bot, envia cualquier mensaje para comenzar de nuevo";
            await stepContext.Context.SendActivityAsync(status);

            return(await stepContext.EndDialogAsync()); //fin del dialogo se regresa al dialogo principal
        }
        private async Task <DialogTurnResult> showAdaptiveCardAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            if ((stepContext.Context.Activity.Text != null) || (stepContext.Context.Activity.Value != null))
            {
                // The token will be available in the Result property of the task.
                var tokenResponse = stepContext.Result as TokenResponse;

                List <Microsoft.Graph.User> users = new List <Microsoft.Graph.User>();
                var list = new List <Tuple <string, string> >();
                Dictionary <string, string> _teamsa = new Dictionary <string, string>();
                users = await OAuthHelpers.ListMeAsync(stepContext.Context, tokenResponse);

                try
                {
                    foreach (Microsoft.Graph.User u in users)
                    {
                        string dname = u.DisplayName;
                        string sname = u.Surname;
                        try
                        {
                            if (dname == null)
                            {
                                dname = "Test";
                            }
                            if (sname == null)
                            {
                                sname = "Test";
                            }
                        }
                        catch (Exception e) { }
                        //_teamsa.Add((JsonConvert.DeserializeObject(u.DisplayName.ToString())), (JsonConvert.DeserializeObject<Microsoft.Graph.User>(u.Surname.ToString())));
                        list.Add(Tuple.Create(dname, sname));
                        _teamsa.Add(dname, sname);
                    }
                }
                catch (Exception e)
                {
                    e.ToString();
                }
                List <string> _teamsType = new List <string>
                {
                    { "Public" },
                    { "Private" }
                };
                List <string> _teamsClassification = new List <string>
                {
                    { "Internal" },
                    { "External" },
                    { "Business" },
                    { "Protected" },
                    { "Important" },
                    { "Personal" }
                };

                //var choicesTeamOwners = _teamsa.Select(s => new AdaptiveChoice { Title = s.Key, Value = s.Key }).ToList();
                var choicesType = _teamsType.Select(s => new AdaptiveChoice {
                    Title = s, Value = s
                }).ToList();
                var choicesClassification = _teamsClassification.Select(s => new AdaptiveChoice {
                    Title = s, Value = s
                }).ToList();
                try
                {
                    var card = new AdaptiveCard
                    {
                        Version = new AdaptiveSchemaVersion(1, 0),
                        Body    =
                        {
                            new AdaptiveTextBlock("Team Name"),
                            new AdaptiveTextInput
                            {
                                Id = "Teamname",
                            },
                            new AdaptiveTextBlock("Description"),
                            new AdaptiveTextInput
                            {
                                Id = "Description",
                            },
                            new AdaptiveTextBlock("Team Owners"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesType,
                                Id            = "TeamOwners",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            },
                            new AdaptiveTextBlock("Type"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesType,
                                Id            = "Type",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            },
                            new AdaptiveTextBlock("Classification"),
                            new AdaptiveChoiceSetInput
                            {
                                Choices       = choicesClassification,
                                Id            = "Classification",
                                Style         = AdaptiveChoiceInputStyle.Compact,
                                IsMultiSelect = false
                            }
                        },
                        Actions = new List <AdaptiveAction>
                        {
                            new AdaptiveSubmitAction
                            {
                                Title = "Create Team",
                                Type  = "Action.Submit"
                            }
                        }
                    };

                    return(await stepContext.PromptAsync($"{ nameof(SiteRequestDialog)}.ShowCard",
                                                         new PromptOptions
                    {
                        // Choices = ChoiceFactory.ToChoices(_teamsa.Select(pair => pair.Value).ToList()),
                        Prompt = (Activity)MessageFactory.Attachment(new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(card))
                        })
                    },
                                                         cancellationToken));
                }
                catch (Exception e)
                { e.ToString(); }
                return(await stepContext.NextAsync());
            }
            else
            {
                return(await stepContext.EndDialogAsync());
            }
        }
Example #18
0
        /// <summary>
        /// Top level processing, is the user trying to check or change a setting?.
        /// </summary>
        /// <param name="sc">Step Context.</param>
        /// <param name="cancellationToken">Cancellation Token.</param>
        /// <returns>Dialog Turn Result.</returns>
        public async Task <DialogTurnResult> ProcessSetting(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var state = await Accessor.GetAsync(sc.Context);

            // Ensure we don't have state from a previous instantiation
            state.Changes.Clear();
            state.Entities.Clear();

            var luisResult = state.VehicleSettingsLuisResult;
            var topIntent  = luisResult?.TopIntent().intent;

            switch (topIntent.Value)
            {
            case Luis.VehicleSettings.Intent.VEHICLE_SETTINGS_CHANGE:
            case Luis.VehicleSettings.Intent.VEHICLE_SETTINGS_DECLARATIVE:

                // Process the LUIS result and add entities to the State accessors for ease of access
                if (luisResult.Entities.AMOUNT != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.AMOUNT), luisResult.Entities.AMOUNT);
                }

                if (luisResult.Entities.INDEX != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.INDEX), luisResult.Entities.INDEX);
                }

                if (luisResult.Entities.SETTING != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.SETTING), luisResult.Entities.SETTING);
                }

                if (luisResult.Entities.TYPE != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.TYPE), luisResult.Entities.TYPE);
                }

                if (luisResult.Entities.UNIT != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.UNIT), luisResult.Entities.UNIT);
                }

                if (luisResult.Entities.VALUE != null)
                {
                    state.Entities.Add(nameof(luisResult.Entities.VALUE), luisResult.Entities.VALUE);
                }

                // Perform post-processing on the entities, if it's declarative we indicate for special processing (opposite of the condition they've expressed)
                settingFilter.PostProcessSettingName(state, topIntent.Value == Luis.VehicleSettings.Intent.VEHICLE_SETTINGS_DECLARATIVE ? true : false);

                // Perform content logic and remove entities that don't make sense
                settingFilter.ApplyContentLogic(state);

                var settingNames = state.GetUniqueSettingNames();
                if (!settingNames.Any())
                {
                    // missing setting name
                    await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(VehicleSettingsResponses.VehicleSettingsMissingSettingName));

                    return(await sc.EndDialogAsync());
                }
                else if (settingNames.Count() > 1)
                {
                    // If we have more than one setting name matching prompt the user to choose
                    var options = new PromptOptions()
                    {
                        Choices = new List <Choice>(),
                    };

                    for (var i = 0; i < settingNames.Count; ++i)
                    {
                        var item   = settingNames[i];
                        var choice = new Choice()
                        {
                            Value    = item,
                            Synonyms = new List <string> {
                                (i + 1).ToString(), item
                            },
                        };
                        options.Choices.Add(choice);
                    }

                    var card = new HeroCard
                    {
                        Images = new List <CardImage> {
                            new CardImage(GetSettingCardImageUri("settingcog.jpg"))
                        },
                        Text    = "Please choose from one of the available settings shown below",
                        Buttons = options.Choices.Select(choice =>
                                                         new CardAction(ActionTypes.ImBack, choice.Value, value: choice.Value)).ToList(),
                    };

                    options.Prompt = (Activity)MessageFactory.Attachment(card.ToAttachment());

                    return(await sc.PromptAsync(Actions.SettingNameSelectionPrompt, options));
                }
                else
                {
                    // Only one setting detected so move on to next stage
                    return(await sc.NextAsync());
                }

            case Luis.VehicleSettings.Intent.VEHICLE_SETTINGS_CHECK:
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply("The skill doesn't support checking vehicle settings quite yet!"));

                return(await sc.EndDialogAsync(true, cancellationToken));

            default:
                await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(VehicleSettingsResponses.VehicleSettingsOutOfDomain));

                return(await sc.EndDialogAsync(true, cancellationToken));
            }
        }
        private async Task HandleActions(ITurnContext <IMessageActivity> turnContext)
        {
            var action = Newtonsoft.Json.JsonConvert.DeserializeObject <ActionBase>(turnContext.Activity.Value.ToString());

            switch (action.Type)
            {
            //case "PushAgenda":
            //    var pushAgendaAction = Newtonsoft.Json.JsonConvert.DeserializeObject<PushAgendaAction>(turnContext.Activity.Value.ToString());
            //    var agendaItem = _agenda.AgendaItems.First(a => a.Id.ToString() == pushAgendaAction.Choice);

            //    Attachment adaptiveCardAttachment = GetAdaptiveCardAttachment("QuestionTemplate.json", agendaItem);
            //    var activity = MessageFactory.Attachment(adaptiveCardAttachment);

            //    activity.ChannelData = new TeamsChannelData
            //    {
            //        Notification = new NotificationInfo()
            //        {
            //            AlertInMeeting = true,
            //            ExternalResourceUrl = $"https://teams.microsoft.com/l/bubble/{ _config["MicrosoftAppId"] }?url=" +
            //                                  HttpUtility.UrlEncode($"{_config["BaseUrl"]}/ContentBubble?topic={agendaItem.Topic}") +
            //                                  $"&height=270&width=250&title=ContentBubble&completionBotId={_config["MicrosoftAppId"]}"
            //        }
            //    };
            //    await turnContext.SendActivityAsync(activity);
            //    break;
            case "PushAgenda":

                var random     = new Random();
                var randomized = _agenda.AgendaItems.OrderBy(item => random.Next());
                foreach (AgendaItem agendaItem in randomized)
                {
                    //var pushAgendaAction = Newtonsoft.Json.JsonConvert.DeserializeObject<PushAgendaAction>(turnContext.Activity.Value.ToString());
                    //var agendaItem = _agenda.AgendaItems.First(a => a.Id.ToString() == pushAgendaAction.Choice);
                    Attachment adaptiveCardAttachments = GetAdaptiveCardAttachment("QuestionTemplate.json", agendaItem);
                    var        activity = MessageFactory.Attachment(adaptiveCardAttachments);

                    activity.ChannelData = new TeamsChannelData
                    {
                        Notification = new NotificationInfo()
                        {
                            AlertInMeeting      = true,
                            ExternalResourceUrl = $"https://teams.microsoft.com/l/bubble/{ _config["MicrosoftAppId"] }?url=" +
                                                  HttpUtility.UrlEncode($"{_config["BaseUrl"]}/ContentBubble?topic={agendaItem.Topic}") +
                                                  $"&height=270&width=250&title=ContentBubble&completionBotId={_config["MicrosoftAppId"]}"
                        }
                    };
                    turnContext.SendActivityAsync(activity);
                    await Task.Delay(random.Next(300000, 600000));

                    //turnContext.DeleteActivityAsync(activity.Id);
                }

                break;

            case "SubmitFeedback":
                var submitFeedback = Newtonsoft.Json.JsonConvert.DeserializeObject <SubmitFeedbackAction>(turnContext.Activity.Value.ToString());
                var item           = _agenda.AgendaItems.First(a => a.Id.ToString() == submitFeedback.Choice);
                await turnContext.SendActivityAsync($"{turnContext.Activity.From.Name} voted **{submitFeedback.Feedback}** for '{item.Topic}'");

                break;

            default:
                break;
            }
        }
Example #20
0
        private async Task <DialogTurnResult> SearchBingAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await _accessors.PictureState.GetAsync(stepContext.Context);

            //since we got here via a prompt, the step context's "Result" property
            //should be a true or false value indicating whether the user
            //clicked yes or no.

            //If the user said YES to Bing Search...
            // - create a new instance of Microsoft.Azure.CognitiveServices.Search.ImageSearch.ImageSearchAPI
            // - This ImageSearchAPI instance should use an instance of ApiKeyServiceClientCredentials based on your BING key
            // - pass the same query parameter to the the client's Images property's SearchAsync method. (this is on the state!)
            // - Let us assume all images are PNG. You will want to map (Select =>) some number of these
            //   as an Attachment (Bot.Builder) where the ContentUrl is the image's ContentUrl, and the ContentType is "image/png"
            // - Use MessageFactory to create a carousel of these attachments.
            // - Be sure to use try and Catch! We have our OnTurnError callback but the user should ideally never see it

            //If the user said no...
            // - Respect their choice :)

            //In any case end the dialog
            var choice = (bool)stepContext.Result;

            if (choice)
            {
                var key    = "";
                var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(key));

                try
                {
                    Azure.CognitiveServices.Search.ImageSearch.Models.Images results = await client.Images.SearchAsync(state.Search);

                    var attachments = results.Value.Take(5)
                                      .Select(img => new Attachment
                    {
                        ContentUrl  = img.ContentUrl,
                        ContentType = "image/png"
                    });

                    var activity = MessageFactory.Attachment(attachments, "We found the following images on Bing:");
                    activity.AttachmentLayout = "carousel";

                    await stepContext.Context.SendActivityAsync(activity, cancellationToken);
                }
                catch (Exception e)
                {
                    await stepContext.Context.SendActivityAsync($"Problem during Bing search: {e.Message}");
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Alright, we will not Bing.");
            }


            //Reset the state
            state.Search      = string.Empty;
            state.IsSearching = false;
            await _accessors.ConversationState.SaveChangesAsync(stepContext.Context);

            return(await stepContext.EndDialogAsync());
        }
Example #21
0
        /// <summary>
        /// When OnTurn method receives a submit invoke activity on bot turn, it calls this method.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="taskModuleRequest">Task module invoke request value payload.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <returns>A task that represents a task module response.</returns>
        protected override async Task <TaskModuleResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext <IInvokeActivity> turnContext, TaskModuleRequest taskModuleRequest, CancellationToken cancellationToken)
        {
            try
            {
                turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));

                var activity = (Activity)turnContext.Activity;
                this.RecordEvent(nameof(this.OnTeamsTaskModuleFetchAsync), turnContext);
                IMessageActivity notificationCard;
                Activity         mentionActivity;
                var valuesfromTaskModule = JsonConvert.DeserializeObject <TaskModuleResponseDetails>(((JObject)activity.Value).GetValue("data", StringComparison.OrdinalIgnoreCase)?.ToString());
                switch (valuesfromTaskModule.Command.ToUpperInvariant())
                {
                case Constants.SaveAdminDetailsAction:
                    mentionActivity = await CardHelper.GetMentionActivityAsync(valuesfromTaskModule.AdminPrincipalName.Split(",").ToList(), turnContext.Activity.From.AadObjectId, valuesfromTaskModule.TeamId, turnContext, this.localizer, this.logger, MentionActivityType.SetAdmin, cancellationToken);

                    var cardDetail = (Activity)MessageFactory.Attachment(AdminCard.GetAdminCard(this.localizer, valuesfromTaskModule, this.options.Value.ManifestId));
                    await this.SendMentionedCardAsync(turnContext, cardDetail, mentionActivity);

                    this.logger.LogInformation("R&R admin has been configured");
                    break;

                case Constants.CancelCommand:
                    break;

                case Constants.UpdateAdminDetailCommand:
                    mentionActivity = await CardHelper.GetMentionActivityAsync(valuesfromTaskModule.AdminPrincipalName.Split(",").ToList(), turnContext.Activity.From.AadObjectId, valuesfromTaskModule.TeamId, turnContext, this.localizer, this.logger, MentionActivityType.SetAdmin, cancellationToken);

                    notificationCard              = MessageFactory.Attachment(AdminCard.GetAdminCard(this.localizer, valuesfromTaskModule, this.options.Value.ManifestId));
                    notificationCard.Id           = turnContext.Activity.Conversation.Id.Split(';')[1].Split("=")[1];
                    notificationCard.Conversation = turnContext.Activity.Conversation;
                    await turnContext.UpdateActivityAsync(notificationCard);

                    await turnContext.SendActivityAsync(mentionActivity);

                    this.logger.LogInformation("Card is updated.");
                    break;

                case Constants.NominateAction:
                    var awardsList = await this.awardsStorageProvider.GetAwardsAsync(valuesfromTaskModule.TeamId);

                    await turnContext.SendActivityAsync(MessageFactory.Carousel(NominateCarouselCard.GetAwardsCard(this.appBaseUrl, awardsList, this.localizer, valuesfromTaskModule)));

                    break;

                case Constants.SaveNominatedDetailsAction:
                    turnContext.Activity.Conversation.Id = valuesfromTaskModule.TeamId;
                    var result = (Activity)MessageFactory.Attachment(EndorseCard.GetEndorseCard(this.appBaseUrl, this.localizer, valuesfromTaskModule));
                    mentionActivity = await CardHelper.GetMentionActivityAsync(valuesfromTaskModule.NominatedToPrincipalName.Split(",").Select(row => row.Trim()).ToList(), turnContext.Activity.From.AadObjectId, valuesfromTaskModule.TeamId, turnContext, this.localizer, this.logger, MentionActivityType.Nomination, cancellationToken);

                    await this.SendMentionedCardAsync(turnContext, result, mentionActivity);

                    this.logger.LogInformation("Nominated an award");
                    break;

                case Constants.OkCommand:
                    return(null);

                default:
                    this.logger.LogInformation($"Invalid command for task module submit activity.Command is : {valuesfromTaskModule.Command} ");
                    await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage"));

                    break;
                }

                return(null);
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, $"Error at OnTeamsTaskModuleSubmitAsync(): {ex.Message}", SeverityLevel.Error);
                await turnContext.SendActivityAsync(this.localizer.GetString("ErrorMessage"));

                throw;
            }
        }
Example #22
0
        private static Activity CreateCarousel()
        {
            var Ingreso = new HeroCard
            {
                Title    = "PASO 1",
                Subtitle = "Haga click en el siguiente enlace para redireccionar a la plataforma e ingrese <a href='https://aulavirtual.pucese.edu.ec/'>Página principal Aula Virtual</a>",

                Images = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/ingreso.png")
                },
            };

            var usuario = new HeroCard
            {
                Title    = "PASO 2",
                Subtitle = "Ingresa tu correo institucional y contraseña",

                Images = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/crede1.png")
                }
            };

            var contra = new HeroCard
            {
                Title    = "PASO 3",
                Subtitle = "Ingresa tu contraseña del correo institucional",

                Images = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/crede2.png")
                }
            };
            var califi1 = new HeroCard
            {
                Title    = "PASO 3",
                Subtitle = "En tu lado superior derecho, alado de su imagen presione en la flecha y seleccione <b>perfil</b>.",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil2.png")
                }
            };

            var califi2 = new HeroCard
            {
                Title    = "PASO 4",
                Subtitle = "Una vez dentro, alado de su imagen seleccione la ruedita y elija <b>editar perfil</b>",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil11.png")
                }
            };
            var califi3 = new HeroCard
            {
                Title    = "PASO 5",
                Subtitle = "En esta sección, puede cambiar la información",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil12.png")
                }
            };

            var perfil6 = new HeroCard
            {
                Title    = "PASO 6",
                Subtitle = "También puede cambiar la imagen de perfil a su gusto, haciendo click en la hojita 📄",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil6.png")
                }
            };

            var perfil7 = new HeroCard
            {
                Title    = "PASO 7",
                Subtitle = $"De click en <b>seleccionar archivo</b>",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil13.png")
                }
            };

            var perfill8 = new HeroCard
            {
                Title    = "PASO 8",
                Subtitle = "Seleccione la imagen a su gusto y luego de click en <b>abrir</b>",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/finalcharlar.png")
                }
            };

            var perfil9 = new HeroCard
            {
                Title    = "PASO 9",
                Subtitle = "Una vez esté todo listo, de click en <b>subir archivo</b>",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil9.png")
                }
            };

            var perf10 = new HeroCard
            {
                Title    = "PASO 10",
                Subtitle = "Cuando ya este todo listo, de click en <b>actualizar información personal</b> y automáticamente se actualizará su perfil",
                Images   = new List <CardImage> {
                    new CardImage("https://tesisstorage.blob.core.windows.net/images/perfil16.png")
                }
            };


            var optionAttachments = new List <Attachment>()
            {
                Ingreso.ToAttachment(),
                usuario.ToAttachment(),
                //contra.ToAttachment(),
                califi1.ToAttachment(),
                califi2.ToAttachment(),
                califi3.ToAttachment(),
                perfil6.ToAttachment(),
                perfil7.ToAttachment(),
                perfill8.ToAttachment(),
                perfil9.ToAttachment(),
                perf10.ToAttachment()
            };

            var reply = MessageFactory.Attachment(optionAttachments);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            return(reply as Activity);
        }
Example #23
0
 private static async Task AskPreferredLanguageCardAsync(ITurnContext turnContext, CancellationToken cancellationToken)
 {
     var languageCard = Cards.GetSelectLanguageCard();
     var response     = MessageFactory.Attachment(languageCard);
     await turnContext.SendActivityAsync(response, cancellationToken);
 }
Example #24
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var _lineText = turnContext.Activity.Text.ToLower();

            var matchFound = DialogEnum.Words.ReservedStrings.Where(w => _lineText.Contains(w)).FirstOrDefault();

            if (matchFound != null)
            {
                switch (matchFound)
                {
                case DialogEnum.Words.Meniu:
                    var attachments         = new List <Attachment>();
                    var replyToConversation = MessageFactory.Attachment(attachments);
                    replyToConversation.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                    userDataService = new UserDataService(configuration);
                    var _data = userDataService.GetMenuItems();

                    foreach (var item in _data)
                    {
                        replyToConversation.Attachments.Add(GetHeroCard(item).ToAttachment());
                    }

                    await turnContext.SendActivityAsync(replyToConversation, cancellationToken);

                    //reply.Type = ActivityTypes.Typing;
                    //reply.Text = null;
                    //await turnContext.SendActivityAsync(reply, cancellationToken);

                    //userDataService = new UserDataService(configuration);
                    //var _data = userDataService.GetMenuItems();

                    //AdaptiveCard adaptiveCard = BuildMenuAdaptiveCard(_data);
                    //var heroCard = BuildMenuHeroCard(_data);

                    //var _menuCard = CreateAdaptiveCardAttachment(adaptiveCard);
                    //var response = MessageFactory.Attachment(_menuCard);
                    //await turnContext.SendActivityAsync(response, cancellationToken);
                    break;


                case DialogEnum.Words.Total:
                    userDataService = new UserDataService(configuration);
                    decimal _total = userDataService.WeeklyTotal(turnContext.Activity.From.Name);

                    if (_total > 0)
                    {
                        await turnContext.SendActivityAsync(new Activity()
                        {
                            Type = ActivityTypes.Message,
                            Text = $"{turnContext.Activity.From.Name}, suma comenzilor pentru saptamana aceasta este: {_total} Lei"
                        }, cancellationToken);
                    }
                    else
                    {
                        await turnContext.SendActivityAsync(new Activity()
                        {
                            Type = ActivityTypes.Message,
                            Text = $"{turnContext.Activity.From.Name}, nu ai comandat nimic pana acum"
                        }, cancellationToken);
                    }
                    break;

                case DialogEnum.Words.Del:
                    userDataService = new UserDataService(configuration);
                    userDataService.DeleteOrder(turnContext.Activity.From.Name);
                    await turnContext.SendActivityAsync(new Activity()
                    {
                        Type = ActivityTypes.Message,
                        Text = $"{turnContext.Activity.From.Name}, comanda ta a fost stearsa"
                    }, cancellationToken);

                    break;


                case DialogEnum.Words.Test:
                    break;
                }
            }
            else
            {
                string line    = turnContext.Activity.Text.ToLower();
                string user    = turnContext.Activity.From.Name;
                string comanda = string.Empty;
                userDataService = new UserDataService(configuration);
                if (ProcessLine(line, user, userDataService, out comanda))
                {
                    await turnContext.SendActivityAsync(new Activity()
                    {
                        Type = ActivityTypes.Message,
                        Text = $"Comanda pentru {user} este: {comanda}"
                    }, cancellationToken);
                }
            }
        }
Example #25
0
        /// <summary>
        /// Sends the notification.
        /// </summary>
        /// <param name="notificationContent">The content of the notification to be sent.</param>
        /// <param name="serviceUrl">The service URL to use for sending the notification.</param>
        /// <param name="conversationId">The conversation ID of the conversation to which the notification should be sent.</param>
        /// <param name="maxNumberOfAttempts">The maximum number of request attempts to send the notification.</param>
        /// <param name="log">The logger.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
        public async Task <SendNotificationResponse> SendAsync(
            string notificationContent,
            string serviceUrl,
            string conversationId,
            int maxNumberOfAttempts,
            ILogger log)
        {
            var sendNotificationResponse = new SendNotificationResponse
            {
                TotalNumberOfSendThrottles = 0,
                AllSendStatusCodes         = string.Empty,
            };

            // Set the service URL in the trusted list to ensure the SDK includes the token in the request.
            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);

            var conversationReference = new ConversationReference
            {
                ServiceUrl   = serviceUrl,
                Conversation = new ConversationAccount
                {
                    Id = conversationId,
                },
            };

            await this.botAdapter.ContinueConversationAsync(
                botAppId : this.microsoftAppId,
                reference : conversationReference,
                callback : async(turnContext, cancellationToken) =>
            {
                var adaptiveCardAttachment = new Attachment()
                {
                    ContentType = SendNotificationService.AdaptiveCardContentType,
                    Content     = JsonConvert.DeserializeObject(notificationContent),
                };
                var message = MessageFactory.Attachment(adaptiveCardAttachment);

                // Loop through attempts to try and send the notification.
                for (int i = 1; i <= maxNumberOfAttempts; i++)
                {
                    try
                    {
                        await turnContext.SendActivityAsync(message);

                        // If made it passed the sending step, then the notification was sent successfully.
                        // Store the data about the successful request.
                        sendNotificationResponse.ResultType          = SendNotificationResultType.Succeeded;
                        sendNotificationResponse.StatusCode          = (int)HttpStatusCode.Created;
                        sendNotificationResponse.AllSendStatusCodes += $"{(int)HttpStatusCode.Created},";

                        break;
                    }
                    catch (ErrorResponseException e)
                    {
                        log.LogError(e, $"ERROR: {e.GetType()}: {e.Message}");

                        var responseStatusCode = e.Response.StatusCode;
                        sendNotificationResponse.StatusCode          = (int)responseStatusCode;
                        sendNotificationResponse.AllSendStatusCodes += $"{(int)responseStatusCode},";

                        // If the response was a throttled status code or a 5xx status code,
                        // then delay and retry the request.
                        if (responseStatusCode == HttpStatusCode.TooManyRequests ||
                            ((int)responseStatusCode >= 500 && (int)responseStatusCode < 600))
                        {
                            if (responseStatusCode == HttpStatusCode.TooManyRequests)
                            {
                                // If the request was throttled, set the flag for indicating the throttled state and
                                // increment the count of the number of throttles to be stored later.
                                sendNotificationResponse.ResultType = SendNotificationResultType.Throttled;
                                sendNotificationResponse.TotalNumberOfSendThrottles++;
                            }
                            else
                            {
                                // If the request failed with a 5xx status code, set the flag for indicating the failure
                                // and store the content of the error message.
                                sendNotificationResponse.ResultType   = SendNotificationResultType.Failed;
                                sendNotificationResponse.ErrorMessage = e.Response.Content;
                            }

                            // If the maximum number of attempts has not been reached, delay
                            // for a bit of time to attempt the request again.
                            // Do not delay if already attempted the maximum number of attempts.
                            if (i < maxNumberOfAttempts)
                            {
                                var random = new Random();
                                await Task.Delay(random.Next(500, 1500));
                            }
                        }
                        else if (responseStatusCode == HttpStatusCode.NotFound)
                        {
                            // If in this block, then the recipient has been removed.
                            // This recipient should be excluded from the list.
                            sendNotificationResponse.ResultType   = SendNotificationResultType.RecipientNotFound;
                            sendNotificationResponse.ErrorMessage = e.Response.Content;

                            break;
                        }
                        else
                        {
                            // If in this block, then an error has occurred with the service.
                            // Return the failure and do not attempt the request again.
                            sendNotificationResponse.ResultType   = SendNotificationResultType.Failed;
                            sendNotificationResponse.ErrorMessage = e.Response.Content;

                            break;
                        }
                    }
                }
            },
                cancellationToken : CancellationToken.None);

            return(sendNotificationResponse);
        }
Example #26
0
        // Handle message activity in 1:1 chat
        private async Task OnMessageActivityInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            if (!string.IsNullOrEmpty(message.ReplyToId) && (message.Value != null) && ((JObject)message.Value).HasValues)
            {
                this.telemetryClient.TrackTrace("Card submit in 1:1 chat");
                await this.OnAdaptiveCardSubmitInPersonalChatAsync(message, turnContext, cancellationToken);

                return;
            }

            string text = (message.Text ?? string.Empty).Trim().ToLower();

            switch (text)
            {
            case AskAnExpert:
                this.telemetryClient.TrackTrace("Sending user ask an expert card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard()));

                break;

            case ShareFeedback:
                this.telemetryClient.TrackTrace("Sending user feedback card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard()));

                break;

            case TakeATour:
                this.telemetryClient.TrackTrace("Sending user tour card");
                var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri);
                await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards));

                break;

            default:
                this.telemetryClient.TrackTrace("Sending input to QnAMaker");
                var queryResult = await this.GetAnswerFromQnAMakerAsync(text, turnContext, cancellationToken);

                if (queryResult != null)
                {
                    this.telemetryClient.TrackTrace("Sending user QnAMaker card");
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], queryResult.Answer, text)));
                }
                else
                {
                    var tileList = await this.MatchTagsWithMessageAsync(text);

                    if (tileList != null)
                    {
                        this.telemetryClient.TrackTrace("Sending user tags card");
                        await turnContext.SendActivityAsync(SuggestedLinkCard.GetTagsCarouselCards(text, tileList, Resource.CustomMessage));
                    }
                    else
                    {
                        this.telemetryClient.TrackTrace("Sending user with no matched tags result");
                        await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text, Resource.NoMatchedTagsMessage)));
                    }
                }

                break;
            }
        }
        public void AttachmentNull()
        {
            IMessageActivity message = MessageFactory.Attachment((Attachment)null);

            Assert.Fail("Exception not thrown");
        }
Example #28
0
        // Handle adaptive card submit in 1:1 chat
        // Submits the question or feedback to the SME team
        private async Task OnAdaptiveCardSubmitInPersonalChatAsync(IMessageActivity message, ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            Attachment   smeTeamCard = null;    // Notification to SME team
            Attachment   userCard    = null;    // Acknowledgement to the user
            TicketEntity newTicket   = null;    // New ticket

            switch (message.Text)
            {
            case AskAnExpert:
            {
                this.telemetryClient.TrackTrace("Sending user ask an expert card (from answer)");

                var responseCardPayload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard(responseCardPayload)));

                break;
            }

            case ShareFeedback:
            {
                this.telemetryClient.TrackTrace("Sending user share feedback card (from answer)");

                var responseCardPayload = ((JObject)message.Value).ToObject <ResponseCardPayload>();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard(responseCardPayload)));

                break;
            }

            case AskAnExpertCard.AskAnExpertSubmitText:
            {
                this.telemetryClient.TrackTrace($"Received question for expert");

                var askAnExpertPayload = ((JObject)message.Value).ToObject <AskAnExpertCardPayload>();

                // Validate required fields
                if (string.IsNullOrWhiteSpace(askAnExpertPayload.Title))
                {
                    var updateCardActivity = new Activity(ActivityTypes.Message)
                    {
                        Id           = turnContext.Activity.ReplyToId,
                        Conversation = turnContext.Activity.Conversation,
                        Attachments  = new List <Attachment> {
                            AskAnExpertCard.GetCard(askAnExpertPayload)
                        },
                    };
                    await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

                    return;
                }

                var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                newTicket = await this.CreateTicketAsync(message, askAnExpertPayload, userDetails);

                smeTeamCard = new SmeTicketCard(newTicket).ToAttachment(message.LocalTimestamp);
                userCard    = new UserNotificationCard(newTicket).ToAttachment(Resource.NotificationCardContent, message.LocalTimestamp);
                break;
            }

            case ShareFeedbackCard.ShareFeedbackSubmitText:
            {
                this.telemetryClient.TrackTrace($"Received app feedback");

                var shareFeedbackPayload = ((JObject)message.Value).ToObject <ShareFeedbackCardPayload>();

                // Validate required fields
                if (!Enum.TryParse(shareFeedbackPayload.Rating, out FeedbackRating rating))
                {
                    var updateCardActivity = new Activity(ActivityTypes.Message)
                    {
                        Id           = turnContext.Activity.ReplyToId,
                        Conversation = turnContext.Activity.Conversation,
                        Attachments  = new List <Attachment> {
                            ShareFeedbackCard.GetCard(shareFeedbackPayload)
                        },
                    };
                    await turnContext.UpdateActivityAsync(updateCardActivity, cancellationToken);

                    return;
                }

                var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                smeTeamCard = SmeFeedbackCard.GetCard(shareFeedbackPayload, userDetails);
                await turnContext.SendActivityAsync(MessageFactory.Text(Resource.ThankYouTextContent));

                break;
            }

            default:
                this.telemetryClient.TrackTrace($"Unexpected text in submit payload: {message.Text}", SeverityLevel.Warning);
                break;
            }

            // Send message to SME team
            if (smeTeamCard != null)
            {
                var channelId = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.TeamId);

                var resourceResponse = await this.SendCardToTeamAsync(turnContext, smeTeamCard, channelId, cancellationToken);

                // If a ticket was created, update the ticket with the conversation info
                if (newTicket != null)
                {
                    newTicket.SmeCardActivityId       = resourceResponse.ActivityId;
                    newTicket.SmeThreadConversationId = resourceResponse.Id;
                    await this.ticketsProvider.SaveOrUpdateTicketAsync(newTicket);
                }
            }

            // Send acknowledgment to the user
            if (userCard != null)
            {
                await turnContext.SendActivityAsync(MessageFactory.Attachment(userCard), cancellationToken);
            }
        }
Example #29
0
        private static IMessageActivity createContentsCard(string emotion)
        {
            HtmlAgilityPack.HtmlWeb      web = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = web.Load("https://pedia.watcha.com/ko-KR/" + "search?query=" + emotion.ToString());
            string          baseURL          = "https://pedia.watcha.com";
            List <Contents> contentsList     = new List <Contents>();


            foreach (var item in doc.DocumentNode.SelectNodes("//li[@class = 'css-106b4k6-Self e3fgkal0']"))
            {
                var    a_element = item.FirstChild;
                string url       = "";
                if (a_element.Attributes["href"] != null)
                {
                    url = baseURL + a_element.Attributes["href"].Value;
                }
                string img = "";
                foreach (var img_element in a_element.Descendants("img"))
                {
                    if (img_element.Attributes["src"] != null)
                    {
                        img = img_element.Attributes["src"].Value;
                    }
                }
                string title = "", info = "", type = "";
                var    divParent = a_element.LastChild;
                int    cnt       = 0;
                foreach (var div in divParent.Descendants("div"))
                {
                    switch (cnt++)
                    {
                    case 0:
                        title = div.InnerText;
                        break;

                    case 1:
                        info = div.InnerText;
                        break;

                    default:
                        type = div.InnerText;
                        break;
                    }
                }
                contentsList.Add(new Contents(
                                     title = title,
                                     info  = info,
                                     url   = url,
                                     type  = type,
                                     img   = img
                                     ));
            }
            var attachments = new List <Attachment>();
            var reply       = MessageFactory.Attachment(attachments);

            reply.Text             = $"감정 상태인 {emotion}에 어울리는 컨텐츠입니다.";
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            Random random_movie = new Random();

            foreach (Contents item in contentsList)
            {
                reply.Attachments.Add(GetHeroCard(item.title, $"{item.info}  {item.type}", item.url, item.img).ToAttachment());
            }

            return(reply);
        }
Example #30
0
        private static Activity CreateCarousel()
        {
            var cardMaestriasDisponible1 = new HeroCard
            {
                Title    = "Maestría en Administración de Empresas",
                Subtitle = "Opciones",
                Images   = new List <CardImage> {
                    new CardImage("https://posbot1storage.blob.core.windows.net/cursos/Captura4.PNG")
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Más información", Value = "https://posbot1storage.blob.core.windows.net/cursos/MAE-3_ oficial.pdf", Type = ActionTypes.DownloadFile
                    },
                    new CardAction()
                    {
                        Title = "Preinscripción", Value = "Preinscripcion~31", Type = ActionTypes.PostBack
                    },
                }
            };

            var cardMaestriasDisponible2 = new HeroCard
            {
                Title    = "Maestría en Recursos Naturales y Gestión Ambiental",
                Subtitle = "Opciones",
                Images   = new List <CardImage> {
                    new CardImage("https://posbot1storage.blob.core.windows.net/cursos/Captura5.PNG")
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Más información", Value = "https://posbot1storage.blob.core.windows.net/cursos/MAGA-4_oficial.pdf", Type = ActionTypes.DownloadFile
                    },
                    new CardAction()
                    {
                        Title = "Preinscripción", Value = "Preinscripcion~32", Type = ActionTypes.PostBack
                    },
                }
            };

            var cardMaestriasDisponible3 = new HeroCard
            {
                Title    = "Maestría en Educación Superior Universitaria",
                Subtitle = "Opciones",
                Images   = new List <CardImage> {
                    new CardImage("https://posbot1storage.blob.core.windows.net/cursos/Captura6.PNG")
                },
                Buttons = new List <CardAction>()
                {
                    new CardAction()
                    {
                        Title = "Más información", Value = "https://posbot1storage.blob.core.windows.net/cursos/MESU-10_oficial.pdf", Type = ActionTypes.DownloadFile
                    },
                    new CardAction()
                    {
                        Title = "Preinscripción", Value = "Preinscripcion~33", Type = ActionTypes.PostBack
                    },
                }
            };

            var optionsAttachments = new List <Attachment>()
            {
                cardMaestriasDisponible1.ToAttachment(),
                cardMaestriasDisponible2.ToAttachment(),
                cardMaestriasDisponible3.ToAttachment(),
            };

            var reply = MessageFactory.Attachment(optionsAttachments);

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            return(reply as Activity);
        }