public static void ShowWorkItems(IBotContext context, List <Workitem> workitems, IHttpContextAccessor accessor, bool lastOnly = false)
        {
            if ((workitems == null) || (workitems.Count == 0))
            {
                context.Reply("You have no workitems saved.");
                return;
            }

            List <Attachment> attachments = new List <Attachment>();

            if (lastOnly)
            {
                workitems = new List <Workitem>()
                {
                    workitems.LastOrDefault()
                };
            }

            foreach (var item in workitems)
            {
                var card = new WorkItemCard(item);

                Attachment attachment = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content     = card.GetCard(accessor)
                };

                attachments.Add(attachment);
            }
            var activity = MessageFactory.Carousel(attachments);

            context.Reply(activity);
        }
Exemple #2
0
        private IActivity GetCrousleCard(ITurnContext currentContext)
        {
            var activity = MessageFactory.Carousel(
                new Attachment[]
            {
                new HeroCard(
                    title: "Docker",
                    images: new CardImage[] { new CardImage(url: "http://localhost:3978/images/docker.png") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "Go to Item", type: ActionTypes.ImBack, value: "Docker"),
                })
                .ToAttachment(),
                new HeroCard(
                    title: "Visual Studio",
                    images: new CardImage[] { new CardImage(url: "http://localhost:3978/images/visualstudio.png") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "Go to Item", type: ActionTypes.ImBack, value: "VisualStudio")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "Xamrine",
                    images: new CardImage[] { new CardImage(url: "http://localhost:3978/images/xamarin.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "Go to Item", type: ActionTypes.ImBack, value: "Xamrine")
                })
                .ToAttachment()
            });

            return(activity);
        }
        // Handle message activity in channel
        private async Task OnMessageActivityInChannelAsync(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 channel");
                await this.OnAdaptiveCardSubmitInChannelAsync(message, turnContext, cancellationToken);

                return;
            }

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

            switch (text)
            {
            case TeamTour:
                this.telemetryClient.TrackTrace("Sending team tour card");
                var teamTourCards = TourCarousel.GetTeamTourCards(this.appBaseUri);
                await turnContext.SendActivityAsync(MessageFactory.Carousel(teamTourCards));

                break;

            default:
                this.telemetryClient.TrackTrace("Unrecognized input in channel");
                var unrecognizedInputCard = UnrecognizedTeamInputCard.GetCard();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(unrecognizedInputCard));

                break;
            }
        }
Exemple #4
0
        private async Task <DialogTurnResult> AskInsuranceTypeStep(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var ineedInsuranceState = await _ineedInsuranceStateAccessor.GetAsync(stepContext.Context);

            var actions = new[]
            {
                new CardAction(type: ActionTypes.ImBack, title: "Car", value: "Car", image: $"{Site}/auto_600x400.png"),
                new CardAction(type: ActionTypes.ImBack, title: "Property", value: "Property", image: $"{Site}/property_600x400.jpg"),
                new CardAction(type: ActionTypes.ImBack, title: "Life", value: "Life", image: $"{Site}/life_600x400.jpg"),
            };
            var heroCard = new HeroCard(buttons: actions);

            // Add the cards definition with images
            var cards = actions
                        .Select(x => new HeroCard
            {
                Images = new List <CardImage> {
                    new CardImage(x.Image)
                },
                Buttons = new List <CardAction> {
                    x
                },
            }.ToAttachment())
                        .ToList();


            // Replace the following line to show carousel with images
            var activity = (Activity)MessageFactory.Carousel(cards, "What kind of insurance do you need?");

            return(await stepContext.PromptAsync(PromptStep.InsuranceTypePrompt, new PromptOptions { Prompt = activity }, cancellationToken));
        }
        private async Task ShowProductCarouselStep(DialogContext dc, IDictionary <string, object> args, SkipStepFunction next)
        {
            var context       = dc.Context;
            var catalogFilter = dc.Context.GetUserState <UserInfo>().CatalogFilter;

            var products = await GetProducts(catalogFilter, catalogAIService, catalogService);

            int pageCount = (products.Count + CatalogFilterData.PageSize - 1) / CatalogFilterData.PageSize;

            if (products.Count != 0)
            {
                const bool logged           = false;
                const bool supportsMarkdown = false;
                var        text             = $"Page {catalogFilter.PageIndex + 1} of {pageCount} ( {products.Count} items )";
                var        items            = CatalogCarousel(products, logged, supportsMarkdown);
                await context.SendActivities(new[]
                {
                    MessageFactory.Carousel(items, text),
                    MessageFactory.SuggestedActions(CreateNextButtons(catalogFilter.PageIndex, pageCount, logged), "choose one option")
                });
            }
            else
            {
                await context.SendActivities(new[] {
                    MessageFactory.Text("There are no results matching your search"),
                    MessageFactory.Text("Type what do you want to do.")
                });

                await dc.End();
            }
        }
Exemple #6
0
        public void CarouselTwoAttachments()
        {
            var text      = Guid.NewGuid().ToString();
            var ssml      = Guid.NewGuid().ToString();
            var inputHint = InputHints.ExpectingInput;

            var attachmentName = Guid.NewGuid().ToString();
            var attachment1    = new Attachment
            {
                Name = attachmentName,
            };

            var attachmentName2 = Guid.NewGuid().ToString();
            var attachment2     = new Attachment
            {
                Name = attachmentName2,
            };

            var multipleAttachments = new List <Attachment> {
                attachment1, attachment2
            };

            var message = MessageFactory.Carousel(multipleAttachments, text, ssml, inputHint);

            Assert.Equal(message.Text, text);
            Assert.Equal(message.Type, ActivityTypes.Message);
            Assert.Equal(message.InputHint, inputHint);
            Assert.Equal(message.Speak, ssml);
            Assert.True(message.AttachmentLayout == AttachmentLayoutTypes.Carousel);
            Assert.True(message.Attachments.Count == 2, "Incorrect Attachment Count");
            Assert.True(message.Attachments[0].Name == attachmentName, "Incorrect Attachment1 Name");
            Assert.True(message.Attachments[1].Name == attachmentName2, "Incorrect Attachment2 Name");
        }
        // 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)
                {
                    string answer = this.ReplaceWildCard(message, turnContext, queryResult.Answer);
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(ResponseCard.GetCard(queryResult.Questions[0], answer, queryResult.Source, text)));
                }
                else
                {
                    await turnContext.SendActivityAsync(MessageFactory.Attachment(UnrecognizedInputCard.GetCard(text)));
                }

                // Save conversation
                var saveConversations = await this.configurationProvider.GetSavedEntityDetailAsync(ConfigurationEntityTypes.SaveConversations);

                if (bool.Parse(saveConversations))
                {
                    var userDetails = await this.GetUserDetailsInPersonalChatAsync(turnContext, cancellationToken);

                    ConversationEntity newConversation = await this.CreateConversationAsync(message, queryResult, userDetails);
                }

                break;
            }
        }
        public static void ReplyWithCarousel(ITurnContext context)
        {
            // Create the activity and attach a set of Hero cards.
            var activity = MessageFactory.Carousel(
                new Attachment[]
            {
                new HeroCard(
                    title: "title1",
                    images: new CardImage[] { new CardImage(url: catUrl) },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "button1", type: ActionTypes.ImBack, value: "item1")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "title2",
                    images: new CardImage[] { new CardImage(url: catUrl) },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "button2", type: ActionTypes.ImBack, value: "item2")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "title3",
                    images: new CardImage[] { new CardImage(url: catUrl) },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "button3", type: ActionTypes.ImBack, value: "item3")
                })
                .ToAttachment()
            });

            context.SendActivity(activity);
        }
