[Part 1] How to build a Telegram Bot using Node.js (Building a Bookmark Manager Bot series)

Using Node.js and Vue.js

Original photo by 수안 최

This article is part of a series on how to build a Telegram bot and save our bookmarks, deploy the bot, and create a simple interface in Vue.js to manage our bookmarks. In this part, we will take a look at how to build the bot.

Even though browsers are implementing shared bookmarks between devices and there are a bunch of services helping you keep track of your bookmarks, I always found something that I was not satisfied with. As you will see, it is actually very easy to create your own bookmark manager which you can access from anywhere by creating a Telegram bot!

Before we start

I’m assuming that you have some sort of package manager installed, I will be using Yarn but NPM will work just as fine (however the commands for installing packages will be different). Because we will be using Node.js, you will, obviously, need to have it installed.

You can find the full code for the bot here on GitHub.

1: Let’s get busy!

The first thing we need to do is creating our project folder, all we need for now is a project folder and a index.js file. In the Terminal go to your project folder, create a package.json using init and add/install the modules we will be using, node-telegram-bot-api , open-graph-scraper and firebase :

cd your-project-folder

yarn init

yarn add node-telegram-bot-api open-graph-scraper firebase

node-telegram-bot-ap is used to interact with the Telegram API and we will use open-graph-scraper to easily scrap the OG data from our bookmarked websites. Because we will be using Firebase for storing the data you will also need the firebase module.

The BotFather

Luckily Telegram makes it very easy to create and manage bots. Add the BotFather to Telegram and start creating a new bot by sending the /newbot command. BotFather will guide you through the process. He will give you a token which you will need to use the HTTP API.

2: Let’s finally build something

We are all set up now and ready to start programming. Your project should have a node_modules folder containing the required modules. First, we need to make sure to load our modules using Node.js’s require() in the index.js file:

const TelegramBot = require('node-telegram-bot-api');

const ogs = require('open-graph-scraper');

const firebase = require('firebase');

Next, we need to create some constants to hold some of our bot’s information. Constants are similar to variables, except their value cannot change (see the MDN page for more information):

const token = 'your-token';

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

Make sure to replace your-token with your actual token, else your bot won’t connect! The constant bot creates a new bot object from the Node.js Telegram Bot API using the token constant for the token.

We now have our basics set up! But it is a bit boring when it does not do anything. Let’s make it talk back to us! To make our bot do something we need to capture an event so it can trigger the bot to do whatever we instruct it to do.

bot.on('message', (msg) => {

bot.sendMessage(msg.chat.id, 'Ill have the tuna. No crust.');

});

Now if the bot receives a message, it will reply back to us! In my example, it is ordering a sandwich, but you can use any message you want of course. Let’s check if it is working!

3: Testing the bot

Because we are using Node.js it is very easy to test our bot. Just go into the terminal and run the following commands:

cd your-project-folder

node index.js

Node will now run our script for us and we can go test our bot. Add your bot as a friend on Telegram and try sending it a message, if everything is working correctly you will receive a message back from your bot! Now before we continue let’s stop Node running our script by pressing Control + C while in the Terminal.

4: Connecting to Firebase

Our bot can receive our messages and reply back, but if we want it to bookmark our links we will need to connect to a database. With Firebase we can create a cloud-based database and sync/read our data in real-time. This makes it ideal for our bot (actually Firebase can do more than just that, this article gives a good overview). Sign in to your Google account and go to Firebase console. Click on Add project, choose a name for your project, and walk through the steps to step up your database.

When your project is ready you will be automatically redirected to the dashboard. In the left side menu click on Database under Develop. Create a new Realtime Database and start in Test Mode. Great, we now have our database ready as well. To get the information needed to connect to the database go to Project Overview from the left side menu and click on Add Firebase to your web app. You can find your credentials in the popup (in the object config ).

You can remove the message event we created for testing as we won’t need it anymore. To connect to your Firebase add the following code to your script and add the credential we just got from the Project settings:

