Sending Blog's updates to Telegram with Express
Tags: javascript, express, telegram, node
Published: 2023-07-30 21:23:01

---
title: Sending Blog's updates to Telegram with Express
published: true
date: 2023-07-30 03:01:49 UTC
tags: #JavaScript #Express #telegram #Nodejs
canonical_url: https://carlosmv.hashnode.dev/sending-blogs-updates-to-telegram-with-express
---

In this article, we are going to build a server with NodeJs and Express framework that reads content from an RSS link and extracts the last entry of a blog page and sends it to a telegram Bot. Like a newsletter but using Telegram instead of an email provider.

To accomplish this, we will need to install Express, an RSS reader library, a library for a telegram bot and a cron job library.

What we will do is, build a server that runs a cron job, reads from an RSS feed, extracts the last entry and sends it to a Telegram chat.

### Requirements

- NodeJS installed

### Building the Server

**app.js**

```

import express from 'express';

const app = express();
const port = 8000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

```

Here we just define a simple express server. We create an instance of the `express()` class. Define the port from which the app will be listening. And a route with a "Hello World!" message as a response.

Now, we are going to add a cron job.

We will use "node-cron" library.

```
npm install node-cron

```

In the same file, we add a cron job.

```
import cron from 'node-cron';
...
cron.schedule("*/15 * * * * *", function () {
    console.log("---------------------");
    console.log("running a task every 15 seconds");
  });

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

```

If we run the `node app.js` command.

We will see the message "running a task every 15 seconds" in the command line.

We will change that, I will set the schedule to run every Monday at 12 pm. I usually publish my articles every Monday before 12 pm. So, when this cron job starts it should be a new article posted. If I didn't post a new article before this time. It will be sent the next Monday.

Now, we need an RSS reader to parse the RSS feed of a blog page.

We import the "rss-parser" library.

```
npm install rss-parser

```

We create a new file, `rssFeed.js`.

**rssFeed.js**

```
import Parser from "rss-parser";
let parser = new Parser();

async function LastEntry(link) {
    try {
      const feed = await parse(rssLink);
      const lastEntryLink = feed.items[0].link;
      return lastEntryLink;  
    } catch (err) {
      console.log(err);
      return 'Unable to fetch RSS feed';
    }
};

export default LastEntry;

```

Here we import the Parser class from the "rss-parser" library and create an instance of the Parser class.

Then we create the `LastEntry()` function, to retrieve and return the link of the last entry of the RSS feed.

We store the link of the last entry in the `lastEntryLink` variable. If the function is unable to fetch the RSS feed, it will return the message "Unable to fetch RSS feed".

**app.js**

```
import LastEntry from './rssFeed.js';
import express from 'express';

import cron from 'node-cron';

let rssLink = 'https://carlosmv.hashnode.dev/rss.xml';

const app = express();
const port = 8000;

cron.schedule("*/15 * * * * *", function () {
    console.log("---------------------");
    console.log("running a task every 15 seconds");
  });

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/feed',async (req, res) => {
   try {
      let lastEntry = await LastEntry(rssLink);  
      res.send(lastEntry);
    } catch (err) {
      console.log(err);
      res.status(500).send('Unable to fetch RSS feed');
    }
})

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

```

We import the `LastEntry()` function from the rssFeed.js file.

We define the variable rssLink, which contains the URL of the RSS feed.

The `/feed` route uses the `LastEntry()` function to fetch the latest entry from the RSS feed and returns it to the client.

If we start the server and navigate to `localhost:8000/feed` we will see the last entry of the blog as a response.

### Creating the Telegram Bot

#### BotFather

To create a Telegram bot, we need a token.

Go to the Telegram App and enter [@BotFather](https://hashnode.com/@BotFather) in the search bar.

![Screenshot-2022-12-16-092357](https://www.freecodecamp.org/news/content/images/2022/12/Screenshot-2022-12-16-092357.png)

Select `/start` to activate the bot. Then we select `/newbot` and follow the instructions to create a bot.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477219572/f9d3a9ce-4534-42cb-b448-8d8529619efd.png)

We have to choose a name that the users will see and a username. Then the bot will send us a message with our token in it.

### Creating the Channel

To create a channel, we click on the pencil icon in Telegram.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477352861/447d0530-25a4-4c76-a9cd-2dbb6bd2e8ce.png)

And select "New Channel".

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477389597/877fce19-331a-42f6-96aa-8ddc3bd90fb9.png)

Then, we write a name for the channel.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477555628/c7d49efd-e468-43bc-9480-d41992d65003.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477520962/3c77c9de-fd1f-4b1a-82db-9e4c8912b27e.png)

We have to add our bot as a member and admin in this channel.

We click on the settings button. And we click on "Edit".

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477676966/46a39760-b18a-4896-8db2-580c4d3bbada.png)

