-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
61 lines (49 loc) · 1.58 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
'use strict';
const fs = require('fs');
const axios = require("axios");
async function monitorWebpage(config) {
const name = config.name;
const url = config.url;
const storage = config.storage;
const telegramBotToken = config.telegramBotToken;
const telegramChatId = config.telegramChatId;
const telegramSendMessageOptions = 'telegramSendMessageOptions' in config ?
config.telegramSendMessageOptions : [];
async function getWebPage() {
const response = await axios.get(url);
return response.data;
}
async function extractSnippet(html) {
const snippet = config.extractSnippet(html);
if (! snippet) {
return Promise.reject('ERROR: Snippet ' + name + ' not found');
}
return snippet;
}
async function checkSnippetsHasChanged(snippet) {
let previousSnippet = false;
if (fs.existsSync(storage)) {
previousSnippet = fs.readFileSync(storage, 'utf8');
}
if (previousSnippet && previousSnippet === snippet) {
return Promise.reject('Snippet ' + name + ' has not changed');
}
fs.writeFileSync(storage, snippet, 'utf8');
return snippet;
}
async function postMessage(snippet) {
const url = 'https://api.telegram.org/bot' + telegramBotToken + '/sendMessage';
let params = {
chat_id: telegramChatId,
text: snippet
};
Object.assign(params, telegramSendMessageOptions);
const response = await axios.post(url, params);
return response.data;
}
return getWebPage()
.then(extractSnippet)
.then(checkSnippetsHasChanged)
.then(postMessage);
}
module.exports = monitorWebpage;