You are on page 1of 45

Department of Electronics and Communication Engineering

CREATION OF COVID-19 TRACKER BOT


Organised by Embedded and IOT Club

By:
Bala Srinyvas R P IV ECE
Bharath N IV ECE
AGENDA?

Telegraf library syntax discussion.

Advanced API access and retrieving responses.

COVID-19 Tracker bot Creation.

Hosting Bot.
Quick Recap?

What is a chat-bot?
Ways to link a Chat-bot?
Software’s Needed?

Creating a quick basic bot with node-pad


TELEGRAF LIBRARY

https://telegraf.js.org/#/

$ npm install telegraf --save

Example
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply('👍'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()
BOT TOKEN
To access all functionalities of telegram BOT API.

Eg.123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ

BOT Father

NOTE:

Secure Information

process.env.BOT_TOKEN
MIDDLEWARE
Modify requests and responses.

Interaction between user and bot.

Eg= ctx,next

const bot = new Telegraf(process.env.BOT_TOKEN)


bot.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log('Response time: %sms', ms)
})
bot.on('text', (ctx) => ctx.reply('Hello World'))
bot.launch()
Error handling
Default : Errors are Printed In STDERR.

const bot = new Telegraf(process.env.BOT_TOKEN)


bot.catch((err, ctx) =>
{
console.log(`Ooops, encountered an error for ${ctx.updateType}`, err)
})
bot.start((ctx) =>
{
throw new Error('Example error')
})
bot.launch()
Context
Property Description

[ctx.message] Received message


[ctx.editedMessage] Edited message
[ctx.inlineQuery] Received inline query

New incoming channel post of any kind — text,


[ctx.channelPost]
photo, sticker, etc.

New version of a channel post that is known to


[ctx.editedChannelPost]
the bot and was edited

New version of a anonymous poll that is known to


[ctx.poll]
the bot and was changed

This object represents an answer of a user in a


[ctx.pollAnswer]
non-anonymous poll.

[ctx.chat] Current chat info


[ctx.from] Sender info
ctx.webhookReply Shortcut to ctx.telegram.webhookReply
SYNTAX-Context
bot.use((ctx)
=>
{
console.log(ctx.message)
})

Accessing DB-Data

const bot = new Telegraf(process.env.BOT_TOKEN)


bot.context.db = {
getScores: () => { return 42 }
}
bot.on('text', (ctx) => {
const scores = ctx.db.getScores(ctx.message.from.username)
return ctx.reply(`${ctx.message.from.username}: ${scores}`)
})
bot.launch()
EXAMPLES
Shortcut Bound to
forwardMessage telegram.forwardMessage
reply telegram.sendMessage
replyWithAudio telegram.sendAudio
replyWithDice telegram.sendDice
replyWithDocument telegram.sendDocument
replyWithGame telegram.sendGame
replyWithHTML telegram.sendMessage
replyWithInvoice telegram.sendInvoice
replyWithLocation telegram.sendLocation
replyWithPhoto telegram.sendPhoto
replyWithPoll telegram.sendPoll
replyWithQuiz telegram.sendQuiz
replyWithSticker telegram.sendSticker
replyWithVideo telegram.sendVideo
replyWithVoice telegram.sendVoice
SESSION
Created and destroyed for each use.

const session = require('telegraf/session')


const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(session())
bot.on('text', (ctx) => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
return ctx.reply(`Message counter:${ctx.session.counter}`)
})
bot.launch()
Reply Messages

bot.on('message', (ctx) =>


{
return ctx.reply('Hello')
})
bot.on(['sticker', 'photo'], (ctx) =>
{
console.log(ctx.message)
ctx.reply('Cool!')
ctx.replyWithVideo({ source: '/path/to/video.mp4' })
})
EXTRA/MARKUP -

Formatting and using HTML output.


Usage of <b>,<i>,<u> etc.,
Formatting text
Creating and designing buttons
Accessing API’S
{
{ "active": "2012",
"an": "0", "confirmed": "7140",
"ap": "1356", "deaths": "183",
"ar": "4", "deltaconfirmed": "233",
"as": "397", "deltadeaths": "5",
"br": "203", "deltarecovered": "117",
"ch": "1", "lastupdatedtime": "09/07/202
"ct": "107 0 19:38:14",
}, "migratedother": "0",
"recovered": "4945",
"state": "Punjab",
"statecode": "PB",
"statenotes": "“
},
Image API

