forked from nclr/health-check-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (84 loc) · 3.03 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var fs = require('fs');
var http = require('http');
var https = require('https');
var request = require('request');
var emoji = require('node-emoji')
const {
IncomingWebhook
} = require('@slack/client');
const url = process.env.SLACK_WEBHOOK_URL;
const webhookurl = "https://hooks.slack.com/services/<some-sort-of-secret-key>";
const webhook = new IncomingWebhook(webhookurl);
var notReachable = {};
var notReachabletwice = {};
/* Read configuration and start loops */
fs.readFile('./config.json', 'utf8', function (err, data) {
if (err) throw err;
var conf = JSON.parse(data);
var urls = conf.urls;
for (var name in urls) {
var url = urls[name].url;
var interval = urls[name].interval;
createloop(name, url, interval);
}
});
/* Create a loop that's executed every x milliseconds */
function createloop(name, url, interval) {
var requestLoop = setInterval(function () {
request({
url: url,
method: "GET",
timeout: 10000,
followRedirect: true,
maxRedirects: 10
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
if (typeof notReachable[name] != "undefined") {
if (notReachable[name] == "notagain") {
delete notReachable[name];
var message = name + " " + emoji.get('beers') + " " + getFormattedDate();
send(message);
console.log(message);
}
}
} else {
if (typeof notReachable[name] == "undefined") { // first time
notReachable[name] = "true";
var message = name + " " + emoji.get('hankey') + " " + getFormattedDate();
console.log("first time :" + message);
} else if (notReachable[name] == "true") { // secondtime
notReachable[name] = "notagain"; // we don't want second notification
var message = name + " " + emoji.get('hankey') + " " + getFormattedDate();
console.log(message);
send(message);
}
}
});
}, interval);
}
/* Send message to slack incoming webhook */
function send(text) {
webhook.send(text, function (err, res) {
if (err) {
console.log('Error:', err);
} else {
console.log('Message sent: ', res);
}
});
}
/* Get Timestamp */
function getFormattedDate() {
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
sec = (sec < 10 ? "0" : "") + sec;
var str = '[' + day + "-" + month + "-" + date.getFullYear() + "_" + hour + ":" + min + ":" + sec + ']';
return str;
}