Introduction In this tutorial, I will be showing you how to build a basic chat bot for using . This will, amongst other things, give you an overview of how Telegram bots works and what you can do with them. Telegram Nest.js 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 , you can choose your own preferred name when registering a new telegram bot. new-nest-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 and for further instructions and installation steps. Node.js npm 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. : 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. Nest.js : a Node.js module to interact with the official . Node-telegram-bot-api Telegram Bot API Setting up the project First, you need to install the starter project on using Git. To do this, let’s run a command that will clone the starter repository into a new project folder named on your machine. Open your terminal or command prompt and run the command below: Nest.js Github nest-telegram-chat-bot $ 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 . Run the command below to install it: node-telegram-bot-api $ 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 , search for 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. Telegram app @BotFather 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 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. Telegram Bot API 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 { BotService } from './bot/bot.service'; { Get, Controller, Res, HttpStatus } from '@nestjs/common'; import import @Controller() AppController {constructor( botService:BotService) {} export class private @Get()getBotDialog(@Res() res) { .botService.botMessage();res.status(HttpStatus.OK).send("Bot service started");}} this Once we start our application, this controller handles the incoming request and returns the appropriate response. As shown above, we imported and injected it into the controller through the constructor. This is to ensure that handles only the HTTP requests and abstracts the complex logic to a service. We’ll set this up in the next section BotService app.controller.ts Configure the bot service Our depends on a service named to respond to the interaction with our Telegram bot, based on a specified logic. Let’s create this service. Create a folder within the and proceed to create a new file named within it. Next, open the newly created file and paste the code below into it: AppController BotService bot src bot.service.ts // ./src/bot/bot.service.ts { Component} '@nestjs/common'; import from @Component() BotService { export class 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 and within it, we required the module and then assigned the received from BotFather to a token variable. This token was later used as an argument to create a new . Notice the second argument passed to the new ? What we have done here is to create our bot with the configuration by setting it to true. botMessage() node-telegram-bot-api access_token TelegramBot() TelegramBot() long polling It is worth mentioning that, you can actually interact with a server in two ways: : A dedicated URL or can also be referred to as a web callback. Webhook : This allows us to run our application locally without the need for a dedicated server or external address. Long Polling Register the component At the moment, our application doesn’t recognize the newly created service. Let’s change this by editing our module file . To do this, put the service into the ‘components’ array of the decorator. app.module.ts @Module() // ./src/app.module.ts { Module } '@nestjs/common'; { AppController } './app.controller'; { BotService } 'bot/bot.service'; import from import from import from @Module({imports: [],controllers: [AppController],components: [BotService],}) AppModule {} export class 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 and search for or the name of your Telegram bot if you happen to choose a different name. Telegram app new-nest-bot 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 from Nest.js within our component to initialise the botMessage method. OnModuleInit // ./src/bot/bot.service.ts { Component, OnModuleInit } '@nestjs/common'; import from @Component() BotService OnModuleInit { export class implements 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 file with the complete dialog on GitHub. bot.service.ts here 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 on Github. Feel free to explore. here