<img src="https://quickchart.io/chart?
c={type:'pie',data:{labels:
['January','February',
'March','April', 'May'], datasets:
[{data:[50,60,70,180,190]}]}}">
SCHEDULING MESSAGES

npm install node-schedule

var schedule = require('node-schedule');
var date = new Date(2020, 07, 12, 5, 30, 0);
var j = schedule.scheduleJob(date, function(){
  console.log(‘Gold Price:50,880.00‘);
});

j.cancel();
COVID-19 BOT CREATION

STEP 1-Install Required Softwares.


STEP-2 Creating Folder & Installing Packages

Right Click on Desktop & Create a new folder.

NOTE:

Avoid Spaces and special characters as NPM will produce error.

Installing Packages

npm init -y

npm install telegraf - -save

npm install dotenv - -save

Create index.js
BOT-Father
Code Explanation
require('dotenv').config()

const Telegraf=require('telegraf')

const bot=new Telegraf(process.env.BOT_TOKEN)

const Markup=require('telegraf/markup')

const {inlineHandler}=require("./js/inlineHandler.js")

const rp = require('request-promise');

var request = require('request');

const Extra=require('telegraf/extra')
Part-2
bot.start(ctx=>{
try{
const requestOptions = {
method: 'PUT',
uri: 'https://api.backendless.com/C7C46BF0-D887-EE41-FFCC-C473E8648400/9579C9DB-155C-4D21-A30D-
39190ED05E67/counters/id1/increment/get',
headers: {
'Content-Type': 'application/json'
},
json: true,
};
rp(requestOptions).then(response => {
console.log('API call response:', response);
}).catch((err) => {
console.log('API call error:', err.message);
});
}catch(e)
{}

ctx.reply(`Hello ${ctx.from.first_name} , Welcome to the fastest COVID-19 Tracker Bot . For more details \nRefer /help`)
})
Part 3

