Building a chat bot using Nest.js and Telegram

May 15, 2018 0 Comments

Building a chat bot using Nest.js and Telegram

 

 


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.

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 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. 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 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 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 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 :

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

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 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 on Github. Feel free to explore.


Tag cloud