Search code examples
c#jsonframeworksbotframeworkbots

How to create a carousel with a loop Microsoft Bot Framework


Trying to create a carousel using JSON returned from an API. I'm trying to return one carousel with multiple images and you can scroll across to look at all images. I'm pretty sure it's something small I'm missing, any help is much appreciated.

                    RootObject result = JsonConvert.DeserializeObject<RootObject>(apiResponse);

                    var card = new HeroCard { };

                    List<CardImage> cardImages = new List<CardImage>();
                    var reply = context.Activity.CreateReply();
                    Attachment plAttachment;

                    for (int i = 0; i < 5; i++)
                    {
                        cardImages.Add(new CardImage(url: "https://image.tmdb.org/t/p/original" + result.results[i].poster_path));                           
                    }

                    for (int x = 0; x < 5; x++)
                    {
                        HeroCard plCard = new HeroCard()
                        {
                            Text = "Test",
                            Title = "Movies",
                            Images = cardImages,

                        };
                        plAttachment = plCard.ToAttachment();
                        reply.Attachments.Add(plAttachment);
                    }
                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    await context.SendActivityAsync(reply);
                }
            }       
        }

        catch (Exception ex)
        {

        }
}

At the moment its returning multiple carousels with the same image: Bot Reply


Solution

  • You already came up with this solution. It was edited out of your question, presumably because it should be posted as an answer. So here it is (slightly modified for efficiency) in case you want to mark this question as answered:

    for (int i = 0; i < result.results.Count(); i++)
    {
        var data = result.results[i];
        var heroCard = new HeroCard
        {
            Title = data.title,
            Subtitle = "Rating: " + data.popularity,
            Text = data.overview,
            Images = new List<CardImage> { new CardImage("https://image.tmdb.org/t/p/original" + data.poster_path) },
            Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Book", value: "https://www.odeoncinemas.ie/cinema-tickets") },
        };
        // Add the attachment to our reply.
        reply.Attachments.Add(heroCard.ToAttachment());
    }
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    await context.SendActivityAsync(reply);