Tutorials

In this article, learn more about building Teams app capabilities. Here's a list of the step-by-step guides available for Teams platform capabilities.

# Capability Step-by-step guide
1. Bot - Debug your AI chat bot using Microsoft 365 Agents Playground
- Send proactive messages
2. Message extension - Build API-based message extension
- Build action-based message extension
- Build your first message extension app using JavaScript
3. Tab Build your first tab app using C sharp
4. SSO - Build a bot with SSO authentication
- Add SSO to tab and message extension app

Build your first bot app

Start Microsoft Teams app development with your first Teams app. You can create a bot app with Teams using Javascript.


Build your first bot

Your app has a capability, which comes with its own UI and UX:

Diagram shows that this app has three features.

In this tutorial, you'll learn:

  • How to set up a new project with Microsoft 365 Agents Toolkit (previously known as Teams Toolkit).
  • How to build a bot app.
  • How to deploy your app.

Prerequisites

Ensure you install the following tools for building and deploying your apps.

  Install For using...
Required    
  Microsoft 365 Agents Toolkit A Microsoft Visual Studio Code extension that creates a project scaffolding for your app. Use the latest version.
  Microsoft Teams Microsoft Teams to collaborate with everyone you work with through apps for chat, meetings, and call all in one place.
  Node.js Back-end JavaScript runtime environment. For more information, see Node.js version compatibility table for project type.
  Microsoft Edge (recommended) or Google Chrome A browser with developer tools.
  Visual Studio Code JavaScript, TypeScript, or SharePoint Framework (SPFx) build environments. Use the latest version.
Optional    
  Azure Tools for Visual Studio Code and Azure CLI Azure tools to access stored data or to deploy a cloud-based backend for your Teams app in Azure.
  React Developer Tools for Chrome OR React Developer Tools for Microsoft Edge A browser DevTools extension for the open-source React JavaScript library.
  Microsoft Graph Explorer Microsoft Graph Explorer, a browser-based tool that lets you run a query from Microsoft Graph data.
  Developer Portal for Teams Web-based portal to configure, manage, and publish your Teams app including to your organization or the Microsoft Teams Store.

Tip

If you work with Microsoft Graph data, you should learn about and bookmark the Microsoft Graph Explorer. This browser-based tool allows you to query Microsoft Graph outside of an app.

Set up prerequisites

After you install the required tools, set up the development environment.

Install Microsoft 365 Agents Toolkit

Microsoft 365 Agents Toolkit (previously known as Teams Toolkit) helps simplify the development process with tools to provision and deploy cloud resources for your app and publish to the Teams Store.

You can use Agents Toolkit with Visual Studio Code or a command-line interface called Microsoft 365 Agents Toolkit CLI (previously known as TeamsFx CLI).

  1. Open Visual Studio Code and select Extensions (Ctrl+Shift+X or View > Extensions).

  2. In the search box, enter Microsoft 365 Agents Toolkit.

  3. Select Install.

    Screenshot shows the Agents Toolkit extension installation.

    The Microsoft 365 Agents Toolkit icon appears in the Visual Studio Code Activity Bar.

You can also install Agents Toolkit from the Visual Studio Code Marketplace.

Set up your Teams development tenant

A tenant is a space or a container for your organization in Teams, where you chat, share files, and run meetings. This space is also where you upload and test your app. Let's verify if you're ready to develop with the tenant.

Check for upload an app option

After creating your custom app, you must upload your app to Teams with the Upload a custom app option. Sign in to your Microsoft 365 account to check if this option is enabled.

The following steps help you verify if you can upload apps in Teams:

  1. In the Teams client, select the Apps icon.

  2. Select Manage your apps.

  3. Select Upload an app.

  4. Look for the option to Upload a custom app. If the option is visible, you can upload custom apps.

    Screenshot shows the option to upload a custom app in Teams.

Note

If you don't find the option to upload a custom app, contact your Teams administrator.

Create a free Teams developer tenant

If you don't have a Teams developer account, join the Microsoft 365 developer program. This is an optional step.

  1. Go to the Microsoft 365 developer program.

  2. Select Join Now and follow the onscreen instructions.

  3. In the welcome screen, select Set up E5 subscription.

  4. Set up your administrator account. After you finish, the following screen appears:

    The screenshot shows the Microsoft 365 Developer Program.

  5. Sign in to Teams using the administrator account you just set up. Verify that you have the Upload a custom app option in Teams.

Get a free Azure account

If you want to host your app or access resources in Azure, you must have an Azure subscription. Create a free account before you begin.

Now you've got all the tools to set up your account. Next, let's set up your development environment and start building! Select the app you want to create first.

Create project workspace for your bot app

Let's create your first bot app.

The bot capability of a Teams app creates a chatbot or a conversational bot. You use it to run simple and automated tasks, like providing customer service. A bot talks with a web service and helps you use its offerings. You can get weather forecast, make reservations, or any other service offered using a conversational bot.

Diagram showing this app has three features. Bot is highlighted.

As you've already prepared for creating these apps, you can set up a new Teams project for creating the bot app.

In this tutorial, you learn:

  1. How to set up a new bot project with Agents Toolkit.
  2. About the directory structure of your app project.

Create your bot project workspace

If the prerequisites are in place, let's begin!

Note

The Visual Studio Code UI shown is from Mac. It may differ depending on your operating system, Agents Toolkit version, and environment.

  1. Open Visual Studio Code.

  2. Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code Activity Bar.

  3. Select Create a New Agent/App > Teams App.

    This screenshot shows the location of the Create New Project link in the Agents Toolkit sidebar.

  4. Select Bot to create a new bot project.

    Screenshot shows the wizard to Create New Project.

  5. Ensure that Basic Bot is selected as the app feature that you want to build in your app.

    The screenshot shows the app feature to add to your new app.

  6. Select JavaScript as the programming language.

    The screenshot shows the option to select the programming language.

  7. Select Default folder to store your project root folder in default location.

    The screenshot shows the selection of default location.

    You can also change the default location by the following steps:

    1. Select Browse.

      Screenshot shows the selection of browse location option.

    2. Select the location for project workspace.

    3. Select the Select Folder.

      Screenshot shows the folder to select.

  8. Enter a suitable name for your app and then select Enter.

    Screenshot shows where to enter the app name.

A dialog appears, where you would be required to choose yes or no to trust the authors of the files in this folder.

Screenshot shows the dialog to trust or not the authors of the files in this folder.

Your Teams app with a bot capability is created in few seconds.

Screenshot shows the app created.

After your app is created, Agents Toolkit displays the following message:

Screenshot shows the message that the feature is successfully created.

Select Local debug to preview your project.

A quick recap of creating a Teams app. Watch this short recap for creating a Teams app.

Create a Teams app

Take a tour of the bot app source code

After scaffolding is completed, view the project directories and files in the Explorer in the Visual Studio Code.

Screenshot shows the folder structure.

Folder / File Contents
m365agents.yml Main project file
m365agents.local.yml This overrides m365agents.yml with actions that enable local execution and debugging.
.vscode/ VSCode files for local debug.
appPackage/ Templates for the Teams application manifest.
adaptiveCards/ Adaptive Cards sent back by the bot.
infra/ Templates for provisioning Azure resources.
index.js Application entry point and express handler.
teamsBot.js Teams activity handler.

Tip

Familiarize yourself with bots outside of Teams before you integrate your first bot within Teams.

Build and run your first bot app

After you set up your project workspace with Agents Toolkit, build your bot project. You need to sign in to your Microsoft 365 account.

Sign in to your Microsoft 365 account

Use this account to sign in to Teams. If you're using a Microsoft 365 developer program tenant, the admin account you set up while registering is your Microsoft 365 account.

  1. Open Visual Studio Code.

  2. Select the Microsoft 365 Agents Toolkit icon in the sidebar.

  3. Select Sign in to M365 using your credentials.

    Your default web browser opens to let you sign in to the account.

  4. Close the browser when prompted and return to Visual Studio Code.

  5. Return to Agents Toolkit within Visual Studio Code.

    Use this account to sign in to Teams. If you're using a Microsoft 365 developer program tenant, the admin account you set up while registering is your Microsoft 365 account.

    Screenshot shows where to sign in to Microsoft 365 and Azure.

Now you're ready to build the app and run it locally!

Build and run your first bot app locally

To build and run your app in the local environment:

  1. Select F5 in Visual Studio Code to run your app in debug mode.

    Note

    If Agents Toolkit is unable to check a particular prerequisite, it prompts you to check.

    Learn what happens when you run your app locally in the debugger.

    In case you're wondering, when you press the F5 key, Agents Toolkit:

    1. Checks all the following prerequisites:
    • You're logged in with a Microsoft 365 account.
    • Custom app upload is enabled for your Microsoft 365 account.
    • Supported Node.js version is installed.
    • Port required by bot app is available.
    1. Install npm packages.
    2. Starts Dev Tunnel to create a HTTP tunnel.
    3. Registers the app in Microsoft Entra ID and configures the app.
    4. Registers the bot app in Bot Framework and configures the bot app.
    5. Registers the app in Teams Developer Portal and configures the app.
    6. Starts the bot app.
    7. Starts Teams in a web browser and uploads the custom bot app.

    Screenshot showing when F5 key is pressed for debugging.

    Note

    When you run the app for the first time, all dependencies are downloaded, and the app is built. A browser window automatically opens when the build is complete. This process can take three to five minutes to complete.

    Teams runs your app in a web browser.

  2. Sign in with your Microsoft 365 account, if prompted.

  3. Select Add to upload the custom bot app to Teams.

    Screenshot of the app details dialog to add the bot app to Teams.

  4. Select Open to open the app in personal scope.

    Alternatively, you can either search and select the required scope or select a channel, chat, or meeting from the list, and move through the dialog to select Go.

    Screenshot of the scope selection dialog with a list of shared scopes.

    Now the bot is successfully running on Teams! After the app is loaded, a chat session with the bot opens.

    Screenshot shows the bot is running on Teams client.

    You can type welcome to show an introduction card, and type learn to go to Adaptive Card and bot command documentation.

    Screenshot shows the learn card in the bot on Teams client.

    You can do normal debugging activities, such as setting breakpoints, as with any other web application. Open the bot/teamsBot.js file and locate the onMessage() method. Set a breakpoint on any case. Then, type some text.

    Learn how to troubleshoot if your app doesn't run locally.

    To successfully run your app in Teams, ensure that you've enabled custom app upload in your Teams account. You can learn more about custom app upload in the prerequisites section.

    Important

    Custom app upload is available in Government Community Cloud (GCC) and isn't supported in GCC High, DoD, and Teams operated by 21Vianet.

    Tip

    Check for issues before you upload a custom app, using the app validation tool. This tool is included in the toolkit. Fix the errors to upload the app.

Deploy your first Teams app

You've learned to create, build, and run Teams app with Bot capability. The final step is to deploy your app on Azure.

Let's deploy the first app with Bot capability on Azure using Agents Toolkit.

Sign in to your Azure account

Use this account to access the Microsoft Azure portal and to provision new cloud resources to support your app.

  1. Open Visual Studio Code.

  2. Open the project folder in which you created the bot app.

  3. Select the Microsoft 365 Agents Toolkit icon in the sidebar.

  4. Select Sign in to Azure using your credentials.

    Tip

    If you have the AZURE ACCOUNT extension installed and are using the same account, you can skip this step. Use the same account as you are using in other extensions.

    Your default web browser opens to let you sign in to the account.

  5. Close the browser when prompted and return to Visual Studio Code.

    The ACCOUNTS section of the sidebar shows the two accounts separately. It also lists the number of usable Azure subscriptions available to you. Ensure you have at least one usable Azure subscription available. If not, sign out and use a different account.

Congratulations, you have created a Teams app! Now let's go ahead and learn how to deploy one of the apps to Azure using Agents Toolkit.

Provision and Deploy your app on Azure

Deployment consists of two steps. First, Azure creates necessary cloud resources (also known as provisioning). Then, Azure copies your app's code into the created cloud resources. For this tutorial, you'll deploy the bot app.

What's the difference between Provision and Deploy?
The Provision step creates resources in Azure and Microsoft 365 for your app, but doesn't copy code (HTML, CSS, or JavaScript) to the resources. The Deploy step copies the code for your app to the resources you created during the provision step. It's common to deploy multiple times without provisioning new resources. Since the provision step can take some time to complete, it's separate from the deployment step.

Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code sidebar.

  1. Select Provision.

    Screenshot shows the selection of provision in the cloud under Agents toolkit.

  2. Select a subscription to use for the Azure resources.

    Screenshot shows the subscription to use for the Azure resources.

    Your app is hosted using Azure resources.

    A dialog warns you that costs may be incurred when running resources in Azure.

  3. Select Provision.

    Screenshot shows a dialog box that costs may be incurred when running resources in Azure.

    The provisioning process creates resources in the Azure cloud. It may take some time. You can monitor the progress by watching the dialogs in the bottom-right corner. After a few minutes, you see the following notice:

    Screenshot shows a notice, which displays hellomsg successfully provisioned in the cloud.

    If you want, you can view the provisioned resources. For this tutorial, you don't need to view resources.

    The provisioned resource appears in the ENVIRONMENT section.

    Screenshot shows the resource being provisioned in the environment section.

  4. Select Deploy from the LIFECYCLE panel after provisioning is complete.

    Screenshot shows deploy to cloud highlighted in red.

    As with provisioning, deployment takes some time. You can monitor the process by watching the dialogs in the bottom-right corner. After a few minutes, you see a completion notice.

Now, you can use the same process to deploy your Bot and Message Extension apps to Azure.

Run the deployed app

Once the provisioning and deployment steps are complete:

  1. Open the debug panel (Ctrl+Shift+D / ⌘⇧-D or View > Run) from Visual Studio Code.

  2. Select Launch Remote (Edge) from the launch configuration dropdown.

  3. Select the Start debugging (F5). You're prompted to upload the custom bot app to Teams.

    Screenshot shows the debug and launch app remotely.

  4. Select Add.

    Screenshot of the app details dialog to add the app to Teams.

  5. Select Open to open the app in personal scope.

    Alternatively, you can either search and select the required scope or select a channel, chat, or meeting from the list, and move through the dialog to select Go.

    The screenshot of the scope selection dialog with the list of shared scopes.

    You successfully added your bot app to the Teams client.

    Screenshot shows the learn card in the bot on Teams client.

Learn what happens when you deployed your app to Azure

Before deployment, the application has been running locally:

  • The backend runs using Azure Functions Core Tools.
  • The application HTTP endpoint, where Microsoft Teams loads the application, runs locally.

Deployment is a two-step process. You provision the resources on an active Azure subscription, and then deploy or upload the backend and frontend code for the application to Azure.

  • The backend, if configured, uses various Azure services, including Azure App Service and Azure Storage.
  • The frontend application is deployed to an Azure Storage account configured for static web hosting.

Congratulations!

You've done it!