Then, we click on "Administrators" and click on "Add Admin".

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477754396/fe7ffab0-18ad-47c3-9c87-84b8a90e79ce.png)

We search for the bot, and add it.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477803401/f0889f6c-d525-4a14-8e76-8d3fdd8aded5.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477821954/30b6edc9-adfc-4ac8-a42e-7eab136c0963.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477843761/8c9abc37-37d4-4a4b-8f9e-c67218f40ac0.png)

Now, for the bot to be able to send messages to the Channel we have to provide it the "Chat ID" of the channel.

To the chat ID, we go to the Telegram search bar and type "ID Bot".

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690477979928/4dc6531c-1a57-42e3-896f-bc7501a460e5.png)

To get Channel's ID we go to the Channel and type "/getgroupid", then we forward the message to IDBot.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690478108008/feeb2ee9-f5b8-4645-a9c9-8e631c855079.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690478126266/2c8e6666-2596-4dc8-b65d-cb47d8b06905.png)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690478147617/d0b8f2ba-782a-44b3-859d-d120b7625cbf.png)

The IDBot will reply with your Channel ID, the ID should start with "-100".

Now, we go again to the `app.js` file and use the bot token to interact with Telegram's API and the channel ID to send messages to the channel.

```
import LastEntry from './rssFeed.js';
import express from 'express';
import cron from 'node-cron';
import TelegramBot from 'node-telegram-bot-api';

const app = express();
const port = 8000;

const token = 'TELEGRAM BOT TOKEN';

const rssLink = 'https://carlosmv.hashnode.dev/rss.xml';
const ChatID = "CHANNEL ID"

const bot = new TelegramBot(TOKEN, {polling: true});

cron.schedule("*/15 * * * * *", async function() {
    console.log("---------------------");
     try {
      console.log("Retrieving the last update");
      let lastEntry = await LastEntry(rssLink);  
      console.log("Sending the last article");
      bot.sendMessage(chatID, lastEntry)
    } catch(err) {
      console.log(err);
      bot.sendMessage(chatID, 'Unable to retrieve latest RSS feed update')  
    }

  });

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

```

We import the TelegramBot class from the `node-telegram-bot-api` package. This class is used to interact with the Telegram Bot API. We create constants to store the Bot token and the chat ID of the channel in `token` and `chatId` constants, respectively.

We create an instance of the `TelegramBot` class.

Then, the schedule function retrieves the latest entry from the RSS feed. The entry is then sent to the Telegram channel with the ChatID of `CHANNEL ID`.

We start the server with `node app.js` command.

We should see this output in our command line:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690479371820/ec30fa81-c7a6-4b51-a2d8-8d1858d38fcf.png)

And if we go to our channel. We should see the last article we published in our blog, in my case this:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690479454315/82e27c7b-daad-4f62-bfc8-bf378abb7848.png)

Now, we just have to modify the cron job. Right now it was set to run every 15 seconds. But should be set up to run in the schedule we publish a new article.

I publish a new article once a week, on Monday morning.

So my cron job would look like this:

```
cron.schedule("0 0 13 * * 1", async function() {
    c try {
      console.log("Retrieving the last update");
      let lastEntry = await LastEntry(rssLink);  
      console.log("Sending the last article");
      bot.sendMessage(chatID, lastEntry)
    } catch(err) {
      console.log(err);
      bot.sendMessage(chatID, 'Unable to retrieve latest RSS feed update')  
    }
  });

```

### Conclusion

In this article, we explored how to send blog updates to a Telegram channel using the Express framework in Node.js. We created an Express server with a cron job that parses the RSS feed for new blog posts and sends it as a message to a Telegram channel bot. This allows our blog to automatically notify subscribers when a new post is published.

Thank you for taking the time to read this article.

If you have any recommendations about other packages, architectures, how to improve my code, my English, or anything; please leave a comment or contact me through [**Twitter**](https://twitter.com/Carlos_marcv), or [**LinkedIn**](https://www.linkedin.com/in/carlos-marcano-a2135a134/).

The source code is [here](https://github.com/carlosm27/newsletter).

### Resources

[Scheduling Jobs with Node.js](https://reflectoring.io/schedule-cron-job-in-node/)

[How To Use node-cron to Run Scheduled Jobs in Node.js](https://www.digitalocean.com/community/tutorials/nodejs-cron-jobs-by-examples)

[rss-parser README](https://github.com/rbren/rss-parser)

[feed-extractor README](https://github.com/extractus/feed-extractor)

[node-cron README](https://github.com/kelektiv/node-cron)

[CronTab](https://crontab.guru/#0_12_*_*_*)

[Express Documentation](https://expressjs.com/en/api.html)

[node-telegram-bot-api README](https://github.com/yagop/node-telegram-bot-api)