-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcron_job.js
69 lines (58 loc) · 1.96 KB
/
cron_job.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'use strict'
// 3rd party library imports
var cron = require('cron')
var twilio = require('twilio')
var rollbar = require("rollbar")
rollbar.init(process.env.ROLLBAR_TOKEN)
// project imports
var db = require('./db')
var message_text = require('./message_text.json')
var forecast = require('./temp_forecast')
// constants
var NOTIFICATION_TIME = 20 // 8 pm
var NOTIFICATION_TEMPERATURE = 20
var TWILIO_SID = 'AC4d903012a56c8cba55657d6f9520846e'
var TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN
var TWILIO_NUMBER = '+19073122014'
var DELAY = 500 // throttle calls to Twilio
var job = new cron.CronJob({
// run every day at the hour specified above
cronTime: '0 ' + NOTIFICATION_TIME + ' * * *',
// cronTime: '* * * * *', // every minute
onTick: sendMessages,
timeZone: 'America/Anchorage'
});
function sendMessages() {
// get weather
forecast.getLowTemps(function(err, data) {
if (err) return rollbar.handleError(err)
var subscribers = db('subscribers').filter(sub => data[sub.zip] <= NOTIFICATION_TEMPERATURE)
// loop over subscribers with delay
var inter = setInterval( gen => {
var next = gen.next()
if (next.done) return clearInterval(inter)
var subscriber = next.value
module.exports.sendToTwilio(subscriber.phone, randomElement(message_text.NOTIFICATIONS))
}, DELAY, subscribers[Symbol.iterator]())
})
}
function sendToTwilio(to, body){
var twilio_client = twilio(TWILIO_SID, TWILIO_AUTH_TOKEN)
twilio_client.sendMessage(
{
to: to,
from: TWILIO_NUMBER,
body: body,
},
function (err, response) {
if (err) return rollbar.handleError(err)
console.log(response)
}
)
}
function randomElement(items) {
return items[Math.floor(Math.random()*items.length)]
}
module.exports.job = job
module.exports.sendMessages = sendMessages
module.exports.sendToTwilio = sendToTwilio