DEV Community

Cover image for Creating a Telegram News Bot - post 2
DShaw0004
DShaw0004

Posted on

Creating a Telegram News Bot - post 2

Briefing

This is the second post of how I create a telegram bot which serves news daily with nodeJS. In this post, I am going add code for handling /subscribe command and fetch the news. This series is going to be long so follow me to stay updated with the posts of this series. Also if you don't see the previous post about how to create a telegram bot then check it out


I am going to use replit for this project. And this is not sponsored I just felt that replit would be great for this project.


Why the '/subscribe' command ?

This /subscribe command will ensure that the news will be send to those who want this news service not everyone without their will.
For now it will respond 'subscribed' in response of /subscribe command, I will edit it later.


bot.onText(/\/subscribe/, msg => {
    let res = "subscribe"
    bot.sendMessage(msg.chat.id, res)
})

Enter fullscreen mode Exit fullscreen mode

Fetch the news :

For this project I am going to use newsapi. Again this is not sponsored by newsapi.
I hope that you know how to fetch an API. So I am going to create a different file to handle all the API fetching.
now our project structure look like this.

daily-news-bot
    |
    |- index.js
    |- fetchNews.js
Enter fullscreen mode Exit fullscreen mode

In the fetchNews.js file firstly import node-fetch to use fetch api and then write a function to fetch the news and return it.


const fetch = require("node-fetch")
const apiKey = process.env["newsApi"]

async function fetchNews (){
    const fetchingAPI = await fetch(`https://newsapi.org/v2/top-headlines?country=in&category=general&language=en&apiKey=${apiKey}`)
    const response = await fetchingAPI.json()   

    if(response.status == "ok"){
        return response.articles
    }
}

module.exports = fetchNews

Enter fullscreen mode Exit fullscreen mode

Again, for now bot will return the news using /news. The /news is only for test purpose, it will be replaced later.
Now import the fetchNews function into your index.js file. Then write some code for handling /news command. But now we going to style our response text using parse_mode: "HTML" as third argument of bot.sendMessage. You can read the docs to more about this.
Firstly we fetch the news then iterate over it and send each articles.


const fetchNews = require("./fetchNews.js")

bot.onText(/\/news/, async msg => {
    let res = await fetchNews()
        news.map(n => {
            bot.sendMessage(msg.chat.id, `<strong>${n.title}</strong>\n\n${n.description}\n<a href="${n.url}">read full</a>`, { parse_mode: "HTML" })
        })
})

Enter fullscreen mode Exit fullscreen mode

Implementing a database :

Since we add a /subscribe it will be great if we also connect this to a database so that our bot can send news to its subscribers automatically. Since I am using replit to make this bot I am also going to use replit's Database for now.
Now create a new file to handle all replit database stuff.
Now your file structure should look something like this.

daily-news-bot
    |
    |- index.js
    |- fetchNews.js
    |- replitdb.js
Enter fullscreen mode Exit fullscreen mode

Let's create a function and write some code to add new subscriber.


const Database = require("@replit/database");
const db = new Database();

async function addNewSubscriber(userId) {
        let response = "something went wrong !";
    let users = await db.get("subscribers") || [];
        users = new Set(users);
    users.add(userId);
    let setValue = users.values();
    db.set("subscribers",Array.from(setValue))
         .then(() => {
             response = "successfully subscribed"
          });
        return response;
}
module.exports = addNewSubscriber
Enter fullscreen mode Exit fullscreen mode

Also we have to add to function to the /subscribe command.


const addNewSubscriber = require("./replitdb.js");
bot.onText(/\/subscribe/, async msg => {
    let res = await addNewSubscriber(msg.chat.id)
    bot.sendMessage(msg.chat.id, res)
})

Enter fullscreen mode Exit fullscreen mode

You can read replit database docs for more info.

Why Set ?

If you know about javascript Set then you know why did I use it for addNewSubscriber() in replitdb. If you don't know about then - Set can only have unique values. If try to add a duplicate value to a Set it will remove one of them. It will ensure that database won't have same user's chat id for more than once.

What's Next ?

Next I am going to automate the bot so it send the news automatically to its subscribers without any human interaction also going to add a check for new subscriber so that we don't have to run addNewSubscriber() every time.

For now Bye 👋.

Top comments (0)