Tutorials > How to create a Telegram Bot with Node.js on Ubuntu 18.04

How to create a Telegram Bot with Node.js on Ubuntu 18.04

Published on: 12 May 2020

Node.js Telegram Ubuntu

Telegram is a state-of-the-art, completely open source instant messaging platform. Among the different features provided by the platform, there is the possibility to create custom Bots, able to interface with users in a completely automatic way.

Bots are able to receive the commands given by the user through the Telegram chat in the form of HTTP requests and to respond with certain actions. The communication APIs with Telegram can be used through the HTTP protocol, as described in the official documentation available at https://core.telegram.org/bots.

In the following tutorial you will see how to use the available tools to create a very simple bot that responds with the received text, by slightly altering it, on a Linux Ubuntu 18.04 server. For making the necessary requests, "superagent" will be used as an HTTP client.

Creating the bot through BotFather

To create a new bot, use the Telegram bot called "BotFather", reachable through a Telegram client by searching the name "@BotFather" or by visiting the link https://t.me/botfather.

After opening the chat with BotFather, click on the "Start" button and type:
/newbot
The bot will request a name for your new bot, here called "node-tg-bot":
“Alright, a new bot. How are we going to call it? Please choose a name for your bot.”

node-tg-bot
At this point you will be asked for a username for your bot (which must end with "_bot"):
Good. Now let's choose a username for your bot. It must end in ‘bot’. Like, for example: TetrisBot or tetris_bot.

aruba_tutorial_bot

After entering the official name of the bot, BotFather will reply with the access token necessary to make the HTTP requests. Keep it and do not disclose it.

Done! Congratulations on your new bot. You will find it at t.me/aruba_tutorial_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:
855911470:AAHQ8QmbktoSV5zFSXYEXUw8sJLBbbLT97I
Keep your token secure and store it safely, it can be used by anyone to control your bot.

Installing Node.js

First, connect to your server via an SSH connection. If you haven't done so yet, following our guide is recommended to connect securely with the SSH protocol. In case of a local server, go to the next step and open the terminal of your server.

Install Node.js via apt making sure you download the latest version available. To do so, update your repositories as follows:

$ sudo apt update && apt install nodejs

Now, move on to installing NPM or the Node Package Manager necessary to install additional modules for Node.js:

$ sudo apt install npm

Before proceeding, it is better to update node with the latest stable version, by running the following commands:

$ sudo npm cache clean -f 
$ sudo npm install -g n 
$ sudo n stable
$ PATH="$PATH"

Then, check the correct installation of Node.js using the command:

$ node -v

If successfully installed, the installed version will be displayed on the screen.

Creating the server application

To create an application compatible with the standards set by Node.js, first initialize a basic NPM configuration. Then, create a folder for the project (in this example, called node-tg-bot) and run the console commands inside the newly created folder:

cd /var/
sudo mkdir node-tg-bot
cd node-tg-bot
npm init

A wizard will be launched to create a package.json file with all the basic information about the project and its dependencies.

Use the suggested values ​​to move forward, as shown below:

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (node-tg-bot)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to package.json:

{
 "name": "node-tg-bot",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC"
}


Is this OK? (yes) yes

Answer ‘yes’ to complete the procedure.

Then, continue by installing the "superagent" module that will be used to make HTTP requests:

npm install --save superagent

By adding the --save parameter, NPM is instructed to update package.json and add this dependency to the project.

The entry point for the application can now be created by creating the index.js file in the same directory as package.json.

Use your favorite text editor to paste the following content into the newly created file. It is a simple test script that will process the message received by the user on Telegram and reply by capitalizing all the text received.

/**
* 
Import superagent, a library that allows you to make
* HTTP requests
*/
const   superagent      = require( 'superagent' );

/**
* 
*Save it in token returned by BotFather
*/
const   botToken        = '855911470:AAHQ8QmbktoSV5zFSXYEXUw8sJLBbbLT97I';

/**
* 
* Save the index of the last message received
*/
let     lastOffset      = 0;


/**
* 
* Process the updates received from Telegram and reply to the message
* received, capitalizing the text received
* @param {Update} msg Struttura "Update" (See https://core.telegram.org/bots/api#update )
*/
function parseMessage( msg ){
   try {
       
       const upperCaseReponse = encodeURIComponent( msg.message.text.toUpperCase() );

       // See how https://core.telegram.org/bots/api#sendmessage

       superagent.get(`https://api.telegram.org/bot${botToken}/sendMessage?chat_id=${msg.message.chat.id}&text=${upperCaseReponse}`)
           .then( response => {
           });
       
   } catch( e ){
       console.error( e );
   }
}

function requestUpdate(){

   // See howhttps://core.telegram.org/bots/api#getupdates

   superagent.get(`https://api.telegram.org/bot${botToken}/getUpdates?limit=1&offset=${lastOffset}`)
       .then( msg => {

           try {

               msg.body.result.map( inputMessage => {

                   // Update the offset with the last message received                   lastOffset = inputMessage.update_id +1;

                   // Process the received text
                   parseMessage( inputMessage );
               });

           } catch( e ){
               console.error( e );
           }

           // Set the reading of the next messages in 2 seconds
           setTimeout( () => {
               requestUpdate();
           } , 2000 );

       });

}

// Start the first reading of the messages requestUpdate();

Complete the procedure by installing the project dependencies, typing the command:

sudo npm install

Starting the Bot

To start your bot and keep it alive persistently, use the Forever application: a software that can run and keep scripts alive, even in the event of a crash.

Install Forever using NPM:

sudo npm install -g forever

Then, start your app:

forever start index.js

Check the functionality of the Bot

At this point, test the correct functioning of the bot. To do so, use a Telegram client, looking for your bot using the name "@ node-tg-bot".

After opening the chat, click on the "Start" button and try typing a test message. If the bot replies with the same message but in capital letters, it is working properly.