DEV Community

Cover image for Build a Telegram Bot using Node.js
Ajay kumbhare
Ajay kumbhare

Posted on

Build a Telegram Bot using Node.js

A bot is a software program that operates on the Internet and performs repetitive tasks.

In this tutorial, we will create a Telegram bot which helps to download images from Pexels.

Getting started

There is a bot called BotFather which helps you to create your bot.

BotFather is the one bot to rule them all. Use it to create new bot accounts and manage your existing bots.

BotFather provides you some commands as following.

Alt Text

so to create a Bot click on the /newBot command. after you create a bot BotFather will provide you token.

There are many good frameworks available for NodeJS, in this tutorial we're going to use Telegraf.

Let's start coding

Initialize the project and install Telegraf

$ npm init
$ npm install telegraf
Enter fullscreen mode Exit fullscreen mode

Now create a file and let's add it script and make a simple bot.

const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()
Enter fullscreen mode Exit fullscreen mode

Preview

Alt Text

PexelsPlashBot

We're going to send the top 10 photos from the Pexels that a user asks for. Install axios library to simplify sending GET requests and grabbing data from Pexels.

npm install axios --save
Enter fullscreen mode Exit fullscreen mode
const { Telegraf } = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN);
const axios = require("axios");
const pexelKey = process.env.PEXEL_KEY;
Enter fullscreen mode Exit fullscreen mode

You can get an API key from PexelsApi

const fetchImages = async (text) => {
  try {
    const { data: { photos } } = await axios.get(`https://api.pexels.com/v1/search?query=${encodeURI(text)}&per_page=10`, {
      headers: { Authorization: pexelKey }
    }).catch((e) => console.log(e));
    // {photos} contains photos object recieved from Pexels

    if (photos.length > 0) {
      return photos.map(({ src }) => ({ media: { url: src?.original }, caption: "Pexel", type: "photo" }));
      // mapping response from photos object
    }
  } catch (e) {
    throw e;
  }
}
Enter fullscreen mode Exit fullscreen mode

// when user sends a text message app.on("text") will call
app.on("text", async (ctx) => {
  // A Telegraf Context encapsulates telegram update
  //  So you can use everything you see there
  try {
    ctx.reply("⌛️ Please Wait It will take few seconds to grab Images"); // bot will send a reply to users. 
    // GET the data from Pexels API
    const photos = await fetchImages(ctx.message.text);
    // fetchImages will return image objects from pexels.
    photos.length > 0 ? ctx.replyMediaGroup(photos) : ctx.reply("Sorry Image not found :(");
    // if photos available then we are sending photos otherwise we are sending a reply as `Sorry Image not found :(`
    // we are sending 10 images here so replyMediaGroup accepts an array with objects of media, caption, and type
  } catch (e) {
    console.log(e);
    ctx.reply("Please try after sometime PexelsPlash is down :(")
  }
});
Enter fullscreen mode Exit fullscreen mode

I'm alive @PexelsPlashBot

Alt Text

Wrapping up

As you can see, we've created a simple Telegram bot in minutes. but you can do more cool stuffs using telegram bot API's.

You can find the source code of this bot on GitHub.

Top comments (0)