Exemple #9
0
        /// <summary>
        /// Invoked when a message activity is received from the bot.
        /// </summary>
        /// <param name="turnContext">Context object containing information cached for a single turn of conversation with a user.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            try
            {
                turnContext = turnContext ?? throw new ArgumentNullException(nameof(turnContext));
                var message = turnContext.Activity;

                if (message != null && !string.IsNullOrEmpty(message.Text))
                {
                    var command = message.RemoveRecipientMention()?.Trim();

                    switch (command?.ToUpperInvariant())
                    {
                    case Constants.HelpCommand:     // Help command to get the information about the bot.
                        this.logger.LogInformation("Sending user help card");
                        var userHelpCards = CarouselCard.GetUserHelpCards(this.botOptions.Value.AppBaseUri);
                        await turnContext.SendActivityAsync(MessageFactory.Carousel(userHelpCards));

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error while message activity is received from the bot.");
                throw;
            }
        }
Exemple #10
0
        private IMessageActivity GetPizzaToppingCarousel(IDictionary <string, object> state, string caption)
        {
            //Turn all the pizza topping enum values into hero cards
            //Remove any the user has already selected
            var attachments = ((PizzaTopping[])Enum.GetValues(typeof(PizzaTopping)))
                              .Except(GetSelectionsFromState(state))
                              .Select(topping =>
            {
                var label = topping.ToString();
                return(new HeroCard()
                {
                    Title = label,
                    Tap = new CardAction()
                    {
                        Type = ActionTypes.ImBack, Value = label
                    },
                    Images = new[]
                    {
                        new CardImage()
                        {
                            Url = "https://via.placeholder.com/150"
                        }
                    }
                }.ToAttachment());
            });

            //Now combine them into a carousel
            var activity = MessageFactory.Carousel(attachments, text: caption);

            return(activity);
        }
Exemple #11
0
        public void CarouselUnorderedAttachments()
        {
            string text      = Guid.NewGuid().ToString();
            string ssml      = Guid.NewGuid().ToString();
            string inputHint = InputHints.ExpectingInput;

            string     attachmentName1 = Guid.NewGuid().ToString();
            Attachment attachment1     = new Attachment
            {
                Name = attachmentName1
            };

            string     attachmentName2 = Guid.NewGuid().ToString();
            Attachment attachment2     = new Attachment
            {
                Name = attachmentName2
            };

            HashSet <Attachment> multipleAttachments = new HashSet <Attachment> {
                attachment1, attachment2
            };
            IMessageActivity message = MessageFactory.Carousel(multipleAttachments, text, ssml, inputHint);

            HashSet <string> names = new HashSet <string> {
                attachmentName1, attachmentName2
            };

            Assert.AreEqual(message.Text, text, "Message Text does not match");
            Assert.AreEqual(message.Type, ActivityTypes.Message, "Incorrect Activity Type");
            Assert.AreEqual(message.InputHint, inputHint, "InputHint does not match");
            Assert.AreEqual(message.Speak, ssml, "ssml text is incorrect");
            Assert.IsTrue(message.AttachmentLayout == AttachmentLayoutTypes.Carousel);
            Assert.IsTrue(message.Attachments.Count == 2, "Incorrect Attachment Count");
            Assert.IsTrue(names.SetEquals(message.Attachments.Select(a => a.Name)), "Incorrect set of attachment names.");
        }
Exemple #12
0
        private async Task DisplayDefaultWatchesAsync(ITurnContext context)
        {
            var actions = new[]
            {
                new CardAction(type: ActionTypes.ShowImage, title: "Fabrikam Smart Watch", value: "Fabrikam Smart Watch", image: $"{SiteImagesPath}/watches/SearchResult_Product1.png"),
                new CardAction(type: ActionTypes.ShowImage, title: "Arch Pro - Series 2", value: "Arch Pro - Series 2", image: $"{SiteImagesPath}/watches/SearchResult_Product2.png"),
                new CardAction(type: ActionTypes.ShowImage, title: "V300 Smart Watch", value: "V300 Smart Watch", image: $"{SiteImagesPath}/watches/SearchResult_Product3.png"),
                new CardAction(type: ActionTypes.ShowImage, title: "Litware Tallboy", value: "Litware Tallboy", image: $"{SiteImagesPath}/watches/SearchResult_Product4.png"),
                new CardAction(type: ActionTypes.ShowImage, title: "AdventureWorks X", value: "AdventureWorks X", image: $"{SiteImagesPath}/watches/SearchResult_Product5.png"),
            };

            var cards = actions
                        .Select(x => new HeroCard
            {
                Images = new List <CardImage> {
                    new CardImage(x.Image)
                },
                Buttons = new List <CardAction> {
                    x
                },
            }.ToAttachment())
                        .ToList();
            var activity = (Activity)MessageFactory.Carousel(cards, "Watch Catalog");
            await context.SendActivityAsync(activity);
        }
Exemple #13
0
        private async Task CarTypeStep(DialogContext dialogContext, object result, SkipStepFunction next)
        {
            var state = dialogContext.Context.GetConversationState <ReservationData>();

            if (state.CarType == null)
            {
                // Your code goes here
                var actions = new[]
                {
                    new CardAction(type: ActionTypes.ImBack, title: "Sedan", value: "Sedan"),
                    new CardAction(type: ActionTypes.ImBack, title: "SUV", value: "SUV"),
                    new CardAction(type: ActionTypes.ImBack, title: "Sports car", value: "Sports car")
                };

                var heroCard = new HeroCard(buttons: actions);
                var activity = (Activity)MessageFactory.Carousel(new[] { heroCard.ToAttachment() }, "Please select a car type.");
                var choices  = actions.Select(x => new Choice {
                    Action = x, Value = (string)x.Value
                }).ToList();
                await dialogContext.Prompt(PromptStep.CarTypePrompt, activity, new ChoicePromptOptions { Choices = choices });

                //    await dialogContext.Context.SendActivity("What kind of vehicle would you like?");
                //    await dialogContext.Prompt(PromptStep.CarTypePrompt, $"Available options are: {string.Join(", ", BotConstants.CarTypes)}");
            }
            else
            {
                await next();
            }
        }
Exemple #14
0
        // Handle message activity in channel
        private async Task OnMessageActivityInChannelAsync(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 channel");
                await this.OnAdaptiveCardSubmitInChannelAsync(message, turnContext, cancellationToken);

                return;
            }

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

            if (text.Equals(Resource.ResourceManager.GetString("TakeATeamTourButtonText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase))
            {
                this.telemetryClient.TrackTrace("Sending team tour card");
                var teamTourCards = TourCarousel.GetTeamTourCards(this.appBaseUri);
                await turnContext.SendActivityAsync(MessageFactory.Carousel(teamTourCards));
            }
            else
            {
                this.telemetryClient.TrackTrace("Unrecognized input in channel");
                var unrecognizedInputCard = UnrecognizedTeamInputCard.GetCard();
                await turnContext.SendActivityAsync(MessageFactory.Attachment(unrecognizedInputCard));
            }
        }
Exemple #15
0
        private async Task <DialogTurnResult> AskUsers(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var groupDetails = (CreateGroupParams)stepContext.Options;

            groupDetails.tabsWebsiteUrl = (string)stepContext.Result;

            List <Attachment> usersCardAttachments = new List <Attachment>();

            var users = _flowClient.GetUsers();

            foreach (var userValue in users.value)
            {
                var userCard = new ThumbnailCard
                {
                    Title    = userValue.displayName,
                    Subtitle = userValue.id,
                    Images   = new List <CardImage> {
                        new CardImage {
                            Url = "https://botdevhecdiag.blob.core.windows.net/public/id-card.png"
                        }
                    }
                };
                usersCardAttachments.Add(userCard.ToAttachment());
            }

            Activity message = MessageFactory.Carousel(usersCardAttachments,
                                                       "Por último, ¿Que usuarios perteneceran a este grupo?, Pegame las ids separadas por ;") as Activity;

            return(await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = message }, cancellationToken));
        }
Exemple #16
0
        public async Task <DialogTurnResult> ChooseOrderStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await Accessors.CustomerDataState.GetAsync(stepContext.Context, null, cancellationToken);

            if (state.SalesOrders == null)
            {
                var orders = await Client.GetSalesOrdersOfCustomer(state.Customer.Number);

                state.SalesOrders = ConvertDictionary(orders);
                var attachments = new List <Attachment>();
                foreach (var order in orders)
                {
                    attachments.Add(StaticTexts.CreatePostedSalesOrderAttachment(order.Key, order.Value, state.Customer));
                }

                await Accessors.CustomerDataState.SetAsync(stepContext.Context, state, cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Carousel(attachments), cancellationToken);

                await Chatter.SendMessageAsync(stepContext.Context, StaticTexts.ViewedOrdersText);
            }
            return(await stepContext.PromptAsync(OrdersPrompt, new PromptOptions
            {
                Prompt = await Chatter.GetActivityAsync(stepContext.Context, StaticTexts.EnterOrderNumberText),
                RetryPrompt = await Chatter.GetActivityAsync(stepContext.Context, StaticTexts.EnterOrderNumberAgainText)
            }, cancellationToken : cancellationToken));
        }
        private async Task <DialogTurnResult> SearchAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var result = (string)stepContext.Result;

            if (!string.IsNullOrEmpty(result))
            {
                var criteria = new dto.ProductSearchCriteria
                {
                    SearchPhrase = result
                };
                var products = await _productFetcher.GetProductsAsync(criteria);

                if (products.Length != 0)
                {
                    var cards = products.GetCards();

                    await stepContext.Context.SendActivityAsync(MessageFactory.Carousel(cards.Select(c => c.ToAttachment())), cancellationToken);
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Nothing found"),
                                                                cancellationToken);
                }
            }

            return(await stepContext.ReplaceDialogAsync(nameof(SearchDialog), cancellationToken : cancellationToken));
        }
