Beginners Guide to MS Teams Development #2: Bots
Tags: msteams, m365, javascript, node
Published: 2020-10-05 21:41:23

Hello, I hope you enjoyed my [previous tutorial](https://dev.to/azure/beginners-guide-to-ms-teams-development-1-tabs-4e9k) 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](https://dev.to/azure/beginners-guide-to-ms-teams-development-1-tabs-4e9k), 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](https://docs.microsoft.com/en-us/microsoftteams/platform/overview/?WT.mc_id=m365-devto-timura) 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](https://docs.microsoft.com/en-us/microsoftteams/platform/assets/images/overview-bots.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/fij31w2au7swf5gxwwom.png)

### 📓 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!](https://developer.microsoft.com/en-us/microsoft-365/dev-program/?WT.mc_id=m365-devto-timura))
- 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](https://expressjs.com/)

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**](https://glitch.com) 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](https://glitch.com/edit/#!/remix/msteams-bot-minimum). 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](https://cdn.glitch.com/2703baf2-b643-4da7-ab91-7ee2a2d00b5b%2Fremix-button.svg)](https://glitch.com/edit/#!/remix/msteams-bot-minimum)

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](https://res.cloudinary.com/practicaldev/image/fetch/s--AXHqSAT8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4l4y51fnypv4h8tkggcn.png)

### ⚙️ 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)
```

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](https://dev-to-uploads.s3.amazonaws.com/i/6v7c9sb6k5gpm4qot0ab.png)

### 🔖 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](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/conversation-basics/?WT.mc_id=m365-devto-timura) on docs.)

![App Studio](https://dev-to-uploads.s3.amazonaws.com/i/x8lnral7lc36qt9a9871.png)

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](https://dev-to-uploads.s3.amazonaws.com/i/z90x87ldaf2ew0toqchj.png)

### 🔐 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](https://dev-to-uploads.s3.amazonaws.com/i/mtq6g1ul3n0tk3kof8rb.png)

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](https://dev.botframework.com/) 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](https://www.npmjs.com/package/botbuilder/?WT.mc_id=m365-devto-timura), and a library to set up an HTTP server and routing HTTP requests. I am using [Express](https://www.npmjs.com/package/express) but you can use something else you prefer, such as, [Restify](https://www.npmjs.com/package/restify). 

index.js:
```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');
```
*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.

```js
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();
```

### 🦉 Forwarding requests to the bot logic

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

```js
app.post('/api/messages', (req, res) => {
  adapter.processActivity(req, res, async context => {
    await myBot.run(context);
  });
});
```
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:

```js
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();
    });
  }
}
```

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](https://dev-to-uploads.s3.amazonaws.com/i/fij31w2au7swf5gxwwom.png)

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

- MS Teams Documentation - [What are conversational bots?](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/what-are-bots/?WT.mc_id=m365-devto-timura)
- [Microsoft Bot Frameworks](https://dev.botframework.com/?WT.mc_id=m365-devto-timura)
- Bot Services Documentation - [How bot works?](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0&tabs=javascript&WT.mc_id=m365-devto-timura)
- Microsoft Azure tutorials & articles on [Dev.to](https://dev.to/azure)