You've created a bot app.

Now that you've learned to create a basic app, you can move on to creating more complex apps. You've completed the tutorial to build bot with JavaScript.

Tutorials

Debug your AI chat bot using Microsoft 365 Agents Playground

Start Microsoft Teams app development with your Teams AI chat bot app and debug with Microsoft 365 Agents Playground (previously known as Teams App Test Tool). Agents Playground makes debugging bot-based apps effortless. You don't need a Microsoft 365 developer account, tunneling, or Teams app and bot registration to use Agents Playground.


Tutorial: Debug your AI chat bot

Prerequisites

You can chat with your bot and view the messages and Adaptive Cards as they appear in Teams. You can also mock an activity in Agents Playground using activity triggers.

Note

  • Agents Playground is available only in v5.4.0 of Microsoft 365 Agents Toolkit (previously known as Teams Toolkit).
  • Agents Playground is supported only for desktop and web clients.

This step-by-step guide helps you to build an AI chat bot using Agents Toolkit and debug with the Test Tool. You'll see the following output after you've completed this guide, where the user can access and use the AI chat bot:

Screenshot shows the bot open in Test Tool.

Install For using...
Visual Studio Code or Visual Studio JavaScript, TypeScript, or C# build environments. Use the latest version.
Microsoft 365 Agents Toolkit Microsoft Visual Studio Code extension that creates a project scaffolding for your app. Use Agents Toolkit v5.4.0. For more information, see install Agents Toolkit.
Node.js Back-end JavaScript runtime environment. For more information, see Node.js version compatibility table for project type.
OpenAI or Azure OpenAI First create your OpenAI API key to use OpenAI's GPT. If you want to host your app or access resources in Azure, you must create an Azure OpenAI service.
Microsoft Edge (recommended) or Google Chrome A browser with developer tools.

Create project workspace for your AI chat bot app

The bot capability of a Teams app creates a chatbot or a conversational bot. It communicates with a web service, facilitating the use of its services. The bot can execute simple, automated tasks such as delivering customer service. You can get weather forecast, make reservations, or any other service offered using a conversational bot.

The screenshot shows you the app with three features. Bot is highlighted.

As you've already prepared for creating these apps, you can set up a new Teams project for creating the AI chat bot app.

Create your bot project workspace

If the prerequisites are in place, let's begin!

  1. Open Visual Studio Code.

  2. Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code Activity Bar.

  3. Select Create a New Agent/App.

    The screenshot shows the location of the Create New Project link in the Agents Toolkit sidebar.

  4. Select Agents for Teams > Azure OpenAI > enter an input in Input Azure API service key now

    Screenshot shows the Agents Toolkit app templates.

  5. Select Basic Agents for Teams. If you need a different functionality for your bot, select the required option.

    Screenshot shows the app feature to add to your new app.

  6. Select the programming language as JavaScript.

    Screenshot displays the option to select the programming language.

  7. Select Default folder.

    Screenshot displays the selection of default location.

    To change the default location, follow these steps:

    1. Select Browse.

      Screenshot shows the selection of browse location option.

    2. Select the location for the project workspace.

    3. Select Select Folder.

      Screenshot shows the folder to select.

  8. Enter a suitable name for your app and then select the Enter key.

    Screenshot shows where to enter the app name.

    A dialog appears, where you need to choose yes or no to trust the authors of the files in this folder.

    Screenshot shows the dialog to trust or not the authors of the files in this folder.

Now, you've successfully created your AI chat bot project workspace.

Take a tour of the bot app source code

After you finish scaffolding, explore the project directories and files in the EXPLORER section of the Visual Studio Code.

Screenshot shows the Teams Toolkit sample bot folder Structure.

Folder or file name Contents
env/.env.playground The configuration file with environment variables that can be committed to Git.
env/.env.playground.user The configuration file with environment variables, including credentials, which aren't committed to Git by default.
appPackage App manifest template files and app icons (color.png and outline.png).
appPackage/manifest.json App manifest for running the app in local and remote environment.
src/app.js Handles business logics for the AI chat bot.
m365agents.yml This is the main Agents Toolkit project file. The project file defines two primary things: Properties and configuration and stage definitions.
m365agents.local.yml This overrides m365agents.yml with actions that enable local execution and debugging.
m365agents.playground.yml This overrides m365agents.yml with actions that enable local execution and debugging in Test Tool.

Build and run your AI chat bot app

Create OpenAI key and endpoint for your AI chat bot

  1. Go to Azure portal.

  2. Select Create a resource and search for Azure OpenAI.

  3. Select Azure OpenAI and select Create.

    Screenshot shows the Azure OpenAI in Azure portal.

  4. Fill the required details and select Next.

    Screenshot shows you the Azure OpenAI subscription and resource group.

  5. Select All networks, including the internet, can access this resource and then select Next.

    Screenshot shows the Azure OpenAI network details.

  6. Fill the required details and select Next.

    Screenshot shows the Azure OpenAI tags details.

  7. Select Create.

    Screenshot shows you to preview and create Azure OpenAI.

You've successfully created key and endpoint for your AI chat bot.

Screenshot shows the deployment of the Azure OpenAI.

Note

You can also get OpenAI API key to debug your AI chat bot.

Get Azure OpenAI keys and endpoint
  1. Select Go to resources.

    Screenshot shows you the deployment of the Azure OpenAI.

  2. Select Keys and Endpoint from the left pane and copy the KEY and Endpoint. You can copy either KEY 1 or KEY 2.

    Screenshot shows the keys and endpoints.

    Save the KEY and Endpoint for further use.

  3. Select Model deployments from the left pane and select Manage Deployments.

    Screenshot shows the model deployment for Azure OpenAI.

    The Azure OpenAI Studio window appears.

  4. Select Deployments from the left pane and select + Create new deployment.

    Screenshot shows the model deployments for Azure OpenAI.

  5. Select the following details:

    1. Select gpt-35-turbo from the Select a model dropdown list.

      Note

      Only gpt-35-turbo model is supported for the AI chat bot.

    2. Select 0301 (Default) from the Model version dropdown list.

    3. Enter Deployment name and select Create.

      Screenshot shows the model and version for Azure OpenAI deployment.

    4. Copy and save the Deployment name for further use.

      Screenshot shows the deployment name for Azure OpenAI deployment.

Update Azure OpenAI key and endpoints

  1. Open your project in Visual Studio Code.

  2. Under EXPLORER, go to env > .env.playground.user file.

  3. Enter your SECRET_AZURE_OPENAI_API_KEY and SECRET_AZURE_OPENAI_ENDPOINT.

    ...
    SECRET_AZURE_OPENAI_API_KEY=<azure-openai-api-key>
    SECRET_AZURE_OPENAI_ENDPOINT=<azure-openai-endpoint>
    
  4. Go to src > app.js file.

  5. Comment the OpenAI code and uncomment the Azure OpenAI code.

  6. Enter your Azure OpenAI deployment name in azureDefaultDeployment.

    
    // Use OpenAI
    // apiKey: config.openAIKey,
    // defaultModel: "gpt-3.5-turbo",
    
    azureApiKey: config.azureOpenAIKey,
    azureDefaultDeployment: "gpt-35-turbo",
    azureEndpoint: config.azureOpenAIEndpoint,
    
    

Debug and run your AI chat bot app

  1. From the left pane, select RUN and DEBUG (Ctrl+Shift+D), and then select Debug in Agents Playground from the dropdown list.

    Screenshot shows the option to select debug in Agents Playground.

  2. Agents Playground opens your AI chat bot in a webpage.

    Screenshot shows the bot open in Test Tool.