Exemple #18
0
        public void CarouselTwoAttachments()
        {
            string text      = Guid.NewGuid().ToString();
            string ssml      = Guid.NewGuid().ToString();
            string inputHint = InputHints.ExpectingInput;

            string     attachmentName = Guid.NewGuid().ToString();
            Attachment attachment1    = new Attachment
            {
                Name = attachmentName
            };

            string     attachmentName2 = Guid.NewGuid().ToString();
            Attachment attachment2     = new Attachment
            {
                Name = attachmentName2
            };

            IList <Attachment> multipleAttachments = new List <Attachment> {
                attachment1, attachment2
            };
            IMessageActivity message = MessageFactory.Carousel(multipleAttachments, text, ssml, inputHint);

            Assert.AreEqual(message.Text, text, "Message Text does not match");
            Assert.AreEqual(message.Type, ActivityTypes.Message, "Incorrect Activity Type");
            Assert.AreEqual(message.InputHint, inputHint, "InputHint does not match");
            Assert.AreEqual(message.Speak, ssml, "ssml text is incorrect");
            Assert.IsTrue(message.AttachmentLayout == AttachmentLayoutTypes.Carousel);
            Assert.IsTrue(message.Attachments.Count == 2, "Incorrect Attachment Count");
            Assert.IsTrue(message.Attachments[0].Name == attachmentName, "Incorrect Attachment1 Name");
            Assert.IsTrue(message.Attachments[1].Name == attachmentName2, "Incorrect Attachment2 Name");
        }
Exemple #19
0
        public void CarouselUnorderedAttachments()
        {
            var text      = Guid.NewGuid().ToString();
            var ssml      = Guid.NewGuid().ToString();
            var inputHint = InputHints.ExpectingInput;

            var attachmentName1 = Guid.NewGuid().ToString();
            var attachment1     = new Attachment
            {
                Name = attachmentName1,
            };

            var attachmentName2 = Guid.NewGuid().ToString();
            var attachment2     = new Attachment
            {
                Name = attachmentName2,
            };

            var multipleAttachments = new HashSet <Attachment> {
                attachment1, attachment2
            };
            var names = new HashSet <string> {
                attachmentName1, attachmentName2
            };

            var message = MessageFactory.Carousel(multipleAttachments, text, ssml, inputHint);

            Assert.Equal(message.Text, text);
            Assert.Equal(message.Type, ActivityTypes.Message);
            Assert.Equal(message.InputHint, inputHint);
            Assert.Equal(message.Speak, ssml);
            Assert.True(message.AttachmentLayout == AttachmentLayoutTypes.Carousel);
            Assert.True(message.Attachments.Count == 2, "Incorrect Attachment Count");
            Assert.True(names.SetEquals(message.Attachments.Select(a => a.Name)), "Incorrect set of attachment names.");
        }
