DEV Community

Cover image for Beginners Guide to MS Teams Development #2: Bots
Tomomi Imura 🐱 for Microsoft Azure

Posted on • Edited on

Beginners Guide to MS Teams Development #2: Bots

Hello, I hope you enjoyed my previous tutorial on how to get started with Microsoft Teams development.

This is the second one of the beginner series, and this time, I will walk you through how to build a conversational bot.

There are many different paths to learn how to build Teams apps, and this tutorial uses a bare-minimum code and minimal toolsets. Also, this tutorial is independent of the hosting environment, so I am not staring the process with the Azure setup, and basically, this should run on any environment. (Although this article is listed under MS Azure πŸ˜‰)


In last article, I showed you how to embed a tab, but in this tutorial, I am going to show you a completely different feature, bots.

Teams features: Bots

There are a variety of features you can use to build Teams app, like Messaging extensions, tabs, etc. and bots turn words into actions, such as, generate an order, review my code, check ticket status, etc. A bot can kick off these kinds of workflows right inside Teams.

MS Teams bots

What you are going to do in this tutorial

You are going to create a plain bot, which replies what you say in backward. Yes, this is not a useful bot at all, but hopefully, this sample gives some good ideas about what you'll build in the future.

  1. Configure your app with App Studio
  2. Set up your code on an online IDE and run
  3. Use Microsoft Bot Framework to handle bot conversation

The end result would look like this:
Teams bot

πŸ““ Prerequisites

To be able to install apps to Teams, your organization's admin needs to grant permission.

Otherwise, you can sign up for Microsoft 365 developer program, a free, renewable subscription that comes with a developer tenant sandbox and sample data pack, like mock user data!

  • Permission to develop on Teams or developer tenant (Sign up for M365 developer program!)
  • App Studio - look for the app from the Apps menu in Teams client and install to your workspace
  • Experience with Node.js and basic understanding of Express.js

Unlike the previous tutorial, that requires some front-end coding skills, to work with bots, you need a different skill set, and for this tutorial, Node.js.

Building a chat bot

🎏 Grabbing the code sample

In this tutorial, I am using the 3rd party tool, Glitch to host and run this project and the rest of the tutorial series. Glitch is a web-based IDE that you can write and run your node.js code, so at least for now, you can focus on learning the concepts and basics of Teams app development without worrying about running and tunneling localhost, or deploying. (I will cover them in the future!)

First, let's just click this Glitch link to remix the project. Remixing is like the forking a repo on GitHub, so it generates a copy of the project for you, so you can modify the code in the way you want without messing with the original πŸ™Œ

Remix on Glitch

Once you get your own project repo, it serves up the app automatically and you get your own web server URL. For example, if your generated project name, usually it consists of a few random words, is achieved-diligent-bell, your Node server URL would be https://achieved-diligent-bell.glitch.me. You can customize the name too if you want, too. You will need the URL when you are setting up an app with App Studio later.

glitch project name

βš™οΈ App Configuration: Creating App Manifest with App Studio

This section is exactly the same as one in my previous tutorial to build tabs.

When you are building any apps for Teams, you must create an app package to be installed to Teams client. The package includes:

πŸ“ your-app-package
    └── πŸ“„ manifest.json
    └── πŸ–Ό color.png (192x192)
    └── πŸ–Ό outline.png (32x32)
Enter fullscreen mode Exit fullscreen mode

and the rest of the app code and assets must be hosted on your webserver. (In this tutorial, we are using Glitch to automatically serve your app).

We are not creating the manifest file manually today, but instead, we are going to create the app package using a visual tool called App Studio so you can create the package directly to Teams client.

πŸŽ› Using App Studio

Installed App Studio app in Teams client, if you haven't. Then, open the app.

In App Studio, click the Manifest Editor tab from the top, then select Create a new app and fill out all the required fields including the Bot names, descriptions, etc.

At the App URLs section, fill out your privacy and Terms of Use webpage URLs. In this example, I am just using the placeholder URL, https://example.com, but when you're developing apps to publish, you must have the web pages with the statements.

Also, generate an App ID.

App Studio

πŸ”– Configuring a bot

From the left menu, select Capabilities > Bots.

Then click Set up to configure a new bot.

Fill out the bot name, and let's just select the Personal scope for now. A personal bot allows conversing between bots and a single user. (To learn more about the scopes, read Conversation basics on docs.)

App Studio

Then, click Generate new password. At the modal popup, copy the password, which you will need to paste it in your .env file at the next step!

Alt Text

πŸ” App credentials

Copy the ID next to your bot name (something looks like 2cd53e8a-e698-4exx-...) and paste it as an environment variable in your .env file, which is supposed to be a hidden file (Rename the .env-sample to .env).

Under App Passwords, generate a new password, and copy it. Then paste it in your .env file.

These credentials are used to initialize your bot adapter. (See index.js).

At Messagind Endpoint, enter your bot server, which should be https://[your project].glitch.me/api/messages.

πŸ“¦ Installing the app manifest package

Go to Finish > Test and distribute.

If you get any errors, go fix it, otherwise, click Install your client.

App Studio

You can also download the zip file that contains manifest.json, and two icon images to install later or distribute.

As long as you remixed the code sample, the bot should work already. But let me quickly explain how it is coded before trying the bot.

πŸ€– Microsoft Bot Framework

The Microsoft Bot Framework is an open source SDK that allows you to build intelligent, enterprise-grade bots.

This SDK is a powerful platform that not only for Teams, but also designed to work for wide types of chat bots, including web & mobile chat, Skype, Facebook, Amazon Alexa, Slack, Twilio, and more!

πŸ”§ Initiating the bot service

First, there are two JS files in the Glitch code sample repo, index.js and bots.js.

Note: Glitch automatically pulls all dependencies from the pre-defined package.json so you do not need to install the packages manually.

In index.js, you need to include the libraries, botbuilder, and a library to set up an HTTP server and routing HTTP requests. I am using Express but you can use something else you prefer, such as, Restify.

index.js:

// Import Express & set up HTTP server
const express = require('express');
const app = express();
const server = app.listen(process.env.PORT || 3978);

// Import bot services
const { BotFrameworkAdapter } = require('botbuilder');

// Bot's main dialog
const { ReverseBot } = require('./bot');
Enter fullscreen mode Exit fullscreen mode

Note: In this example, I am using botbuilder version 4.10.0. If your code doesn't work as expected, check the version you are using!

Then, set up the adapter that allows your bot to communicate with the user and send responses.

const adapter = new BotFrameworkAdapter({
  appId: process.env.MicrosoftAppId,
  appPassword: process.env.MicrosoftAppPassword
});

// Error handlings (See the Glitch sample for details!)

// Create the main dialog
const myBot = new ReverseBot();
Enter fullscreen mode Exit fullscreen mode

πŸ¦‰ Forwarding requests to the bot logic

Use Express to handle the routing to listen for incoming requests:

app.post('/api/messages', (req, res) => {
  adapter.processActivity(req, res, async context => {
    await myBot.run(context);
  });
});
Enter fullscreen mode Exit fullscreen mode

You have set up the URL in App Studio in the previous step. The /api/messages is your application’s endpoint URL to respond to client requests.

πŸ’¬ Handling the request and post bot replies

Once a request is received at the endpoint and forwarded to the bot logic, your app receive the context of the request, then create a custom reply in bots.js.

See the TeamsActivityHandler is extended to create an appropriate handler for the request:

const { TeamsActivityHandler, MessageFactory } = require('botbuilder');

class ReverseBot extends TeamsActivityHandler {
  constructor() {
    super();
    this.onMessage(async (context, next) => {
      const backward = [...context.activity.text].reverse().join(''); // reverse string
      const replyText = `πŸ™ƒ *${ backward }*`; // you can use markdown
      await context.sendActivity(MessageFactory.text(replyText));

      await next();
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

The TeamsActivityHandler is a Teams specific class that handles messages- such as messages events (e.g. onMembersAdded method is called whenever a member is added to the conversation), and sending replies.

In the example, when a message is send to the client, the onMessage is triggered, and you can grab the message text and use it to create the custom reply, in this case, reverse the string and send back to the user.

πŸ€–πŸ’¬ Trying your bot

Now, let's try the bot! Go to the Teams client, and click launch the bot from the left menu bar.

If everything works as expected, you should be able to converse with the bot like this:

Teams bot

This example only shows you how to send a text reply, however, you can create more interactive messages using buttons and other UI components. I will explain more about it later.

I hope you enjoyed the tutorial, I hope you find better use cases than this and create something amazing! See you next time πŸ‘‹


πŸ“š Learn more

Top comments (2)

Collapse
 
n_mehlhorn profile image
Nils Mehlhorn

Thanks for the article! Do you have any tips on developing bots with multiple developers? Especially in combination with authentication, it seems cumbersome to setup a bot channel registration and different manifest package (thus uploaded app) for every developer.

I thought the bot framework emulator would be one option but it won't give you Teams-specific context. Is there an easier solution? How do bigger developer teams do this?

Collapse
 
girlie_mac profile image
Tomomi Imura 🐱

Hi Nils, thank you for your comment and I am sorry about this late reply!

In this series of articles, I only focus on the features and nothing else, but yes, in the reality there are a lot more things involved, like security, access management, etc.

Bot development is all associated with Azure services, although the tool used in the article (App Studio) does some of the operations like configuration automatically so you don't need to manually do anything on your Azure portal.

But when you have more complex tasks and work with more people, you will need to set up manually on Azureβ€”

Azure DevOps: to manage everything(access, keys, auth etc.)
Azure AD: to help to access Test, Build and Release environments on Azure

docs.microsoft.com/en-us/azure/dev...

Bot testing can be done on Bot Framework emulator that you mentioned. But yes, you are right, it only helps some of the functionality and not Teams-specific features like messaging extensions and adaptive card actions.

So your team may end up testing and debugging on own computers. This requires some sort of tunneling so calls from the Azure Bot Channel Service can reach your code. If we had a shared bot registration, there would only be one tunnel URL. If only one developer works at a time, that could work. (Yeah, I know this isn't the best!)