Activity triggers

There are two types of activity triggers:

Predefined activity triggers

Agents Playground provides predefined activity triggers to test the functionalities of your bot.

Category Activity Handler
Trigger Installation Update Activity Install bot


Uninstall bot
onInstallationUpdate
onInstallationUpdateAdded

onInstallationUpdate
onInstallationUpdateRemove
Trigger Conversation Update Activity Add user


Add bot


Add channel
onMembersAdded
onTeamsMembersAddedEvent

onMembersAdded
onTeamsMembersAddedEvent

onTeamsChannelCreatedEvent
Remove user


Remove bot


Remove channel

Remove team
onMembersRemoved
onTeamsMembersRemovedEvent

onMembersRemoved
onTeamsMembersRemovedEvent

onTeamsChannelDeletedEvent

onTeamsTeamDeletedEvent
Rename channel

Rename team
onTeamsChannelRenamedEvent

onTeamsTeamRenamedEvent

Note

All types of activities aren't available in all scopes. For example, you can't add or remove a channel in a personal chat or a group chat.

Predefined activity triggers are available in the Mock an Activity menu in Agents Playground.

To mock an Add user activity, follow these steps:

  1. In Agents Playground, go to Mock an Activity > Add user.

    Screenshot shows the Add user option under mock an activity.

    A dialog appears to preview the activity handler.

  2. Select Send activity.

    Screenshot shows the option to send activity for predefined mock activity add user.

    Bot sends the following response:

    Screenshot shows the response of predefined mock activity add user.

Custom activity triggers

You can use Custom activity to customize activity triggers, for example, reactionsAdded to meet the requirements of your bot app. Agents Playground automatically populates the required properties of the activity. You can also modify the activity type and add more properties.

  1. Select Mock an Activity > Custom activity.

    Screenshot shows the list of option under mock an activity.

  2. Add messageReaction to customize the activity under the type property:

    {
        "type": "messageReaction",
        "reactionsAdded": [
        {
            "type": "like"
        }
        ],
        "replyToId": "d60fd1cb-3e8f-44ef-849c-404806ba1b47"
    }
    
  3. Select Send activity.

    Screenshot shows the option to send activity after customization on mock activity.

    Bot sends an onReactionsAdded handler in response.

    Screenshot shows the response of custom mock activity.

Complete challenge

Did you come up with output like this?

Screenshot shows the bot open in Test Tool.

Congratulations! You've successfully created an AI chat bot app. Now, you've learned to debug your AI chat bot app in Agents Playground.

Back to top

Send proactive messages

A proactive message is a message sent by a bot in response to simple commands sent in the chat from a user.


Tutorial: Send proactive messages

The message response can be in one of the following formats:

  • Welcome messages
  • Scheduled messages
  • Notifications

This step-by-step guide helps you to send a proactive message from a bot. You'll see the following output:

Screenshot shows the proactive hello message in Teams chat.

Prerequisites

Ensure that you install the following tools for building and deploying your apps.

  Install For using
  Microsoft Visual Studio Code JavaScript or TypeScript, build environments. Use the latest version.
  Microsoft 365 Agents Toolkit (previously known as Teams Toolkit) Visual Studio Code extension that creates a project scaffolding for your app. Use the latest version.
  Node.js Back-end JavaScript runtime environment. For more information, see Node.js version compatibility table for project type.
  Microsoft Teams Teams to collaborate with everyone you work with through apps for chat, meetings, call and all in one place.
  Microsoft Edge (recommended) or Google Chrome A browser with developer tools.
  Microsoft 365 developer account Access to Teams account with the appropriate permissions to install an app.

Prepare development environment

After you install the required tools, set up the development environment.

Install Microsoft 365 Agents Toolkit

Microsoft 365 Agents Toolkit (previously known as Teams Toolkit) helps simplify the development process with tools to provision and deploy cloud resources for your app and publish to the Teams Store.

You can use Agents Toolkit with Visual Studio Code or a command-line interface called Microsoft 365 Agents Toolkit CLI (previously known as TeamsFx CLI).

  1. Open Visual Studio Code and select Extensions (Ctrl+Shift+X or View > Extensions).

  2. In the search box, enter Microsoft 365 Agents Toolkit.

  3. Select Install.

    Screenshot shows the Agents Toolkit extension installation.

    The Microsoft 365 Agents Toolkit icon appears in the Visual Studio Code Activity Bar.

You can also install Agents Toolkit from the Visual Studio Code Marketplace.

Set up your Teams development tenant

A tenant is a space or a container for your organization in Teams, where you chat, share files, and run meetings. This space is also where you upload and test your app. Let's verify if you're ready to develop with the tenant.

Check for upload an app option

After creating your custom app, you must upload your app to Teams with the Upload a custom app option. Sign in to your Microsoft 365 account to check if this option is enabled.

The following steps help you verify if you can upload apps in Teams:

  1. In the Teams client, select the Apps icon.

  2. Select Manage your apps.

  3. Select Upload an app.

  4. Look for the option to Upload a custom app. If the option is visible, you can upload custom apps.

    Screenshot shows the option to upload a custom app in Teams.

    Note

    If you don't find the option to upload a custom app, contact your Teams administrator.

Create a free Teams developer tenant (optional)

If you don't have a Teams developer account, join the Microsoft 365 developer program.

  1. Go to the Microsoft 365 developer program.

  2. Select Join Now and follow the onscreen instructions.

  3. In the welcome screen, select Set up E5 subscription.

  4. Set up your administrator account. After you finish, the following screen appears:

    This screenshot displays the Microsoft 365 Developer Program.

  5. Sign in to Teams using the administrator account you just set up. Verify that you have the Upload a custom app option in Teams.

Build Proactive Message bot

To build proactive message bot using Visual Studio Code, follow these steps:

  1. Open Visual Studio Code.

  2. Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code Activity Bar.

  3. In the left pane, select View Samples.

    Screenshot shows the View Samples option in Visual Studio Activity Bar.

  4. From the list of samples, select Proactive Messaging. A prebuilt sample that's ready for debugging opens.

    Screenshot shows the prebuilt Proactive Messaging bot sample in the list of samples.

  5. Select Create.

    Screenshot shows the Create option to create a proactive messaging bot.

  6. Select Default folder to store your project root folder in the default location.

    Screenshot shows the option to select the default location.

    If you want to change the default location, perform the following steps:

    1. Select Browse.

      Screenshot shows the option to browse the location.

    2. Select the location for project workspace.

    3. Select Select Folder.

      Screenshot shows the option to select the folder.

    The proactive message bot is created in a few seconds and displays the proactive message bot successful dialog in the lower-right corner with the option to debug:

    Screenshot shows the proactive message bot created. :::

  7. Select Run and Debug icon from the top-left corner.

  8. Select Debug (Edge) or Debug (Chrome) from the dropdown list.

    Screenshot shows the debugging options to choose from.

    When debugging is successful, you are prompted to upload the proactive message bot to Teams on your local machine.

  9. Select Add.

    Screenshot of message extension details dialog with the Add option highlighted.

  10. Search and select the required scope or select a channel, chat, or meeting from the list, and move through the dialog to select Go.

    Screenshot of the scope selection dialog showing the list of shared scopes.

    The proactive message bot app is uploaded to Teams client and the following message appears in response to the message sent.

    Screenshot shows the proactive message bot response in the chat.

  11. Copy and paste the URL or navigate to the URL in browser. A proactive hello message is triggered and shared in the chat.

    Screenshot shows the browser that triggers bot to respond with a proactive message in Teams.

  12. Go to Teams. You'll receive a proactive hello message from the bot.

    Screenshot shows the bot response on the chat.

