Build telegram bot with node

Table of tutorials contents

  1. Setting up the project
  2. Working with messages - WIP
  3. Adding commands to the bot, working with the special messages and keyboards - WIP
  4. Persisting state between sessions - WIP
  5. Using telegraf middleware - WIP

Motivation

As Telegram in justified way replaced all of my other messengers for personal and professional use I’ve started to look for ways of automating things with it. The main reason for that is that bot features of telegram are already enough for most of the user facing apps that contain input/output flows. In simple words you get your UI for free and only need to care about business logic.

Choice of technologies

Coming from JavaScript background I didn’t think much about the choice of the server framework for the telegram application - simple and clean express.js. It was harder to choose between two of the most popular node frameworks for building bots for telegram. The main players there are Telegraf.js and telegram-node-api. As I’ve scanned the docs and tutorials I decided to go for Telegraf, so you can expect that the whole series will be written with it. Be sure to check both and form your own opinion as they offer quite similar functionalities!

What you will learn?

As I was building my small army of minio… bots, I’ve faced various problems and found different solutions to them. I want to provide a broad understanding of the tools that bots can offer to you, meaning that after finishing the series you will be ready to solve your problems and automate tasks with telegram bots.

What this series is not about?

I will not go deep into details how telegram works, or how Telegraf successfully abstracts the most complicated logic providing the wrappers over most useful telegram APIs. On the contrary, I will focus on the real world problems that I at some point solved and personally think they are the strongest blockers when it comes to writing the bot, and figuring our not fantastically (still very decently though :) ) written telegram docs.

Talk is cheap, let’s get started

In this first part of the series I want to show you how easy the whole setup is and how you can get the things rolling with less than 50 lines of code!

Telegraf framework requires a server to operate on top of so the first and obvious thing for us to do is setting up express server. Don’t forget to install the needed packages with npm install express telegraf or yarn add express telegraf.

index.js
js
1const
Copy
express
Copy
=
Copy
Copy
require
Copy
(
Copy
'express'
Copy
)
Copy
Copy
2
3const app = express()
4
5const PORT = '8888'
6
7app.listen(PORT, async () => {
8 console.log(`🚀 server is running`)
9 require('./bot')
10})

As telegram needs a way of authorizing bot actions every bot must be created via @botfater - telegram owned bot that acts as a setup wizard for all the bots that you will be creating.

An image

The whole process is fast and frictionless. Go to the bot and run /newbot either from message input field or from the command list Dropdown.

An image

Choose the name of your marvelous creation and you will get a congrats message from telegram containing the first thing we need for making our bot work - Access token.

An image

Now we are ready to go trough setup of telegraph. Provide your access token to the configuration object of telegraf (be sure to keep it secret and concealed in your .env file which should not go to your public version control like github or gitlab. For the purposes of this tutorial I include the token directly as a string, which is not production safe!

Telegram api can operate in two modes - webhook mode and long polling mode. For the simplicity of development and later deployment of your bot into the wild we will be using long polling mode.

bot.js
js
1const
Copy
Copy
Telegraf
Copy
Copy
=
Copy
Copy
require
Copy
(
Copy
'telegraf'
Copy
)
Copy
Copy
2
3const bot = new Telegraf('996917:AAF7ZAhEFxTc7WMSnNuO_VHx4YePZzhm20Y')
4
5bot.telegram.deleteWebhook().then(success => {
6 success && console.log('🤖 is listening to your commands')
7 bot.startPolling()
8})

We are ready to launch our bot. To do this you need to start the server. You should see the messages that confirm our server to be running and our bot to be listening.

You would probably be surprised but we are just one step away from giving our bot life and giving it ability to engage into simple interactions. Let’s teach it to greet the users when they open the bot.

bot.js
js
1const
Copy
Copy
Telegraf
Copy
Copy
=
Copy
Copy
require
Copy
(
Copy
'telegraf'
Copy
)
Copy
Copy
2
3const bot = new Telegraf('996917685:AAF7ZAhEFxTc7WMSnNuO_VHx4YePZzhm20Y')
4
5bot.telegram.deleteWebhook().then(success => {
6 success && console.log('🤖 is listening to your commands')
7 bot.startPolling()
8})
9
10bot.start(async ctx => {
11 const name = ctx.from.first_name
12 ctx.reply(`Hello ${name ? name : 'friend'}! You managed to run me!`)
13})

Congrats, you made some good progress and now can bootstrap a bot to prepare the project for new functionalities. Speaking of which, it will be coming in next part of the series where we will do a deep dive into messages and telegraf/telegram APIs for working with them.

In the next part of the series you will learn how to work with messages in telegram bot, how to react to them listening for regex patterns and simple strings and other useful tips for making the user love the interaction with your bots!

I have worked hard on the newsletter to make sure you are always getting updates when my new content is out, so if you don’t want to miss the next part of the series hit the form down below to subscribe to my newsletter. 👇👇👇


Comments section

Dimitri Ivashchuk

Written by Dimitri who lives and works in Vienna building useful things. He is passionate about modern web technologies and enjoys learning something new everyday as well as sharing his knowledge with others.

Front-end engineer @CubeTech
Instructor @egghead.io