Building a chat bot using Nest.js and Telegram
Tags: nestjsandtelegram, telegrambot, buildingachatbot, bots
Published: 2018-05-15 00:48:44

---
title: Building a chat bot using Nest.js and Telegram
published: true
tags: nestjs-and-telegram,telegram-bot,building-a-chat-bot,bots
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/738/1*0zZ09keEm0AKHSHargUeVQ.jpeg)

### Introduction

In this tutorial, I will be showing you how to build a basic chat bot for Telegram using Nest.js. This will, amongst other things, give you an overview of how Telegram bots work and what you can do with them.

Telegram bots are simply accounts that do not require an additional phone number to set up. Users can interact with them via commands: opening a chat directly or sending a request directly from a chat input field by typing bot’s @username.

### What we’ll be building

We’ll be building a telegram bot with a username new-nest-bot, you can choose your own preferred name when registering a new telegram bot.

{% youtube qBQaX3eVsdk %}

This bot was built to respond to text messages sent directly to it with predefined responses from the logic implemented on the back-end of the application.

### Prerequisites

A basic understanding of TypeScript and Node.js will help you get the best out of this tutorial. I assume that you already have Node and npm installed, if otherwise quickly check [Node.js](https://nodejs.org/en/) and [npm](https://www.npmjs.com/) for further instructions and installation steps.

In addition, a Telegram account is also required to have access to Telegram services, either to start a chat or create a bot. If you don’t have an account, I recommend using the [Telegram web client](https://web.telegram.org/#/login)

Finally, here is a quick overview of the technologies that we will be using in this post.

- [Nest.js](https://nestjs.com/): a progressive framework for building efficient and scalable server-side applications; built to take the advantage of modern JavaScript but still preserves compatibility with pure JavaScript.

![](https://cdn-images-1.medium.com/proxy/1*8_uUnP2g8H8Zj3N_KktFtw.png)

- [Node-telegram-bot-api](https://github.com/yagop/node-telegram-bot-api): a Node.js module to interact with the official [Telegram Bot API](https://core.telegram.org/bots/api).

### Setting up the project

First, you need to install the [Nest.js](https://nestjs.com/) starter project on [Github](https://github.com/nestjs/typescript-starter) using Git. To do this, let’s run a command that will clone the starter repository into a new project folder named nest-telegram-chat-bot on your machine. Open your terminal or command prompt and run the command below:

```
$ git clone https://github.com/nestjs/typescript-starter.git nest-telegram-chat-bot
```

Go ahead and change directory into the newly created folder and install all the dependencies for the project.

```
// change directory
cd nest-telegram-chat-bot

// install dependencies
npm install
```

### Installing server dependencies

The only server dependency required for this application is the [node-telegram-bot-api](https://github.com/yagop/node-telegram-bot-api). Run the command below to install it:

```
$ npm install --save node-telegram-bot-api
```

### Creating a Telegram bot

We’ll basically be interacting with Telegram bot API. To do this, you will need to obtain an access token. Open a [Telegram app](https://web.telegram.org/), search for @BotFather and start the chat. Use the /newbot command to create a new bot. The BotFather will ask you a couple of questions, like the name and username, before an access token can be generated.

![](https://cdn-images-1.medium.com/max/695/0*uA1JKceuZv7b0l5_.png)

Follow all the instructions and once you are done, a token that is required to send requests to Telegram Bot API will be generated for you. As shown below:

![](https://cdn-images-1.medium.com/max/1024/1*BPP_fA5Qb1_SPRktYuuwWw.jpeg)

Now we have successfully created a bot, but it is passive at the moment as it has not been configured to respond to chat.

### Making request

Open a new tab in your browser and test the new bot by making an HTTPS request to the Telegram Bot API using this URL:

```
https://api.telegram.org/bot\<YOUR\_ACCESS\_TOKEN\>/getMe
```

This will return a response in JSON format with the id, name, and username of the bot.

```
{"ok":true,"result":{"id":591836832,"is\_bot":true,"first\_name":"new-nest-bot","username":"nest\_demo\_bot"}}
```

### Initialize the application controller

When a user interacts with our bot on Telegram, the [Telegram Bot API](https://core.telegram.org/bots/api) sends details about the interaction to our Nest.js application over an HTTP request and a response will be sent back with instructions on how the bot should respond. Let’s configure our application logic.

Nest.js starter project comes installed with a default controller named app.controller.ts. Open this file and update it with the code below:

```
// ./src/app.controller.ts

import { BotService } from './bot/bot.service';
import { Get, Controller, Res, HttpStatus } from '@nestjs/common';

@Controller()
 export class AppController {
 constructor( private botService:BotService) {}

 @Get()
 getBotDialog(@Res() res) {
 this.botService.botMessage();
 res.status(HttpStatus.OK).send("Bot service started");
 }
}
```

Once we start our application, this controller handles the incoming request and returns the appropriate response. As shown above, we imported BotService and injected it into the controller through the constructor. This is to ensure that app.controller.ts handles only the HTTP requests and abstracts the complex logic to a service. We’ll set this up in the next section

### Configure the bot service

Our AppController depends on a service named BotService to respond to the interaction with our Telegram bot, based on a specified logic. Let’s create this service. Create a bot folder within the src and proceed to create a new file named bot.service.ts within it. Next, open the newly created file and paste the code below into it:

```
// ./src/bot/bot.service.ts

import { Component} from '@nestjs/common';

@Component()
 export class BotService {

 botMessage() { 
 process.env.NTBA\_FIX\_319 = "1";
 const TelegramBot = require('node-telegram-bot-api');

const token = 'YOUR\_ACCESS\_TOKEN';

const bot = new TelegramBot(token, { polling: true });

 bot.on('message', (msg) =\> {
let Hi = "hi";
if (msg.text.toString().toLowerCase().indexOf(Hi) === 0) {
 bot.sendMessage(msg.from.id, "Hello " + msg.from.first\_name + " what would you like to know about me ?");
 }
 }
}
```

Here, we created a method named botMessage() and within it, we required the node-telegram-bot-api module and then assigned the access\_token received from BotFather to a token variable. This token was later used as an argument to create a new TelegramBot(). Notice the second argument passed to the new TelegramBot()? What we have done here is to create our bot with the [long polling](https://en.wikipedia.org/wiki/Push_technology#Long_polling) configuration by setting it to true.

It is worth mentioning that, you can actually interact with a server in two ways:

1. [Webhook](https://sendgrid.com/blog/whats-webhook/): A dedicated URL or can also be referred to as a web callback.
2. [Long Polling](https://en.wikipedia.org/wiki/Push_technology#Long_polling): This allows us to run our application locally without the need for a dedicated server or external address.

### Register the component

At the moment, our application doesn’t recognize the newly created service. Let’s change this by editing our module file app.module.ts. To do this, put the service into the ‘components’ array of the @Module() decorator.

```
// ./src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { BotService } from 'bot/bot.service';

@Module({
 imports: [],
 controllers: [AppController],
 components: [BotService],
})
export class AppModule {}
```

### Running the application

Start the application with :

```
$ npm start
```

This will start the application on the default port used by Nest.js. Open your browser and navigate to [http://localhost:3000](http://localhost:3000).

![](https://cdn-images-1.medium.com/max/1024/0*ZTnkRysk-zkqei24.png)

Next, open a [Telegram app](https://web.telegram.org/#/im) and search for new-nest-bot or the name of your Telegram bot if you happen to choose a different name.

![](https://cdn-images-1.medium.com/max/1024/0*g0EggNgYipgx4YtK.png)

Now, you can click on the start button to start a chat.

![](https://cdn-images-1.medium.com/max/1024/0*TACZqrOgmoK_0SOr.png)

if you don’t get a response at the moment, don’t worry, just refresh the application if you have it open in a different tab.

![](https://cdn-images-1.medium.com/max/1024/0*rJybkJUQ4EeURg6O.png)

### Update the service

In order to avoid refreshing the page all the time, we will use a life-cycle event named OnModuleInit from Nest.js within our component to initialize the botMessage method.

```
// ./src/bot/bot.service.ts

import { Component, OnModuleInit } from '@nestjs/common';

@Component()
 export class BotService implements OnModuleInit {

 onModuleInit() {
 this.botMessage();
 }

 botMessage() { 
 ...
 }
}
```

Restart the development server if it is currently running, then proceed to try out the new-nest-bot

![](https://cdn-images-1.medium.com/max/1024/0*HlU0qbVBhIijVRC1.png)

You can find the complete bot.service.ts file [here](https://github.com/yemiwebby/nest-telegram-chat-bot/blob/master/src/bot/bot.service.ts) with the complete dialog on GitHub.

### Conclusion

Here, we have been able to build a telegram chatbot with a predefined response to chat from other users. The intention was to give you a general building block that can be improved and build amazing chatbot that can do much more.

I hope this tutorial was helpful and gave you enough information required to start building bots tailored for other use cases, as you deem fit, in your organization.

The source code for this tutorial can be found [here](https://github.com/yemiwebby/nest-telegram-chat-bot) on Github. Feel free to explore.

* * *