Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Carlos Armando Marcano Vargas
Carlos Armando Marcano Vargas

Posted on • Originally published atcarlosmv.hashnode.dev on

Sending Blog's 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}`);});
Enter fullscreen modeExit fullscreen mode

Here we just define a simple express server. We create an instance of theexpress() 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
Enter fullscreen modeExit fullscreen mode

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}`);});
Enter fullscreen modeExit fullscreen mode

If we run thenode 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
Enter fullscreen modeExit fullscreen mode

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;
Enter fullscreen modeExit fullscreen mode

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

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

We store the link of the last entry in thelastEntryLink 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}`);});
Enter fullscreen modeExit fullscreen mode

We import theLastEntry() function from the rssFeed.js file.

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

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

If we start the server and navigate tolocalhost: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 in the search bar.

Screenshot-2022-12-16-092357

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

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.

And select "New Channel".

Then, we write a name for the channel.

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

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

We search for the bot, and add it.

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

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

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

Now, we go again to theapp.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}`);});
Enter fullscreen modeExit fullscreen mode

We import the TelegramBot class from thenode-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 intoken andchatId constants, respectively.

We create an instance of theTelegramBot 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 ofCHANNEL ID.

We start the server withnode app.js command.

We should see this output in our command line:

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

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')      }  });
Enter fullscreen modeExit fullscreen mode

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 throughTwitter, orLinkedIn.

The source code ishere.

Resources

Scheduling Jobs with Node.js

How To Use node-cron to Run Scheduled Jobs in Node.js

rss-parser README

feed-extractor README

node-cron README

CronTab

Express Documentation

node-telegram-bot-api README

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a backend developer, I enjoy writing tutorials on how to use open-source projects in Python, Go, and Rust, that I use or find interesting.
  • Location
    Maturin/Venezuela
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp