Search code examples
node.jsazurebotsadaptive-cards

How do you implement Azure bot adaptive card?


My understanding for creating an adaptive card in azure bot is by hard coding it. Is there a better to create an Adaptive card? Because imagine if we have to create 120 cards. We have to hard code files that is like the codes below which is not a good practice. Please help! Thanks

 {
   "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.0",
    "body": [
      {
        "type": "Image",
        "url":"google.image.com",
        "size": "small"
      }
     ],
    "actions": [
    {
      "type": "Action.OpenUrl",
      "title": "Google",
      "url": "google.com"
     }
     ]
  }

Solution

  • There's a couple of different ways you can do this. Given the card:

    {
        "type": "AdaptiveCard",
        "body": [
            {
                "type": "Image",
                "id": "img",
                "selectAction": {
                    "type": "Action.OpenUrl",
                    "title": "Google",
                    "url": "http://www.google.com"
                },
                "url": "https://imgplaceholder.com/420x320/ff7f7f/333333/fa-image"
            }
        ],
        "actions": [
            {
                "type": "Action.OpenUrl",
                "title": "Google",
                "url": "http://www.google.com"
            }
        ],
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
        "version": "1.0"
    }
    

    Which will render as:

    enter image description here

    And given that we're importing it with:

    import * as cardJson from './adaptiveCard.json';
    

    And then our code looks something like this:

    const card = CardFactory.adaptiveCard(cardJson);
    const msg = MessageFactory.text('');
    msg.attachments = [card];
    await context.sendActivity(msg);
    

    1. Edit the JSON directly

    If we use this to change the image:

    cardJson.body[0].url = 'https://skillbotbuilder.gallerycdn.vsassets.io/extensions/skillbotbuilder/skillbotbuilder/1.0/1546976085901/Microsoft.VisualStudio.Services.Icons.Default';
    

    we get:

    enter image description here

    So, you can use your .json as more of a template and then build off of it with javascript. Or:

    2. Use a different type of card

    Here's a link to other card types

    You can then use CardFactory to build the cards.

    A Hero Card similar to the above would look something like this:

    const hero = CardFactory.heroCard(
        null,
        CardFactory.images(['https://imgplaceholder.com/420x320/ff7f7f/333333/fa-image']),
        CardFactory.actions([{
            type: 'Action.OpenUrl',
            title: 'Google',
            value: 'Google.com'
        }])
    );