const app = firebase.initializeApp({

apiKey: "your-api-key",

authDomain: "your-auth-domain",

databaseURL: "your-database-url",

projectId: "your-project-id",

storageBucket: "your-storage-bucket",

messagingSenderId: "your-sender-id"

});

Next, we create two constants, ref to hold the reference to our database, and sitesRef which holds the reference to the child “sites” in the database which we created earlier in the Firebase console:

const ref = firebase.database().ref();

const sitesRef = ref.child("sites");

Because we want to add more functions to our bot in the future we will create a command to make our bot bookmark a link, let’s call it /bookmark .

let siteUrl; bot.onText(/\/bookmark (.+)/, (msg, match) => {

siteUrl = match[1]; bot.sendMessage(msg.chat.id,'Got it, in which category?', {

reply_markup: {

inline_keyboard: [[

{

text: 'Development',

callback_data: 'development'

},{

text: 'Music',

callback_data: 'music'

},{

text: 'Cute monkeys',

callback_data: 'cute-monkeys'

}

]]

}

});

});

We created an empty let which we will use to store the received URL. Then we use the Telegram API to catch the onText event and use a Regular Expressions to separate the URL from the command. This will create an array from which we will select the second value (which is [1] because arrays start from zero) and set the variable siteUrl to this value.

The bot will reply with “Got it, in which category?” (you can, of course, use any message you want here) and uses the Telegram API to pull up the inline keyboard (because typing is too much work, we don’t want too tired). The inline keyboard is a build-in function in Telegram which allows us to reply by pressing a button, rather than having to type the answers! The keyboard contains three buttons which are our three categories. text: is the value that will be shown in the button, and callback_data: is the value we can use in our script. Let’s save and run our script to test if our bot is replying by running node index.js from the Terminal and sending it an URL.

Our bot is working! We can now use Telegram’s inline keyboard to reply to our bot. Now we need the bot to scrape the OG data and save it:

bot.on("callback_query", (callbackQuery) => {

const message = callbackQuery.message; ogs({'url': siteUrl}, function (error, results) {

if(results.success) {

sitesRef.push().set({

name: results.data.ogSiteName,

title: results.data.ogTitle,

description: results.data.ogDescription,

url: siteUrl,

thumbnail: results.data.ogImage.url,

category: callbackQuery.data

}); bot.sendMessage(message.chat.id,'Added \"' + results.data.ogTitle +'\" to category \"' + callbackQuery.data + '\"!')

} else {

sitesRef.push().set({

url: siteUrl

});

bot.sendMessage(message.chat.id,'Added new website, but there was no OG data!');

}

});

});

If the bot receives a callback query (meaning that we used the inline keyboard to sent something to him in this case) it will receive this information and process it. The callbackQuery contains a bunch of information, but we only care about the message so we save that in a constant. ogs (Open Graph Scraper) will scrap the URL we passed it into a JSON file. If the scraping is successful (we check by using the success flag) it pushes the OG information, along with the site URL, to Firebase and sends us a reply letting us know it added the bookmark. Then it will trigger the bot to sent back a message, we select the chat.id from the message constant to get the chat ID so the bot knows to which chat it needs to send the reply.

If it was unable to scrape any OG data it will still push the site to our database and send us a different message letting us know he could not scrape any OG data, but still bookmarked the website. In my experience, I would say about 95% of the sites I bookmarked worked fine, so it’s not very common to get no information.

You did it!

Go into the terminal and start our script again to start the bot. Let’s try it out by sending him a URL:

It’s working!

It seems like everything works fine! The final thing to check is our database. Go to your Firebase Project and select Database from the left side menu. If everything is working correctly you will see your bookmark appear in the database (you might need to expand the children using the little ‘+’-sign next to it).

Congratulation, you have now build your own bookmark assistant!

Deploying

Click here to go to the next part of the series, where we take a look at how to deploy our bot. In the future parts, we will create a simple interface for managing our bookmarks using Vue.js!

Series index

[Part 1] How to build a Telegram Bot using Node.js

[Part 2] How to deploy a Telegram Bot using Now

Next parts coming soon!