Take a tour of the source code

Agents Toolkit provides components for building an app. After creating the project, you can view the project folders and files in the EXPLORER area of Visual Studio Code.

Screenshot shows the structure tab.

The new project folder contains the following content:

Folder / File Contents
.vscode/ Visual Studio Code files for debugging.
appManifest/ Templates for the app manifest (previously called Teams app manifest).
env/ Name / value pairs are stored in environment files and used by m365agents.yml to customize the provisioning and deployment rules.
manifest.json App manifest for publishing through the Developer Portal for Teams is stored in Properties/manifest.json.
m365agents.yml Main project file describes your app configuration and defines the set of actions to run in each lifecycle stage.
m365agents.local.yml This overrides m365agents.yml with actions that enable local execution and debugging.

Deploy your Proactive message bot

You've learnt to build and run Teams app with proactive message bot capability. Let's deploy the first app with proactive message bot capability on Azure using Agents Toolkit.

Sign in to your Azure account

Use your account to access the Microsoft Azure portal and provision new cloud resources to support your app.

  1. Open Visual Studio Code.

  2. Open the project folder where you created the proactive message bot app.

  3. Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code Activity Bar.

  4. Select Sign in to Azure using your credentials.

    Tip

    If you have the AZURE ACCOUNT extension installed and are using the same account, you can skip this step.

    Your default web browser opens to let you sign in to the account.

  5. Close the browser when prompted and return to Visual Studio Code.

The ACCOUNTS section of the sidebar shows the two accounts separately. It also lists the number of usable Azure subscriptions available to you. Ensure that you have at least one usable Azure subscription available. If not, sign out and use a different account.

Deploy your app to Azure

Deployment consists of two steps. First, necessary cloud resources are created (also known as provisioning). Then, your app's code is copied into the created cloud resources. For this tutorial, you'll deploy the bot app.

What's the difference between Provision and Deploy?
Provision creates resources in Azure and Microsoft 365 for your app, but no code (HTML, CSS, and JavaScript) is copied to the resources.
Deploy copies the code for your app to the resources you created during provisioning. It's common to deploy multiple times without provisioning new resources. Since provisioning can take some time to complete, it's separate from deployment.

  1. Select the Microsoft 365 Agents Toolkit icon in the Visual Studio Code Activity Bar.

  2. Select Provision under LIFECYCLE.

    Screenshot shows the provisioning commands.

  3. Select one of the existing subscriptions.

    Screenshot shows the subscription option for provisioning.

  4. Select an existing resource group or create new resource group. For more information, see create resource group.

    Screenshot show the resource group option for provisioning.

    Note

    A dialog appears mentioning that costs might be incurred when running resources in Azure.

  5. Select Provision.

    Screenshot of the provisioning dialog.

    The provisioning process creates resources in the Azure cloud. You can monitor the progress in the dialogs that appear in lower-right corner. After few minutes, the following dialog appears:

    Screenshot shows the provisioning complete dialog.

  6. Select Deploy under LIFECYCLE.

    Screenshot shows the Deploy option under LIFECYCLE.

  7. Select Deploy.

    Screenshot shows the confirmation dialog to deploy.

    Deployment takes some time. You can monitor the progress in the dialogs that appear in lower-right corner. After a few minutes, the following dialog appears.

    Screenshot shows the deployment confirmation dialog.

  8. Open the debug panel (Ctrl+Shift+D / ⌘⇧-D or View > Run) from Visual Studio Code.

  9. Select Launch Remote (Edge) from the launch configuration dropdown list.

    Screenshot shows the remote debug option highlighted.

    When debugging is successful, you are prompted to upload the proactive message bot app to Teams.

  10. Select Add.

    Screenshot of message extension app dialog with the Add option highlighted.

  11. Search and select the required scope or select a channel, chat, or meeting from the list, and move through the dialog to select Go.

    Screenshot shows the scope selection dialog with the list of shared scopes.

    The proactive message bot app is uploaded to Teams client and the following message appears in response to the message sent.

    Screenshot shows the proactive message bot response in the chat.

  12. Copy and paste the URL or navigate to the URL in browser. A proactive hello message is triggered and shared in the chat.

    Screenshot shows the browser that triggers bot to respond with a proactive message in Teams.

  13. Go to Teams. You'll receive a proactive hello message from the bot.

    Screenshot shows the bot response on the chat.

Complete challenge

Did you come up with something like this?

Screenshot shows the proactive hello message.

You've completed the scenario.

  • You can send notifications on a daily basis or request for feedback from users on a periodic basis.
  • You can handle throttling limits to avoid multiple notifications.

Back to top

Build API-based message extension

Message extensions built using API (API-based) significantly enhance the functionality of your Teams apps by allowing them to interact with external services. API-based message extensions can help streamline workflows by reducing the need to switch between different applications.


Tutorial: Build API-based message extension

Note

API-based message extensions only support search commands.

You can use API-based message extensions to integrate external services that are commonly used in the business workflow. For example, a business that frequently uses a CRM system for customer management could use a message extension to fetch and display customer data directly from Teams. This app helps save time and improves efficiency by reducing the need to switch between different applications. This feature is supported on all platforms where Teams is available, including desktop, web, and mobile.

Prerequisites for building a message extension

Here's a list of tools you need for building and deploying your apps.

Install For using...
Microsoft Teams Microsoft Teams to collaborate with everyone you work with through apps for chat, meetings, or call - all in one place.
Microsoft Edge (recommended) or Google Chrome A browser with developer tools.
Visual Studio Code JavaScript, TypeScript, or SharePoint Framework (SPFx) build environments. Use version 1.55 or later.
Microsoft 365 developer account Access to Teams account with the appropriate permissions to install an app.
Azure account Access to Azure resources.
OpenAPI Description (OAD) document A document that describes the capabilities of your API. For more information, see OpenAPI Description.

Set up your Teams development tenant

A tenant is like a space, or a container for your organization in Teams, where you chat, share files, and run meetings. This space is also where your upload and test your custom app. Let's verify if you're ready to develop with the tenant.

Check for custom app upload option

After creating the app, you must load your app in Teams without distributing it. This process is known as custom app upload. Sign in to your Microsoft 365 account to view this option.

Note

Custom app upload is necessary for previewing and testing apps in Teams local environment. If it isn't enabled, you can't preview and test your app in Teams local environment.

Do you already have a tenant, and do you have the admin access? Let's check if you really do!

Verify if you can upload a custom app in Teams:

  1. In the Teams client, select the Apps icon.

  2. Select Manage your apps.

  3. Select Upload an app.

  4. Look for the option to Upload a custom app. If you see the option, custom app upload is enabled.

    Screenshot shows the bot home.

Note

Contact your Teams administrator if you don't find the option to upload a custom app.

Create a free Teams developer tenant (optional)

If you don't have a Teams developer account, you can get it free. Join the Microsoft 365 developer program!

  1. Go to the Microsoft 365 developer program.

  2. Select Join Now and follow the onscreen instructions.

  3. In the welcome screen, select Set up E5 subscription.

  4. Set up your administrator account. After you finish, the following screen appears.

    The screenshot displays the Microsoft 365 Developer Program.

  5. Sign in to Teams using the administrator account you just set up. Verify that you have the Upload a custom app option in Teams.

Get a free Azure account

If you want to host your app or access resources in Azure, you must have an Azure subscription. Create a free account before you begin.

You have all the tools to set up your account. Next, let's set up your development environment and start building! Select the app you want to build first.

Create OpenAPI Description document

OpenAPI Description (OAD) is the industry-standard specification that outlines how OpenAPI files are structured and outlined. It's a language-agnostic, human-readable format for describing APIs. It's easy for both humans and machines to read and write. The schema is machine-readable and represented in either YAML or JSON.

To interact with the APIs, an OpenAPI Description document is necessary. The OpenAPI Description document must meet the following criteria:

  • The auth property must not be specified.

  • JSON and YAML are the supported formats.

  • OpenAPI Versions 2.0 and 3.0.x are supported.

  • Teams doesn't support the oneOf, anyOf, allOf, and not (swagger.io) constructs.

  • Constructing arrays for the request isn't supported, however, nested objects within a JSON request body are supported.

  • The request body, if present, must be application/Json to ensure compatibility with a wide range of APIs.

  • Define an HTTPS protocol server URL for the servers.url property.

  • Only single parameter search is supported.

  • Only one required parameter without a default value is allowed.

  • Only POST and GET HTTP methods are supported.

  • The OpenAPI Description document must have an operationId.

  • The operation mustn't require Header or Cookie parameters without default values.

  • A command must have exactly one parameter.

  • Ensure that there are no remote references in the OpenAPI Description document.

  • A required parameter with a default value is considered optional.

    We used the following OpenAPI Description as an example for this tutorial:

    OpenAPI Description
        openapi: 3.0.1
        info:
        title: OpenTools Plugin
        description: A plugin that allows the user to find the most appropriate AI tools for their use cases, with their pricing information.
        version: 'v1'
        servers:
            - url: https://gptplugin.opentools.ai
        paths:
        /tools:
        get:
        operationId: searchTools
        summary: Search for AI Tools
            parameters:
            - in: query
              name: search
              required: true
              schema:
              type: string
              description: Used to search for AI tools by their category based on the keywords. For example, a search for "tool to create music" provides a list of tools that can create music.
            responses:
            "200":
              description: OK
              content:
              application/json:
                schema:
                $ref: '#/components/schemas/searchToolsResponse'
            "400":
              description: Search Error
              content:
              application/json:
                schema:
                ref: '#/components/schemas/searchToolsError'
            components:
            schemas:
            searchToolsResponse:
            required:
            - search
            type: object
            properties:
            tools:
            type: array
            items:
            type: object
            properties:
            name:
            type: string
            description: The name of the tool.
            opentools_url:
            type: string
            description: The URL to access the tool.
            main_summary:
            type: string
            description: A summary of what the tool is.
            pricing_summary:
            type: string
            description: A summary of the pricing of the tool.
            categories:
            type: array
            items:
            type: string
            description: The categories assigned to the tool.
            platforms:
            type: array
            items:
            type: string
            description: The platforms that this tool is available on.
            description: The list of AI tools.
            searchToolsError:
            type: object
            properties:
            message:
            type: string
            description: Message of the error.
    
    

    Note

    Ensure that the required: true property is available for only one parameter. If there are more than one required parameters, you can update the required property to required: false for the other parameters.

You can validate if the OpenAPI Description document is valid. To verify, follow these steps:

  1. Go to Swagger or OpenAPI validator and validate the OpenAPI Description document.

  2. Save the OpenAPI Description document.

  3. Go to Swagger Editor.

  4. In the left pane, paste the OpenAPI Description in the editor.

  5. In the right pane, select GET.

  6. Select Try it out.

  7. Enter the values for the search parameter as Tool to create music.

  8. Select Execute. The swagger editor displays a response with a list of products.

    Screenshots shows the parameters, its values, and the **EXECUTE** option in the swagger editor.

  9. Go to Server response > Response Body.

  10. Under products, copy the first product from the list and save it for future reference.

    Screenshots shows the highlighted product that is selected from the response body.

Create response rendering template

An OpenAPI Description document requires a response rendering template for the app to respond to the GET or POST requests. The response rendering template consists of an Adaptive Card template, Preview card template, and metadata.

Adaptive Card template

To create an Adaptive Card template, follow these steps:

  1. Go to ChatGPT and ask the following query in the message compose area:

    
    Create an Adaptive Card Template that binds to the following response:
        "categories": [
            "Music Generation",
            "AI Detection"
        ],
        "chatbot_short_url": "https://goto.opentools.ai/c/ai-music-generator",
        "main_summary": "AI Music Generator is an AI-powered music composing tool that allows users to create original and personalized music for various purposes. It can generate melodies, harmonies, and rhythms tailored to specific needs and preferences, with customization options such as genre, mood, length, and instrumentation. The tool is designed for creative individuals, from beginners to professionals, and can produce high-quality music in seconds. Every generated piece of music is royalty-free and can be used instantly, with no limitations on beat creation. With advanced AI technology, AI Music Generator makes music production accessible to everyone.",
        "name": "AI Music Generator",
        "opentools_url": "https://goto.opentools.ai/ai-music-generator",
        "platforms": [
            "Web",
            "App",
            "API"
        ]
    
  2. Select Send message.

  3. ChatGPT generates a response with an Adaptive Card template that binds to the sample data. Save the Adaptive Card template for future reference.

    Following is an example of the Adaptive Card template:

    Adaptive Card template
    
    {
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "type": "AdaptiveCard",
    "version": "1.4",
    "body": [
        {
        "type": "TextBlock",
        "text": "AI Music Generator",
        "weight": "Bolder",
        "size": "Large"
        },
        {
        "type": "TextBlock",
        "text": "Categories",
        "size": "Medium"
        },
        {
        "type": "TextBlock",
         "text": "Music Generation, AI Detection",
         "wrap": true
        },
        {
        "type": "TextBlock",
        "text": "Description",
        "size": "Medium"
        },
        {
        "type": "TextBlock",
        "text": "AI Music Generator is an AI-powered music composing tool that allows users to create original and personalized music for various purposes. It can generate melodies, harmonies, and rhythms tailored to specific needs and preferences, with customization options such as genre, mood, length, and instrumentation. The tool is designed for creative individuals, from beginners to professionals, and can produce high-quality music in seconds. Every generated piece of music is royalty-free and can be used instantly, with no limitations on beat creation. AI Music Generator is powered by advanced AI technology, and it makes music production accessible to everyone.",
        "wrap": true
        },
        {
        "type": "TextBlock",
        "text": "Platform",
        "size": "Medium"
        },
        {
        "type": "TextBlock",
        "text": "Web, App, API",
        "wrap": true
        }
    ],
    "actions": [
        {
        "type": "Action.OpenUrl",
        "title": "Learn More",
        "url": "https://goto.opentools.ai/ai-music-generator"
        },
        {
        "type": "Action.OpenUrl",
        "title": "Try It",
        "url": "https://goto.opentools.ai/c/ai-music-generator"
        }
    ]
    }
    
    
  4. To verify if the Adaptive Card generated binds to the sample data, follow these steps:

    1. Go to Adaptive Card Designer.

    2. Go to Select host app, and then select Microsoft Teams from the dropdown.

    3. Go to CARD PAYLOAD EDITOR and paste the Adaptive Card template code.

    4. Go to SAMPLE DATA EDITOR and paste the GET API response that you saved earlier.

      Screenshots shows the Adaptive Card designer with the Adaptive Card template and the sample data.

    5. Select Preview mode. The Adaptive Card designer displays an Adaptive Card with the data that binds the response to the template.

      Screenshot shows the Adaptive Card designer with the Adaptive Card template and the sample data.

Create a preview card template

The preview card template can contain a title, subtitle, and image properties. If the API response doesn't have an image, you can remove the image property.

