Build own Telegram Bot with Node.js
Since Telegram Bot has appeared, I always interested in how they work. So I decided to build simple Telegram Bot with Node.js and Telegraf. Telegraf is a modern bot framework for Node.js. They have friendly documentation and examples.
In this tutorial I will develop a love calculator bot. I used free love calculator api. You should enter your name and name of your partner/lover/crush to find Love compatibility & chances of successful love relationship.
Let’s start and do it together.
Create own Bot with BotFather
First, We should create own bot with BotFather. BotFather is the one bot to rule them all. We will use it to create new bot accounts and manage your existing bots.
If you open a chat with a BotFather, click on the “Start” button.
After that, the bot gives us all the commands.
We should create a new bot by clicking /newbot command. Next, you should enter any name for the bot. I named
Cupido . Fortunately, You can delete the test bot or change the name. In the last step, you have to come up with a username for your bot. It must end in `bot`. For example TetrisBot or tetris_bot. I named MrCupidoBot.
Finally, We got a message that the bot was created and a token. We have to keep this token because, it will help us access the Telegram API.
Setting up the Project
We are going to use Nodejs with Telegraf. If you don’t have nodejs you should install it. We will install nodejs via Homebrew:
brew install node
If everything installed successfully then you can type in the following command in the terminal to check the Node and NPM version.
Create a new directory and move into
mkdir cupido-bot && cd ./cupido-bot
Initialize the project:
We need to download
axios to work with api:
npm install telegraf axios --save
Write bot’s code
Our repository is ready and let’s write bot’s code. Create
index.js file and add the following code:
Next, we should change bot’s icon by
/mybots command. I downloaded the icon from freeicons website.
Next, launch code on nodejs by the following command:
Next, We are going to create
loveCalculator.js to work with api:
We will pass two-parameter to
getPercentage method to calc love compatibility.
We will use
telegraf to implement a two-step conversation between user and bot. Stage is a simple scene-based control flow middleware.
Let’s launch our final code.
That’s it. We did our first own Telegram Bot.
I hope you found this post useful.