DEV Community

Cover image for Build telegram bot with node
Dimitri Ivashchuk
Dimitri Ivashchuk

Posted on • Originally published at divdev.io

Build telegram bot with node

Originally published on divdev.io

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.

const express = require('express')

const app = express()

const PORT = '8888'

app.listen(PORT, async () => {
  console.log(`🚀 server is running`)
  require('./bot')
})
Enter fullscreen mode Exit fullscreen mode

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.

Alt Text

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.

Alt Text

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.

Alt Text

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.

const Telegraf = require('telegraf')

const bot = new Telegraf('996917:AAF7ZAhEFxTc7WMSnNuO_VHx4YePZzhm20Y')

bot.telegram.deleteWebhook().then(success => {
  success && console.log('🤖 is listening to your commands')
  bot.startPolling()
})
Enter fullscreen mode Exit fullscreen mode

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.

const Telegraf = require('telegraf')

const bot = new Telegraf('996917685:AAF7ZAhEFxTc7WMSnNuO_VHx4YePZzhm20Y')

bot.telegram.deleteWebhook().then(success => {
  success && console.log('🤖 is listening to your commands')
  bot.startPolling()
})

bot.start(async ctx => {
  const name = ctx.from.first_name
  ctx.reply(`Hello ${name ? name : 'friend'}! You managed to run me!`)
})
Enter fullscreen mode Exit fullscreen mode

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!

If you liked the post check my other posts and videos at divdev.io and subscribe to my twitter not to miss any important updates! Thanks for reading, see you!

Top comments (0)