Following is an example of a preview card template:

Preview card template
   "previewCardTemplate": {
        "title": "${if(name, name, 'N/A')}",
        "subtitle": "$${if(price, price, 'N/A')}"
    } 

Create an if condition for the title and subtitle, where:

  • If name exists, the bot uses the name.
  • If name doesn't exist, the bot uses NA.

For example, "title": "Name: ${if(name, name, 'N/A')}". Save the preview card template for future reference.

Response rendering template

The response rendering template must conform to the schema hosted at https://developer.microsoft.com/json-schemas/teams/v1.20/MicrosoftTeams.ResponseRenderingTemplate.schema.json.

To create a response rendering template, follow these steps:

  1. Create a JSON file and add the following code to the file:

    { 
      "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.20/MicrosoftTeams.ResponseRenderingTemplate.schema.json", 
      "version": "1.0", 
      "jsonPath": "", 
      "responseLayout": "", 
      "responseCardTemplate": { 
     },
     "previewCardTemplate": {
         }
     }
    
  2. Update the properties in the response rendering template as follows:

    # Property name Value
    1. "$schema" "https://developer.microsoft.com/json-schemas/teams/v1.20/MicrosoftTeams.ResponseRenderingTemplate.schema.json"
    2. "version" "1.0"
    version is the version of the rendering template to use.
    3. "jsonPath" "tools"
    jsonPath is the path to one or more results in the response JSON response. Add the jsonPath to the relevant data/array from the product list in the API response. In this case, the jsonPath is tools. For more information on how to determiner the JSON path, see Querying JSON with JSON path.
    4. "responseLayout" "list"
    responseLayout specifies the layout of the attachments. Used for responses of type result. Supported types are list and grid. If the response body contains an object with multiple elements like text, title, and image, then the response layout must be set to list. If the API response contains only images or thumbnails, then the response layout must be set to grid.
    5. "responseCardTemplate" Paste the Adaptive Card template code that you saved earlier.
    responseCardTemplate is an Adaptive Card template to map the JSON response to an Adaptive Card.
    6. "previewCardTemplate" Paste the preview card template code that you saved earlier.
    previewCardTemplate is a preview card template is used to show a preview of results in the message extension flyout.
  3. Save the response rendering template in the same folder you saved the OpenAPI Description document.

The following code is an example of a Response rendering template:

Response rendering template

{
    "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.20/MicrosoftTeams.ResponseRenderingTemplate.schema.json",
    "version": "1.0",
    "jsonPath": "tools",
    "responseLayout": "list",
    "responseCardTemplate": {
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            {
            "type": "TextBlock",
            "text": "AI Music Generator",
            "weight": "Bolder",
            "size": "Large"
            },
            {
            "type": "TextBlock",
            "text": "Categories",
            "size": "Medium"
            },
            {
            "type": "TextBlock",
            "text": "Music Generation, AI Detection",
            "wrap": true
            },
            {
            "type": "TextBlock",
            "text": "Description",
            "size": "Medium"
            },
            {
            "type": "TextBlock",
            "text": "AI Music Generator is an AI-powered music composing tool that allows users to create original and personalized music for various purposes. It can generate melodies, harmonies, and rhythms tailored to specific needs and preferences, with customization options such as genre, mood, length, and instrumentation. The tool is designed for creative individuals, from beginners to professionals, and can produce high-quality music in seconds. Every generated piece of music is royalty-free and can be used instantly, with no limitations on beat creation. With advanced AI technology, AI Music Generator makes music production accessible to everyone.",
            "wrap": true
            },
            {
            "type": "TextBlock",
            "text": "Platform",
            "size": "Medium"
            },
            {
            "type": "TextBlock",
            "text": "Web, App, API",
            "wrap": true
            }
        ],
        "actions": [
            {
            "type": "Action.OpenUrl",
            "title": "Learn More",
            "url": "https://goto.opentools.ai/ai-music-generator"
            },
            {
            "type": "Action.OpenUrl",
            "title": "Try It",
            "url": "https://goto.opentools.ai/c/ai-music-generator"
            }
        ]
    },
    "previewCardTemplate": {
        "title": "${if(name, name, 'N/A')}",
        "subtitle": "$${if(price, price, 'N/A')}"
    } 
}

Create app manifest

Now, you need to create an app manifest (previously called Teams app manifest). The app manifest describes how your app integrates into the Microsoft Teams product.

Create a Teams app manifest

To create the manifest, follow these steps:

  1. Create a new JSON file. Your app manifest must conform to the 1.20 version of the schema defined in App manifest schema.

  2. Add the following code to the JSON file:

    App manifest
    {
     "$schema": "https://developer.microsoft.com/json-schemas/teams/v1.20/MicrosoftTeams.schema.json",
     "manifestVersion": "1.20",
     "version": "1.0.3",
     "id": "<<YOUR-MICROSOFT-APP-ID>>",
     "packageName": "com.microsoft.teams.extension",
     "developer": {
         "name": "Teams App, Inc.",
         "websiteUrl": "https://www.example.com",
         "privacyUrl": "https://www.example.com/termofuse",
         "termsOfUseUrl": "https://www.example.com/privacy"
     },
     "icons": {
         "color": "color.png",
         "outline": "outline.png"
     },
     "name": {
         "short": "Search ME API",
         "full": "Search ME API full"
     },
     "description": {
         "short": "product app for testing API Message Extensions",
         "full": "product app for testing API Message Extensions"
     },
     "accentColor": "#FFFFFF",
     "composeExtensions": [
         {
             "composeExtensionType": "",
             "apiSpecificationFile": "",
             "commands": [
                 {
                     "context": [
                         "compose"
                     ],
                     "type": "query",
                     "title": "API for fetching Klarna.",
                     "id": "",
                     "parameters": [
                         {
                             "name": "",
                             "title": "",
                             "description": ""
                         }
                     ],
                     "description": "",
                     "apiResponseRenderingTemplateFile": ""
                 }
             ]
         }
     ],
     "permissions": [
         "identity",
         "messageTeamMembers"
     ],
     "validDomains": []
    }
    
  3. Update the app manifest properties as follows:

    • Replace <<YOUR-MICROSOFT-APP-ID>> with bot's Microsoft App ID.
    • Update the value for composeExtensionType to apiBased.
    • Update the value for apiSpecificationFile to the path of your OpenAPI Description file.
    • Update the value for commands.id to searchTools.
    • Update the value for commands.title to Search for AI Tools.
    • Update the value for commands.description to Search for AI Tools.
    • Update the value for parameters.name to search. If there are no parameters, then the values must be query parameters or properties.name if referencing a property in the request body schema.
    • Update the apiResponseRenderingTemplateFile to the path of your response rendering template file.
    • Update the value for validDomains to the service URL endpoint defined in the OpenAPI Description file.
  4. Save the Teams app manifest in the same folder you saved the OpenAPI Description document and the response rendering template.

    • You need a color image and outline image. These images should be included in the folder and referenced in your Teams app manifest.

    • Zip up the contents of the folder. The zip file must include the following files:

      • OpenAPI Description document
      • Response rendering template
      • App manifest
      • Color icon
      • Outline icon

Upload a custom app to Teams

