Build a Telegram Bot using Node.js
Tags: node, javascript, webdev, design
Published: 2020-09-11 16:41:38

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](https://www.pexels.com/).

### Getting started
There is a bot called [BotFather](https://t.me/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](https://dev-to-uploads.s3.amazonaws.com/i/bhqlsueqpxiz422bdlbk.png)

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

```javascript
$ npm init
$ npm install telegraf
```

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

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

### Preview

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6ufhm31z0vasp4487zja.PNG)

### 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.

```javascript
npm install axios --save
```

```javascript
const { Telegraf } = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN);
const axios = require("axios");
const pexelKey = process.env.PEXEL_KEY;
```

You can get an API key from [PexelsApi](https://www.pexels.com/api/documentation/)

```javascript
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;
  }
}
```

```javascript

// 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 :(")
  }
});
```

I'm alive [@PexelsPlashBot](https://t.me/PexelsPlashBot)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k5v8mn20axu1yrk7toid.png)

### 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](https://github.com/Ajaykumbhare/PexelsPlash).