Build Action Based Messaging Extension With Microsoft Teams App

Introduction

The messaging extensions action command allows users to collect information using modal popup, process their information, and send it back to the Teams channel conversation area.

Messaging Extension

Messaging extensions take advantage of the Bot Framework's messaging schema and secure communication protocol to connect with Microsoft Teams Client App.

There are three type of messaging extensions that can be build for Microsoft Teams:

  1. Search based messaging extension for Microsoft Teams
  2. Action based messaging extension for Microsoft Teams
  3. Unfurl Url with messaging extenssion for Microsoft Teams.

In this article, I am going to explain "Action based messaging extesnion for Microsoft Teams".

Previous arcticle

Search based messaging extension can be find here.

How Messaging Extension Action Command works

Build Action Based Messaging Extension With Microsoft Teams App

Prerequisites

  • Microsoft Teams
  • Azure Bot Framework, .NetCore
  • Azure Web API .Net Standard
  • Microsoft 365 tenant
  • Microsoft Azure subscription

Let's get started.

To create Microsoft Team Messaging Extension requires two activities,

  1. Create Microsoft Azure Bot.
  2. Create manifest file with bot reference
  3. Upload manifest file to MS Team Client App.

Step 1 - Create Microsoft Azure Bot

  1. Browse https://portal.azure.com with your work or school account.
  2. Click "+Create Resource"
  3. Select "AI + Machine Learning"
  4. Select "Web App Bot"

 Build Action Based Messaging Extension With Microsoft Teams App

Step 2 - Complete all required information and click create to provision the bot

  1. Bot handle:- The unique name of your bot.
  2. Subscription:- Select a valid available subscription.
  3. Resource Group:- Select an appropriate resource group or create a new one as per your requirement.
  4. Location:- Select your closed azure location or the preferred location.
  5. Pricing:- Select the required pricing tier or F0 as free for POC activity.
  6. App Name:- Leave it as-is for this demo purpose.
  7. Service Plan:- Leave it as-is for this demo purpose.
  8. Bot Template:- Leave it as-is for this demo purpose.
  9. Application insight: Select off for this demo purpose
  10. Microsoft App Id and Password:- Leave it as-is for this demo purpose.
  11. Click create to provision.

Build Action Based Messaging Extension With Microsoft Teams App

Step 3 - Enable Microsoft Team Channel for your Bot

In order for the bot to interact with MS Teams, you must enable the Teams Channel

 Build Action Based Messaging Extension With Microsoft Teams App

 To complete the process, MS Teams and Webchat should be available and should be listed in your channel lists.

Build Action Based Messaging Extension With Microsoft Teams App 

Step 4 - Create a Bot Framework

In this section, we are going to create an echo bot using Visual Studio 2019

  • Open the Visual Studio, Select create project and navigate to the desired directory to create a project.
  • Select Echo Bot (Bot Framework v4) .Net Core

Build Action Based Messaging Extension With Microsoft Teams App 

Step 5 - Update Default Bot Code

  1. Select EchoBot.cs and Remove all default methods implemented into RchoBot class.
  2. Inherit Team Activity Handler to Echo Bot Class to implement messaging extension related method.
  3. Add Submit Action Async method to captur defined command Id. 
  4. Execute custom logic based on action command id.
  5. CreateCard allow user to choose card, share and interact with teams channel conversation.
  6. ShareMessage allow user to choose card, share and interact using "More Action" context menu.

Build Action Based Messaging Extension With Microsoft Teams App 

protected override async Task<MessagingExtensionActionResponse> OnTeamsMessagingExtensionSubmitActionAsync(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action, CancellationToken cancellationToken)  
{  
    switch (action.CommandId)  
    {  
        // These commandIds are defined in the Teams App Manifest.  
        case "createCard":  
            return CreateCardCommand(turnContext, action);  

        case "shareMessage":  
            return ShareMessageCommand(turnContext, action);  
        default:  
            throw new NotImplementedException($"Invalid CommandId: {action.CommandId}");  
    }  
}

Create Card Command capture data from modal popup convert into JSON object and mapped with Hero Card, return with attachement as Messaging Extesnion Action Response.

private MessagingExtensionActionResponse CreateCardCommand(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action)  
{  
    // The user has chosen to create a card by choosing the 'Create Card' context menu command.  
    var createCardData = ((JObject)action.Data).ToObject<CreateCardData>();  

    var card = new HeroCard  
    {  
        Title = createCardData.Title,  
        Subtitle = createCardData.Subtitle,  
        Text = createCardData.Text,  
    };  

    var attachments = new List<MessagingExtensionAttachment>();  
    attachments.Add(new MessagingExtensionAttachment  
    {  
        Content = card,  
        ContentType = HeroCard.ContentType,  
        Preview = card.ToAttachment(),  
    });  

    return new MessagingExtensionActionResponse  
    {  
        ComposeExtension = new MessagingExtensionResult  
        {  
            AttachmentLayout = "list",  
            Type = "result",  
            Attachments = attachments,  
        },  
    };  
}

Shared Message can be invoked using "More Action" context menu and allow user to repond over existing message. This example is used to send custom parameters using message payload and return with attachement as Messaging Extesnion Action Response.

private MessagingExtensionActionResponse ShareMessageCommand(ITurnContext<IInvokeActivity> turnContext, MessagingExtensionAction action)  
{  
    // The user has chosen to share a message by choosing the 'Share Message' context menu command.  
    var heroCard = new HeroCard  
    {  
        Title = $"{action.MessagePayload.From?.User?.DisplayName} orignally sent this message:",  
        Text = action.MessagePayload.Body.Content,  
    };  

    if (action.MessagePayload.Attachments != null && action.MessagePayload.Attachments.Count > 0)  
    {  
        heroCard.Subtitle = $"({action.MessagePayload.Attachments.Count} Attachments not included)";  
    }  

    var includeImage = ((JObject)action.Data)["includeImage"]?.ToString();  
    if (!string.IsNullOrEmpty(includeImage) && bool.TrueString == includeImage)  
    {  
        heroCard.Images = new List<CardImage>  
        {  
            new CardImage { Url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU" },  
        };  
    }  

    return new MessagingExtensionActionResponse  
    {  
        ComposeExtension = new MessagingExtensionResult  
        {  
            Type = "result",  
            AttachmentLayout = "list",  
            Attachments = new List<MessagingExtensionAttachment>()  
            {  
                new MessagingExtensionAttachment  
                {  
                    Content = heroCard,  
                    ContentType = HeroCard.ContentType,  
                    Preview = heroCard.ToAttachment(),  
                },  
            },  
        },  
    };  
}

Build and Publish the Bot Code to Publishing Profile.

Step 5 - Create Manifest

  1. Create folder within solution with the name "TeamAppManifest"
  2. Create and add icon-color.png file
  3. Create and add icon-outline.png file
  4. Create manifest.json file and Update compose Extension with Command Context "Compose" and "CommandBox
"composeExtensions": [  
  {  
    "botId": "4c961f60-bb20-44a9-913d-2177652ddb3b",  
    "commands": [  
      {  
        "id": "createCard",  
        "type": "action",  
        "context": [ "compose" ],  
        "description": "Command to run action to create a Card from Compose Box",  
        "title": "Create Card",  
        "parameters": [  
          {  
            "name": "title",  
            "title": "Card title",  
            "description": "Title for the card",  
            "inputType": "text"  
          },  
          {  
            "name": "subTitle",  
            "title": "Subtitle",  
            "description": "Subtitle for the card",  
            "inputType": "text"  
          },  
          {  
            "name": "text",  
            "title": "Text",  
            "description": "Text for the card",  
            "inputType": "textarea"  
          }  
        ]  
      },  
      {  
        "id": "shareMessage",  
        "type": "action",  
        "context": [ "message" ],  
        "description": "Test command to run action on message context (message sharing)",  
        "title": "Share Message",  
        "parameters": [  
          {  
            "name": "includeImage",  
            "title": "Include Image",  
            "description": "Include image in Hero Card",  
            "inputType": "toggle"  
          }  
        ]  
      }  
    ]  
  }  
],

Step 6 - Upload Manifest into Microsoft Teams App

Navigate to manifest folder /src/manifest. Select both .png files and manifest.jon file and zip all three files. Give the name of zip file "manifest"

Login to https://teams.microsoft.com

  1. Navigate to App Studio
  2. Select Import an existing app
  3. Select the manifest.zip file
  4. Bot name with the icon will appear at the screen

Build Action Based Messaging Extension With Microsoft Teams App

Browse and check Command Added to Message Extension via message extension.json file; i.e., create card and share message.

Build Action Based Messaging Extension With Microsoft Teams App

Step 7 - Install Custom App to Teams Solution

  1. Select the install App using Manifest file and It will navigate to create an app page will all pre-filled information and Select test and distribute
  2. Click Add to add app to teams.

Build Action Based Messaging Extension With Microsoft Teams App 

Once bot deployment and Manifest configuration are complete, now it's time to test the messaging extension.

Output

  1. Navigate to teams and select channel
  2. Below compose message box click "..." and select deployed app i.e. "Action-extension-settigns"
  3. Modal popup will appear;  and fill in the message payload information and click submit.
  4. Message or request will post to Teams Channel conversation section.

Build Action Based Messaging Extension With Microsoft Teams App

Reposnd to existing message; i.e. ShareMessage using Action command with Context Menu.

Step 1

Select exisitng message

  1. click "..." section
  2. Select more actions
  3. Select ShareMessage.

Step 2

Design Modal popup; i.e. Include image or not and click submit.

Step 3

Message posted using adaptive card as response thread to existing message.

Build Action Based Messaging Extension With Microsoft Teams App 

Codebase exists at this https://github.com/manoj1201/MSTeamDevelopment/tree/master/MessageExtensionAction/MessageExtensionAction

I hope you have enjoyed and learned something new in this article. Thanks for reading and stay tuned for the next article.


Similar Articles