Sign into Teams test environment to test your app in Teams. To upload a custom app in Teams, follow these steps:

  1. Go to Microsoft Teams and sign in using your test tenant credentials.

  2. Go to Apps > Manage your app > Upload an app.

  3. Select Upload a customized app.

  4. Select the zip file created and select Open.

  5. Select Add.

    Screenshot of message extension app with the Add option highlighted.

  6. Select Open.

    Screenshot of message extension app with the Open option highlighted.

  7. Go to a chat, then select + from the message compose area, and search for your app.

  8. Select the app and make a search query.

    Screenshot shows that from the plus icon in the chat menu, users can invoke the message extension app that is displayed in the flyout menu.

  9. The app responds with an Adaptive Card in the chat window.

  10. Select Send.

    Screenshot shows the Adaptive Card with the search results in the chat message in Teams.

Congratulations! You did it! You learned to create an API-based message extension using OpenAPI Description document.

Back to top

Build action-based message extension

Teams action based message extension allow users to interact with web services in the Microsoft Teams client. Message extensions help to initiate actions in an external system from the compose message area, the command box, or directly from a message.


Tutorial: Build action-based message extension

Key features of action based message extension:

  • Presents the user with a modal pop-up to collect or display information.
  • Triggers the action commands from the compose message area, the command box, or from a message.

This step-by-step guide helps you to build Teams action-based message extension to initiate actions from compose message and message area. By the end of this tutorial, you can achieve the following output:

Screenshot of the message extension output after you successfully complete the step-by-step guide.

Prerequisites

Ensure that you install the following tools and set up your development environment:

  Install For using...
  Microsoft Teams Microsoft Teams to collaborate with everyone you work with through apps for chat, meetings, and call all in one place.
  Visual Studio 2022 You can install the enterprise version in Visual Studio 2022, and install the ASP.NET and web development workloads. Use the latest version.
  .NET Core SDK Customized bindings for local debugging and Azure Functions app deployments. If you haven't installed the latest version, install the portable version.
  Dev tunnel Teams app features (conversational bots, message extensions, and incoming webhooks) need inbound connections. A tunnel connects your development system to Teams. Dev tunnel is a powerful tool to securely open your localhost to the internet and control who has access. Dev tunnel is available in Visual Studio 2022 version 17.7.0 or later.
or
You can also use ngrok as a tunnel to connect your development system to Teams. It isn't required for apps that only include tabs. This package is installed within the project directory (using npm devDependencies).

Note

After downloading ngrok, sign up and install authtoken.

Set up local environment

  1. Open Microsoft-Teams-Samples.

  2. Select Code.

  3. From the dropdown menu, select Open with GitHub Desktop.

    Screenshot show the option to clone repository in local.

  4. Select Clone.

Register Microsoft Entra app

The following steps help you to create and register your bot in Azure portal:

  • Create and register your Azure app.
  • Create client secret to enable SSO authentication of the bot.
  • Add Teams channel to deploy the bot.
  • Create a tunnel to your web server's endpoints using dev tunnel (recommended) or ngrok.
  • Add messaging endpoint to the dev tunnel that you created.

Add App registration

  1. Go to Azure portal.

  2. Select App registrations.

    Screenshot shows the Azure services to select App registrations.

  3. Select + New registration.

    Screenshot shows the New registration page on Microsoft Entra admin center.

  4. Enter the name of your app.

  5. Select Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant).

  6. Select Register.

    Screenshot shows the option to register the bot in Microsoft Entra admin center.

    Your app is registered in Microsoft Entra ID. The app overview page appears.

    Screenshot shows the app registration overview page.

    Note

    Save the app ID from Application (client) ID and Directory (tenant) ID for further use.

Create a tunnel

Follow one of the following two methods to create a tunnel.

  1. Open Visual Studio.

  2. Select Create a new project.

    Screenshot shows the selection to create a new project.

  3. In the search box, enter ASP.NET. From the search results, select ASP.NET Core Web App.

  4. Select Next.

    Screenshot shows the search and selection of the template.

  5. Enter Project name and select Next.

    Screenshot shows the project name to enter.

  6. Select Create.

    Screenshot shows the project additional information.

    An overview window appears.

    Screenshot shows the overview window.

  7. In the debug dropdown list, select Dev Tunnels (no active tunnel) > Create a Tunnel....

    Screenshot shows the dropdown to select the dev tunnels.

    A pop-up window appears.

  8. Update the following details in the pop-up window:

    1. Account: Enter a Microsoft or GitHub account.
    2. Name: Enter a name for your tunnel.
    3. Tunnel Type: From the dropdown list, select Temporary.
    4. Access: From the dropdown list, select Public.
  9. Select OK.

    Screenshot shows the details to update for creation of tunnel.

    A pop-up window appears showing that dev tunnel is successfully created.

  10. Select OK.

    Screenshot shows the pop-up message that the tunnel is created.

    You can find the tunnel you created in the debug dropdown list as follows:

    Screenshot shows the tunnel is active and selected.

  11. Select F5 to run the application in the debug mode.

  12. If a Security Warning dialog appears, select Yes.

    Screenshot shows the dialog box to accept the security warning.

    A pop-up window appears.

  13. Select Continue.

    Screenshot shows the url for the tunnel.

    The dev tunnel home page opens in a new browser window and the dev tunnel is now active.

    Screenshot shows the dev tunnel welcome page in browser.

  14. Go to Visual Studio, select View > Output.

  15. From the Output console dropdown menu, select Dev Tunnels.

    The Output console shows the dev tunnel URL.

    Screenshot shows the url in the Visual Studio output console.

Add web authentication

  1. In the left pane, under Manage, select Authentication.

  2. Select Add a platform > Web.

    Screenshot shows the selection of web authentication.

  3. Enter the redirect URI for your app by appending auth-end to the fully qualified domain name. For example, https://your-devtunnel-domain/auth-end or https://your-ngrok-domain/auth-end.

  4. Under Implicit grant and hybrid flows, select the Access tokens and ID tokens checkboxes.

  5. Select Configure.

    Screenshot shows the option to add redirect URI and select implicit grant and hybrid flows.

  6. Under Web, select Add URI.

  7. Enter https://token.botframework.com/.auth/web/redirect.

  8. Select Save.

    Screenshot shows the option to add the redirect URI and select implicit grant and hybrid flows.

Create a client secret

Note

If you encounter the error Client secrets are blocked by tenant-wide policy. Contact your tenant administrator for more information., you can create a certificate instead. For step-by-step instructions, refer to create a certificate for app registration.

  1. In the left pane, under Manage, select Certificates & secrets.

  2. Under Client secrets, select + New client secret.

    Screenshot show the selection of new client secret.

    The Add a client secret window appears.

  3. Enter Description.

  4. Select Add.

    Screenshot show the client secret description option to add.

  5. Under Value, select Copy to clipboard to save the client secret value for further use.

    Screenshot show the option to copy the client secret ID value to copy value to clipboard.

Add API permissions

  1. In the left pane, select API permissions.

  2. Select + Add a permission.

    Screenshot shows the option to select Add permission.

  3. Select Microsoft Graph.

  4. Select Delegated permissions.

  5. Select User > User.Read.

  6. Select Add permissions.

    Screenshot shows the option to select permissions.

    Note

    • If an app isn't granted IT admin consent, users must provide consent the first time they use an app.
    • Users need to consent to the API permissions only if the Microsoft Entra app is registered in a different tenant.

Add application ID URI

  1. In the left pane, under Manage, select Expose an API.

  2. Next to Application ID URI, select Add.

    Screenshot shows the option to add Application ID URI for your app.

  3. Update the Application ID URI in the api://botid-{AppID} format and select Save.

    Screenshot shows the option to add the app ID URI and save.

Add a scope

  1. In the left pane, under Manage, select Expose an API.

  2. Select + Add a scope.

    Screenshot shows the selection to Add a Scope.