bot.help(ctx=>
{
ctx.reply('Here is the complete walk-through about the Bot.\
<b><u>\n\nCommands:</u></b>\n\n\
/start\nWelcome to the Bot !!!\n\n\
/total\nDisplays the live count of COVID-19 cases in India.\n\n\
/statewise\nList of COVID cases of all states in India.\n\n\
/country\nShows the COVID cases in the specified country.\n\n\
/state\nList of COVID cases in particular state.\n\n\
/district\nCount of identified Cases in specific district.\n\n\
/help\nView all available Commands.\n\n\
/about\nInformation about the bot',Extra.HTML())
}
)
Part 4
bot.command('country',ctx=>ctx.reply('Enter the Country name for which the count is
needed :'))

bot.command('state',ctx=>ctx.reply('Enter the State name in India for which the count is


needed :'))

bot.command('district',ctx=>ctx.reply('Enter the District name in India for which the


count is needed :'))

bot.command('about',ctx=>ctx.reply('Data Source - <a


href="https://api.covid19india.org">https://api.covid19india.org</a>\n\n\
Developer Contact = <a href="https://t.me/balarp">Bala Srinyvas R
P</a>',Extra.HTML().webPreview(false)))
Part 5
bot.command('total',ctx=>{

var data=request({url: 'https://api.covid19india.org/data.json', json: true}, function(err, res, json) {


if (err) {
throw err;
}
var tc=json.cases_time_series[json.cases_time_series.length-1].totalconfirmed;
var tr=json.cases_time_series[json.cases_time_series.length-1].totalrecovered;
var dc=json.cases_time_series[json.cases_time_series.length-1].dailyconfirmed;
var dr=json.cases_time_series[json.cases_time_series.length-1].dailyrecovered;
var dt=json.cases_time_series[json.cases_time_series.length-1].dailydeceased;
var td=json.cases_time_series[json.cases_time_series.length-1].totaldeceased;
var date=json.cases_time_series[json.cases_time_series.length-1].date;
ctx.reply(
`COVID-19 INDIA updates as on <b>${date}</b>\nTotal Cases <b>${tc}</b> ↗️\nTotal Recovered <b>${tr}</b> ↗️\nToday
Confirmed <b>${dc}</b> ↗️\nToday Recovered <b>${dr}</b> ↙️\nToday's Death <b>${dt}</b> ⏺\nTotal Death
<b>${td}</b> 🔴\n`,Extra.HTML()
)
}
)
})
Part -6 Markup Keyboard
bot.command('statewise',ctx=>ctx.reply('Customized Selection',Markup.keyboard([['All States','North Region','South
Region'],['East Region','West Region']]
bot.hears('West Region',ctx=>{
var data=request({url: 'https://api.covid19india.org/data.json', json: true}, function(err, res, json) {
if (err) {
throw err;
}
var r=""
var q=""
var west=["Rajasthan","Gujarat","Goa","Maharashtra","Madhya Pradesh","Daman and Diu","Ladakh"];
for (i = 1; i <json.statewise.length; i++) {
q = json.statewise[i].state;
if(west.includes(q))
{
r += json.statewise[i].state;
r+=' = <b>'+ json.statewise[i].confirmed+'</b>'
r+='(+'+json.statewise[i].deltaconfirmed+')'
r+='\n';
}}
ctx.reply(
`West Region Count of Total Confirmed Cases:\n${r}`,Extra.HTML().markup(
m=>inline4(m)
)
)
})})
Part -7 INLINE KEYBOARD
const inline4= (m)=>m.inlineKeyboard(
[
[m.callbackButton('West Region Detailed List ↗','West Region Detailed List ↗')]
])
Part
bot.action('West Region Detailed List ↗',ctx=>
-8
ctx.reply
('Customized Selection',
Markup.keyboard(
[
['Rajasthan','Gujarat','Maharashtra'],
['Ladakh','Daman and Diu','Madhya Pradesh'],
['Goa']
]) .resize().extra()))
Part -9
Var flag=false;
var data=request({url: 'https://api.covid19india.org/data.json', json: true}, function(err, res, json) {
if (err) {
throw err;
}
let msg=ctx.message.text
let msg1=msg.toLowerCase().trim();
let name=msg1.charAt(0).toUpperCase()+msg1.slice(1);
for (i = 1; i <json.statewise.length; i++)
{
let temp=json.statewise[i].state;
if(json.statewise[i].state==msg || json.statewise[i].state==name || temp==msg1){
var ta=json.statewise[i].active;
var tc=json.statewise[i].confirmed;
var dd=json.statewise[i].deaths;
var dr=json.statewise[i].recovered;
var dc=json.statewise[i].deltaconfirmed;
var dd1=json.statewise[i].deltadeaths;
var dr1=json.statewise[i].deltarecovered;
var date=json.statewise[i].lastupdatedtime;
flag=true;
if(dc!=0 && dc!='0')
{
ctx.reply(
`${json.statewise[i].state} updates as on <b>${date}</b>\nTotal Cases <b>${tc}</b>(+${dc})↗\nActive Cases <b>$
{ta}</b> ↗\nTotal Recovered <b>${dr}</b> (+${dr1})↗️\nTotal Death <b>${dd}</b> (+${dd1}) 🔴\n`,Extra.HTML()
)
ctx.replyWithPhoto(`https://quickchart.io/chart?bkg=white&c={type:'pie',data:{labels:['Total Cases','Active
Cases','Total Recovered','Total Death'],datasets:[{data:[${tc},${ta},${dr},${dd}],hoverBackgroundColor:['white'],backgroundColor:
['hotpink','coral','lime','red']}]}}`)
}
else
{
ctx.reply(
`${json.statewise[i].state} updates as on <b>${date}</b>\nTotal Cases <b>${tc}</b>(+${dc})↔\nActive Cases <b>$
{ta}</b> ↗️\nTotal Recovered <b>${dr}</b> (+${dr1})↗\nTotal Death <b>${dd}</b> (+${dd1}) 🔴\n`,Extra.HTML()
)
ctx.replyWithPhoto(`https://quickchart.io/chart?bkg=white&c={type:'pie',data:{labels:['Total Cases','Active
Cases','Total Recovered','Total Death'],datasets:[{data:[${tc},${ta},${dr},${dd}],hoverBackgroundColor:['white'],backgroundColor:
['hotpink','coral','lime','red']}]}}`)
}
Part -10
try{
If(flag==false)
{
var data=request({url: 'https://api.covid19india.org/state_district_wise.json', json: true}, function(err, res, json) {
if (err) {
throw err;
}
for(i=0;i<arr.length;i++)
{
try{
var q=json[arr[i]].districtData[msg].active;
var q1=json[arr[i]].districtData[msg].confirmed;
var q2=json[arr[i]].districtData[msg].recovered;
var q3=json[arr[i]].districtData[msg].deceased;
var q4=json[arr[i]].districtData[msg].delta.confirmed;
var q21=json[arr[i]].districtData[msg].delta.recovered;
var q31=json[arr[i]].districtData[msg].delta.deceased;
console.log(json[arr[i]].districtData[msg].active);
}
catch(e)
{}
if(q4!=0 && q4!='0')
{
ctx.reply(`${msg1} COVID DETAILS=\nTotal Cases=<b>${q1}</b>(+${q4}) ↗\nActive Cases=<b>${q}</b> ↗\nTotal
Recovered=<b>${q2}</b>(+${q21}) ↗\nTotal Death=<b>${q3}</b>(+${q31})🔴\n`,Extra.HTML())
ctx.replyWithPhoto(`https://quickchart.io/chart?bkg=white&c={type:'pie',data:{labels:['Total Cases','Active
Cases','Total Recovered','Total Death'],datasets:[{data:[${q1},${q},${q2},${q3}],hoverBackgroundColor:
['white'],backgroundColor:['hotpink','coral','lime','red']}]}}`)
}
else
{
ctx.reply(`${msg1} COVID DETAILS=\nTotal Cases=<b>${q1}</b>(+${q4}) ↔\nActive Cases=<b>${q}</b> ↗\nTotal
Recovered=<b>${q2}</b> (+${q21})↗\nTotal Death=<b>${q3}</b> (+${q31})🔴\n`,Extra.HTML())
ctx.replyWithPhoto(`https://quickchart.io/chart?bkg=white&c={type:'pie',data:{labels:['Total Cases','Active
Cases','Total Recovered','Total Death'],datasets:[{data:[${q1},${q},${q2},${q3}],hoverBackgroundColor:
['white'],backgroundColor:['hotpink','coral','lime','red']}]}}`)
}
flag=true;
if(flag==false)
{ let msg=ctx.message.text
var data=request({url: `https://covid19.mathdro.id/api/countries/${msg}/confirmed`, json: true}, function(err, res, json) {
if (err) { throw err;}
try{
var name=json[0].countryRegion;
var tc=json[0].confirmed;
var ac=json[0].active;
var tr=json[0].recovered;
var td=json[0].deaths;
}
catch(e)
{}
if(name!=undefined)
{ ctx.reply(`${msg1} COVID DETAILS of ${name}\nTotal Cases=<b>${tc}</b> ↗\nActive Cases=<b>${ac}</b> ↗\nTotal
Recovered=<b>${tr}</b> ↗\nTotal Death=<b>${td}</b> 🔴\n`,Extra.HTML())
ctx.replyWithPhoto(`https://quickchart.io/chart?bkg=white&c={type:'pie',data:{labels:['Total Cases','Active Cases','Total
Recovered','Total Death'],datasets:[{data:[${tc},${ac},${tr},${td}],hoverBackgroundColor:['white'],backgroundColor:
['hotpink','coral','lime','red']}]}}`)
flag=true;
}
PART-12-FINAL MESSAGE
if(flag==false)
{
ctx.reply('Sorry,Your input could not be recognized.\n Refer /help')
}
}
HOSTING CODE WITH GITHUB & GLITCH

git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/abcd/TEST.git
git push -u origin master
COVID-19 GITHUB LINK

https://github.com/balasrinyvasrp/COVIDbot.git

BOT_TOKEN=10002:balarpXXXX47695
For Any Further Queries ,Please Feel free to Contact Us!!!

Bharath N Bala Srinyvas R P


9585662470 8489963819
1084bharath@gmail.com srinyvas95@gmail.com

You might also like