Exemple #20
0
        private async Task <DialogTurnResult> SearchAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var result = (string)stepContext.Result;

            if (!string.IsNullOrEmpty(result))
            {
                var userProfileAccessor = _conversationState.CreateProperty <dto.UserProfile>(nameof(dto.UserProfile));
                var userProfile         = await userProfileAccessor.GetAsync(stepContext.Context, () => new dto.UserProfile(), cancellationToken);

                var criteria = new dto.ProductSearchCriteria
                {
                    SearchPhrase = result,
                    StoreId      = userProfile.Customer.StoreId
                };
                var products = await _productFetcher.GetProductsAsync(criteria);

                if (!products.IsNullOrEmpty())
                {
                    var cards = products.GetCards();

                    await stepContext.Context.SendActivityAsync(MessageFactory.Carousel(cards.Select(c => c.ToAttachment())), cancellationToken);
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(MessageFactory.Text("Nothing found"),
                                                                cancellationToken);
                }
            }

            return(await stepContext.ReplaceDialogAsync(nameof(SearchDialog), cancellationToken : cancellationToken));
        }
        /// <summary>
        /// Send the nomination reminder notification to specified team.
        /// </summary>
        /// <param name="rewardCycleEntity">Reward cycle model object.</param>
        /// <returns>A task that sends notification card in channel.</returns>
        private async Task SendCardToTeamAsync(RewardCycleEntity rewardCycleEntity)
        {
            rewardCycleEntity = rewardCycleEntity ?? throw new ArgumentNullException(nameof(rewardCycleEntity));

            var awardsList = await this.awardsStorageProvider.GetAwardsAsync(rewardCycleEntity.TeamId);

            var valuesFromTaskModule = new TaskModuleResponseDetails()
            {
                RewardCycleStartDate = rewardCycleEntity.RewardCycleStartDate,
                RewardCycleEndDate   = rewardCycleEntity.RewardCycleEndDate,
                RewardCycleId        = rewardCycleEntity.CycleId,
            };

            var teamDetails = await this.teamStorageProvider.GetTeamDetailAsync(rewardCycleEntity.TeamId);

            string serviceUrl = teamDetails.ServiceUrl;

            MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
            string teamGeneralChannelId = rewardCycleEntity.TeamId;

            this.logger.LogInformation($"sending notification to channel id - {teamGeneralChannelId}");

            await retryPolicy.ExecuteAsync(async() =>
            {
                try
                {
                    var conversationParameters = new ConversationParameters()
                    {
                        ChannelData = new TeamsChannelData()
                        {
                            Channel = new ChannelInfo()
                            {
                                Id = rewardCycleEntity.TeamId
                            }
                        },
                        Activity = (Activity)MessageFactory.Carousel(NominateCarouselCard.GetAwardNominationCards(this.options.Value.AppBaseUri, awardsList, this.localizer, valuesFromTaskModule)),
                    };

                    Activity mentionActivity = MessageFactory.Text(this.localizer.GetString("NominationReminderNotificationText"));

                    await((BotFrameworkAdapter)this.adapter).CreateConversationAsync(
                        Constants.TeamsBotFrameworkChannelId,
                        serviceUrl,
                        this.microsoftAppCredentials,
                        conversationParameters,
                        async(conversationTurnContext, conversationCancellationToken) =>
                    {
                        await conversationTurnContext.SendActivityAsync(mentionActivity, conversationCancellationToken);
                    },
                        default);
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, "Error while sending mention card notification to channel.");
                    throw;
                }
            });
        }
        public async Task <IActionResult> WinnerNominationAsync([FromBody] IList <AwardWinnerNotification> details)
        {
            try
            {
                if (details == null)
                {
                    return(this.BadRequest());
                }

                var    emails      = string.Join(",", details.Select(row => row.NominatedToPrincipalName)).Split(",").Select(row => row.Trim()).Distinct();
                string teamId      = details.First().TeamId;
                var    claims      = this.GetUserClaims();
                var    teamDetails = await this.teamStorageProvider.GetTeamDetailAsync(teamId);

                string serviceUrl = teamDetails.ServiceUrl;
                string appId      = this.configuration["MicrosoftAppId"];
                string appBaseUrl = this.configuration.GetValue <string>("Bot:AppBaseUri");
                string manifestId = this.configuration.GetValue <string>("Bot:ManifestId");
                MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
                var conversationParameters = new ConversationParameters()
                {
                    ChannelData = new TeamsChannelData()
                    {
                        Team = new TeamInfo()
                        {
                            Id = teamId
                        }, Channel = new ChannelInfo()
                        {
                            Id = teamId
                        }
                    },
                    Activity = (Activity)MessageFactory.Carousel(WinnerCarouselCard.GetAwardWinnerCard(appBaseUrl, details, this.localizer, manifestId)),
                    Bot      = new ChannelAccount()
                    {
                        Id = appId
                    },
                    IsGroup  = true,
                    TenantId = this.configuration.GetValue <string>("Bot:TenantId"),
                };

                await((BotFrameworkAdapter)this.adapter).CreateConversationAsync(
                    Channel,
                    serviceUrl,
                    new MicrosoftAppCredentials(this.configuration.GetValue <string>("MicrosoftAppId"), this.configuration.GetValue <string>("MicrosoftAppPassword")),
                    conversationParameters,
                    async(turnContext, cancellationToken) =>
                {
                    Activity mentionActivity = await CardHelper.GetMentionActivityAsync(emails, claims.FromId, teamId, turnContext, this.localizer, this.logger, MentionActivityType.Winner, default);
                    await((BotFrameworkAdapter)this.adapter).ContinueConversationAsync(
                        this.configuration.GetValue <string>("MicrosoftAppId"),
                        turnContext.Activity.GetConversationReference(),
                        async(continueConversationTurnContext, continueConversationCancellationToken) =>
                    {
                        mentionActivity.ApplyConversationReference(turnContext.Activity.GetConversationReference());
                        await continueConversationTurnContext.SendActivityAsync(mentionActivity, continueConversationCancellationToken);
                    }, cancellationToken);
                }, default);
Exemple #23
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            var results = await SearchPagesInAttachment(turnContext.Activity.Text);

            // text response
            // await turnContext.SendActivityAsync(MessageFactory.Text($"{JsonConvert.SerializeObject(results)}"), cancellationToken);

            // carousel card response
            await turnContext.SendActivityAsync(MessageFactory.Carousel(results), cancellationToken);
        }
        public static void ShowReservations(ITurnContext context, List <Reservation> reservations)
        {
            if ((reservations == null) || (reservations.Count == 0))
            {
                context.SendActivity("You have no reservations.");
                return;
            }

            IMessageActivity activity;

            if (reservations.Count == 1)
            {
                activity = context.Activity.CreateReply();
                var card    = new AdaptiveCard();
                var factset = new AdaptiveFactSet();
                factset.Facts.Add(new AdaptiveFact("Start Date", reservations[0].StartDay.ToString("dd/MM/yyyy")));
                factset.Facts.Add(new AdaptiveFact("Location", reservations[0].Location));
                factset.Facts.Add(new AdaptiveFact("Duration", reservations[0].Duration.ToString()));
                factset.Facts.Add(new AdaptiveFact("People", reservations[0].PeopleNumber.ToString()));

                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text = "Your reservation", Size = AdaptiveTextSize.Default, Wrap = true, Weight = AdaptiveTextWeight.Default
                });
                card.Body.Add(factset);

                activity.Attachments.Add(new Attachment(AdaptiveCard.ContentType, content: card));
                context.SendActivity(activity);
                return;
            }

            string message     = $"You have { reservations.Count } reservations: \n\n";
            var    attachments = new List <Attachment>();

            foreach (var res in reservations)
            {
                var card    = new AdaptiveCard();
                var factset = new AdaptiveFactSet();
                factset.Facts.Add(new AdaptiveFact("Start Date", res.StartDay.ToString("dd/MM/yyyy")));
                factset.Facts.Add(new AdaptiveFact("Location", res.Location));
                factset.Facts.Add(new AdaptiveFact("Duration", res.Duration.ToString()));
                factset.Facts.Add(new AdaptiveFact("People", res.PeopleNumber.ToString()));

                card.Body.Add(new AdaptiveTextBlock()
                {
                    Text = "Your reservation", Size = AdaptiveTextSize.Default, Wrap = true, Weight = AdaptiveTextWeight.Default
                });
                card.Body.Add(factset);

                attachments.Add(new Attachment(AdaptiveCard.ContentType, content: card));
            }
            activity = MessageFactory.Carousel(attachments);

            context.SendActivity(activity);
        }
