paint-brush
Building a chat bot using Nest.js and Telegramby@yemiwebby
5,617 reads
5,617 reads

Building a chat bot using Nest.js and Telegram

by Olususi Kayode OluyemiMay 13th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this tutorial, I will be showing you how to build a basic chat bot for <a href="https://hackernoon.com/tagged/telegram" target="_blank">Telegram</a> using <a href="https://hackernoon.com/tagged/nestjs" target="_blank">Nest.js</a>. This will, amongst other things, give you an overview of how Telegram bots works and what you can do with them.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Building a chat bot using Nest.js and Telegram
Olususi Kayode Oluyemi HackerNoon profile picture

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 works and what you can do with them.

Telegram bot are simply accounts that do not require an additional phone number to setup. 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.

https://www.youtube.com/watch?v=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 and npm 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

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

  • Nest.js: 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.

Setting up the project

First, you need to install the Nest.js starter project on Github 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 directorycd nest-telegram-chat-bot

// install dependenciesnpm install

Installing server dependencies

The only server dependency required for this application is the 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, 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.

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:

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 a 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 sends details about the interaction to our Nest.js application over a 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 configuration by setting it to true.

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

  1. Webhook: A dedicated URL or can also be referred to as a web callback.
  2. 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.

Next, open a Telegram app and search for new-nest-bot or the name of your Telegram bot if you happen to choose a different name.

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

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.

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 initialise 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

You can find the complete bot.service.ts file here with the complete dialog on GitHub.

Conclusion

Here, we have been able to build a telegram chat bot 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 chat bot 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 on Github. Feel free to explore.