DEV Community

Antonio Pitasi
Antonio Pitasi

Posted on • Edited on

6 1

Simple Telegram's bot with Node.js

First article here, yeah!

Today we are going to build an awesome Telegram's bot.
You will need a little Node.js and Telegram's bot platform knowledge.
Yup, I won't teach you something you can already read somewhere else.

We'll use Telegraf.js as a wrapper/framework for Telegram API. It's a pretty awesome library which simplifies a lot of annoying tasks you will encounter while developing bots.
Plus, it is middleware powered.

Enough talk, let's begin. Our bot will have a list of keywords, or commands, which will trigger a reply. The bot reply can be a simple text message, a sticker, or an animated GIF:

A cool Batman GIF

1. Creating the bot account

Assuming you are already familiar with Telegram, contact the @BotFather and create your bot account.

Please note the token (something like 410509983:AAF3kbJrAGKIrW6ceOdrUg-zLlk5Tuy-NhU), we'll use it later.

Now you have to disable privacy mode, in order to make the bot able to read all the messages in groups and not just commands.

2. Init the directory

Easy peasy.



$ mkdir coolbot
$ cd coolbot
$ npm init
# I'm assuming you already have Node & NPM installed. If not:
# https://nodejs.org/en/download/package-manager/


Enter fullscreen mode Exit fullscreen mode

Now answer the few questions NPM will ask and - done. We can install Telegraf.js now.

To do so:



$ npm install --save telegraf


Enter fullscreen mode Exit fullscreen mode

You will have a package.json file in your folder, edit the scripts part to add a 'start' script:



"scripts": {
  "start": "node main.js",
  "test": "echo \"Error: no test specified\" && exit 1"
},


Enter fullscreen mode Exit fullscreen mode

3. Let's code

Coding is fun

I think the code it's pretty easy to understand, I added some comments to make it even easier.

We want the bot to have a list of trigger, and for each trigger a reply the bot will send. The reply can be a text message, a sticker, or a GIF.

As a pretty feature, we also want that if I reply to John's message using one of the triggers, the bot should send his message replying to the John's message.

(I know, bad English is strong here.)

These triggers will be defined in a separate file later. For now, let's have a look at the core of the bot:

// Include Telegraf module
const Telegraf = require('telegraf');
// Create a bot using TOKEN provided as environment variable
const bot = new Telegraf(process.env.TOKEN);
// Import replies file
const replies = require('./replies')
// Extract reply_to_message.message_id field from Telegraf ctx
// If not present, return null
const getReplyToMessageId = ctx => (
ctx.message.reply_to_message ? ctx.message.reply_to_message.message_id : null
)
// This method will send the reply, based on the answer type
// (text / gif / sticker). See replies.js for objects structure.
const sendReply = (ctx, reply) => {
// reply method will be the Telegraf method for sending the reply
let replyMethod = {
text: ctx.reply,
gif: ctx.replyWithDocument,
sticker: ctx.replyWithSticker
}[reply.type]
replyMethod(reply.value, {
// this will make the bot reply to the original message instead of just sending it
reply_to_message_id: getReplyToMessageId(ctx)
})
}
// /list command - will send all the triggers defined in replies.js.
bot.command('list', ctx => {
ctx.reply(
'Available triggers:\n\n' +
Object.keys(replies).join('\n')
)
})
// Listen on every text message, if message.text is one of the trigger,
// send the reply
bot.on('text', ctx => {
let cmd = ctx.message.text.toLowerCase()
if (cmd in replies)
sendReply(ctx, replies[cmd])
})
bot.startPolling();
view raw main.js hosted with ❤ by GitHub

In this file we are using:

  • bot.command to define what to do in case of someone writing /list,
  • bot.on to manually define what to do in case of a Telegram event (any text message)
  • bot.startPolling to make the bot start asking Telegram for incoming new messages periodically.

4. Triggers and replies

Okay now you can customize your bot by creating and editing the replies.js file:

module.exports = {
// text
"i did not hit her": { type: 'text', value: 'https://www.youtube.com/watch?v=zLhoDB-ORLQ'}
// gif
"nodejs": { type: 'gif', id: 'CgADBAADLQIAAlnKaVMm_HsznW30oQI' },
// sticker
"woah": { type: 'sticker', id: 'CAADAgAD5gADJQNSD34EF_pwQMgbAg' },
}
view raw replies.js hosted with ❤ by GitHub

To get stickers and GIFs IDs, I suggest sending them to @jsondumpbot and look for "file_id" (pay attention to not use file_id of the "thumb"!).

5. Running the bot

RUN!

Easiest part ever:



$ TOKEN=410509983:AAF3kbJrAGKIrW6ceOdrUg-zLlk5Tuy-NhU npm start


Enter fullscreen mode Exit fullscreen mode

Obviously, use your token instead of the sample one.

The end

This is it for now. I'm not used to make tutorials and that kind of stuff, so I'll appreciate any comment.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
corusm profile image
corusm

you can also replace the process.env.TOKEN with the token in "your_token"

Collapse
 
yahyakhanmit profile image
yahyakhanmit

Thank you I was finding this for the whole morning.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay