Visiting a web page daily for COVID-19 data is a tedious task especially if you are a lazy programmer like me๐. In order to solve this problem, I have created a notification system that sends me data about worldwide Coronavirus cases daily at a specified time.
In this tutorial, I'm going to show this how you can make your own system like this one.
Setting up Twilio account
In order to send a message, you need Twilio credentials. Go to Twilio console and get the Twilio number which we will use to send SMS using API.
From your dashboard, you need your ACCOUNT SID
, AUTH TOKEN
, and TRIAL NUMBER
, copy them and save them in a .env
file in your project's root directory.
It should look something like below
ACC_SID='your-account-sid'
AUTH_TOKEN='your-auth-token'
FROM='your-twilio-number'
# Also add your number here (recommended)
TO='your-number'
Sending a message
Now we need to install Twilio package for node.js
npm install twilio
Now let's test our credentials by sending a message.
const accountSid = process.env.ACC_SID;
const authToken = process.env.AUTH_TOKEN;
const twilio = require("twilio");
const client = new twilio(accountSid, authToken);
client.messages
.create({
body: "Hello World!",
to: process.env.TO,
from: process.env.FROM
})
.then(message => console.log(message.sid));
Now run the file using
node index
If all goes well you'll receive an SMS with the text "Hello World!"๐
Getting COVID-19 data
We will use this API to get the latest data about COVID-19.
To get the data in Node.js we will use the request
library since I found it quite user-friendly.
npm install request
To send data in the SMS
request(
"https://covidapi.info/api/v1/global",
{ json: true },
(err, res, body) => {
if (err) {
return console.log(err);
}
var result = body.result;
// Format message
var msg = `\n Coronavirus Stats (IND):
\nConfirmed: ${result.confirmed}
\nDeaths: ${result.deaths}
\nRecovered: ${result.recovered}
`;
sendNotification(msg);
}
);
// Send message
function sendNotification(msg) {
client.messages
.create({
body: msg,
to: process.env.TO,
from: process.env.FROM
})
.then(message => console.log(message.sid));
}
Setting up a cronjob
in order to set up a cronjob in Node.js, we can use a library called node-cron
npm install node-cron
Now we have to run the above code every day at 8:00 AM (say). Wrap the above code to send SMS every day at 8 AM with the latest data.
const twilio = require("node-cron");
cron.schedule("0 8 * * *", () => {
request(
"https://covidapi.info/api/v1/global",
{ json: true },
...
...
});
Bonus
Let's also add a reminder to wash our hands every two hours. We can add another cronjob to send SMS
// Cron job to send message every 2 hour from 8-23 daily
cron.schedule("0 9-23/2 * * *", () => {
sendNotification("Its time to wash your hands ๐");
});
Below is the GitHub repository where you can find all the code. Also, give it a starโญ if you like.๐ค
Top comments (1)
Thank you!