Exemple #25
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();

            if (text.Equals(Resource.ResourceManager.GetString("AskAnExpertDisplayText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase))
            {
                this.telemetryClient.TrackTrace("Sending user ask an expert card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(AskAnExpertCard.GetCard()));
            }
            else if (text.Equals(Resource.ResourceManager.GetString("ShareFeedbackDisplayText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase))
            {
                this.telemetryClient.TrackTrace("Sending user feedback card");
                await turnContext.SendActivityAsync(MessageFactory.Attachment(ShareFeedbackCard.GetCard()));
            }
            else if (text.Equals(Resource.ResourceManager.GetString("TakeATourButtonText", CultureInfo.CurrentCulture), StringComparison.InvariantCultureIgnoreCase))
            {
                this.telemetryClient.TrackTrace("Sending user tour card");
                var userTourCards = TourCarousel.GetUserTourCards(this.appBaseUri);
                await turnContext.SendActivityAsync(MessageFactory.Carousel(userTourCards));
            }
            else
            {
                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)));
                    }
                }
            }
        }
        public async Task AttachJobSearchCardsAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var keywordCard = CreateAdaptiveCardAttachment("HSUbot.Cards.KeyWordSearchCard.json");
            var ChoiceCard  = CreateAdaptiveCardAttachment("HSUbot.Cards.ChoiceSearchCard.json");
            var attachments = new List <Attachment>();

            attachments.Add(keywordCard);
            attachments.Add(ChoiceCard);
            var att = MessageFactory.Carousel(attachments);
            await turnContext.SendActivityAsync(att, cancellationToken);
        }
        /// <summary>
        /// Every Conversation turn for our EchoBot will call this method. In here
        /// the bot checks the Activty type to verify it's a message, bumps the
        /// turn conversation 'Turn' count, and then echoes the users typing
        /// back to them.
        /// </summary>
        /// <param name="context">Turn scoped context containing all the data needed
        /// for processing this conversation turn. </param>
        public async Task OnTurn(ITurnContext context)
        {
            // This bot is only handling Messages
            if (context.Activity.Type == ActivityTypes.Message)
            {
                // Get the conversation state from the turn context
                var state = context.GetConversationState <WillieState>();

                // Bump the turn count.
                state.TurnCount++;

                IMessageActivity response = null;

                if (context.Activity.Attachments?.Count > 0)
                {
                    IList <Attachment> attachments = new List <Attachment>();

                    foreach (Attachment originalAttachment in context.Activity.Attachments)
                    {
                        HttpRequestMessage  req = new HttpRequestMessage(HttpMethod.Get, originalAttachment.ContentUrl);
                        HttpResponseMessage res = await _httpClient.SendAsync(req);

                        if (res.IsSuccessStatusCode)
                        {
                            using (MemoryStream memStream = new MemoryStream())
                            {
                                await res.Content.CopyToAsync(memStream);

                                string base64Image = Convert.ToBase64String(memStream.GetBuffer());

                                Attachment attachment = new Attachment
                                {
                                    ContentType = originalAttachment.ContentType,
                                    Name        = "Echoed Image",
                                    ContentUrl  = $"data:{originalAttachment.ContentType};base64,{base64Image}"
                                };

                                attachments.Add(attachment);
                            }
                        }
                    }

                    response = MessageFactory.Carousel(attachments, $"Turn {state.TurnCount}: You sent this");
                }
                else
                {
                    response = MessageFactory.Text($"Turn {state.TurnCount}: You sent '{context.Activity.Text}'");
                }
                // Echo back to the user whatever they typed.
                await context.SendActivity(response);
            }
        }
        private async Task <DialogTurnResult> PromptForCarTypeStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var actions = new[]
            {
                new CardAction(type: ActionTypes.ImBack, title: "Sedan", value: "Sedan"),
                new CardAction(type: ActionTypes.ImBack, title: "SUV", value: "SUV"),
                new CardAction(type: ActionTypes.ImBack, title: "Sports car", value: "Sports car"),
            };

            var heroCard = new HeroCard(buttons: actions);
            var activity = (Activity)MessageFactory.Carousel(new[] { heroCard.ToAttachment() }, "Please select a car type.");

            return(await stepContext.PromptAsync(PromptStep.CarTypePrompt, new PromptOptions { Prompt = activity }, cancellationToken));
        }
Exemple #29
0
        private static async Task SendNearestATMAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = MessageFactory.Carousel(
                new Attachment[]
            {
                new HeroCard(
                    title: "1 Km from Current Location.",
                    subtitle: " No.150, Velachery Tambaram Rd, V.G.P Pushpa Nagar, Medavakkam, Chennai, Tamil Nadu 600100",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir/12.9137106,80.1819266/State+Bank+of+India,+No.150,+Velachery+Tambaram+Rd,+V.G.P+Pushpa+Nagar,+Medavakkam,+Chennai,+Tamil+Nadu+600100/@12.9172299,80.1789818,16z/data=!3m1!4b1!4m9!4m8!1m1!4e1!1m5!1m1!1s0x3a525c1fffa58599:0x2901962e5eeaf17!2m2!1d80.1875752!2d12.9193671")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "700 metre from Current Location.",
                    subtitle: "3/153, 11/329, Perumbakkam Main Rd, Opp ARUN Hospital, Medavakkam, Chennai, Tamil Nadu 600100",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//nearest+sbi+atm/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x3a525c1f1e55d089:0x9c58792bc66efa35?sa=X&ved=2ahUKEwi5w_v10v7hAhXm7HMBHb34ABUQ9RcwAHoECAEQCQ")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "2 Km from Current Location",
                    subtitle: "Shop No. 94, Velachery Main Rd, Pallikaranai, Chennai, Tamil Nadu 600100",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//nearest+sbi+atm/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x3a525c1878a5398b:0x422c12ef418ce4d9?sa=X&ved=2ahUKEwiQyP7A0_7hAhXzjuYKHcp5CrkQ9RcwAHoECAEQCA")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "100 Metre from Current Location",
                    subtitle: "Munusamy Nagar, Vimala Nagar, Medavakkam, Chennai, Tamil Nadu 600100",

                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "button", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//nearest+sbi+atm/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x3a525c1fab940a2b:0x289cd69a4db77f3?sa=X&ved=2ahUKEwiu18y_0_7hAhV1muYKHULKDLsQ9RcwAHoECAEQCA")
                })
                .ToAttachment()
            });
            await turnContext.SendActivityAsync(MessageFactory.Text($"I found 4 Nearest ATM."), cancellationToken);

            // Send the activity as a reply to the user.
            await turnContext.SendActivityAsync(activity, cancellationToken : cancellationToken);

            await SendSuggestedActionsAsync(turnContext, cancellationToken);
        }
Exemple #30
0
        private static async Task SendNearestBranchAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = MessageFactory.Carousel(
                new Attachment[]
            {
                new HeroCard(
                    title: "1 Km from Current Location.",
                    subtitle: "No.150, Velachery Tambaram Rd, Medavakkam, Chennai, Tamil Nadu 600100",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//State+Bank+of+India,+No.150,+Velachery+Tambaram+Rd,+V.G.P+Pushpa+Nagar,+Medavakkam,+United+Colony,+V.G.P+Pushpa+Nagar,+Medavakkam,+Chennai,+Tamil+Nadu+600100/@12.9137104,80.1818837,15z/data=!4m16!1m6!3m5!1s0x3a525c1fffa58599:0x2901962e5eeaf17!2sState+Bank+of+India!8m2!3d12.9193671!4d80.1875752!4m8!1m0!1m5!1m1!1s0x3a525c1fffa58599:0x2901962e5eeaf17!2m2!1d80.1875752!2d12.9193671!3e3")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "700 metre from Current Location.",
                    subtitle: "3/153, 11/329, Perumbakkam Main Rd, Opp ARUN Hospital, Medavakkam, Chennai, Tamil Nadu 600100",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//3%2F153,+State+Bank+Of+India,+11%2F329,+Perumbakkam+Main+Rd,+Opp+ARUN+Hospital,+Medavakkam,+Chennai,+Tamil+Nadu+600100/@12.9137101,80.1818408,15z/data=!4m16!1m6!3m5!1s0x3a525c1f1e55d089:0x9c58792bc66efa35!2sState+Bank+Of+India!8m2!3d12.9150086!4d80.1944557!4m8!1m0!1m5!1m1!1s0x3a525c1f1e55d089:0x9c58792bc66efa35!2m2!1d80.1944557!2d12.9150086!3e3")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "2 Km from Current Location",
                    subtitle: "Plot No.75, Rajakilapakkam, Madambakkam Main Rd, Gokul Nagar, Rajakilpakkam, Madambakkam, Chennai, Tamil Nadu 600073",
                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//State+Bank+of+India,+Plot+No.75,+Rajakilapakkam,+Madambakkam+Main+Rd,+Gokul+Nagar,+Rajakilpakkam,+Madambakkam,+Chennai,+Tamil+Nadu+600073/@12.9162504,80.14359,15z/data=!4m16!1m6!3m5!1s0x3a525edd173ed3b5:0x8d34c93d459d1f72!2sState+Bank+of+India!8m2!3d12.9162504!4d80.1523447!4m8!1m0!1m5!1m1!1s0x3a525edd173ed3b5:0x8d34c93d459d1f72!2m2!1d80.1523447!2d12.9162504!3e3")
                })
                .ToAttachment(),
                new HeroCard(
                    title: "100 Metre from Current Location",
                    subtitle: "Natwest Vijay Block IV,, Velachery Main Rd, Pallikaranai, Chennai, Tamil Nadu 600100",

                    images: new CardImage[] { new CardImage(url: "https://www.mantri.in/serenity/images/serenity-map.jpg") },
                    buttons: new CardAction[]
                {
                    new CardAction(title: "View Map", type: ActionTypes.OpenUrl, value: "https://www.google.com/maps/dir//State+Bank+of+India,+Natwest+Vijay+Block+IV,,+Velachery+Main+Rd,+Pallikaranai,+Chennai,+Tamil+Nadu+600100/@12.9292956,80.1945426,15z/data=!4m16!1m6!3m5!1s0x3a525c3a37c5a1a7:0x3f7aa4f76c57c487!2sState+Bank+of+India!8m2!3d12.9292956!4d80.2032973!4m8!1m0!1m5!1m1!1s0x3a525c3a37c5a1a7:0x3f7aa4f76c57c487!2m2!1d80.2032973!2d12.9292956!3e3")
                })
                .ToAttachment()
            });
            await turnContext.SendActivityAsync(MessageFactory.Text($"I found 4 Nearest Branch."), cancellationToken);

            // Send the activity as a reply to the user.
            await turnContext.SendActivityAsync(activity, cancellationToken : cancellationToken);

            await SendSuggestedActionsAsync(turnContext, cancellationToken);
        }