-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (74 loc) · 2.34 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
require('dotenv').config();
const xoxb = process.env.XOXB;
const channel = process.env.CHANNEL;
const cronPattern = process.env.CRON_PATTERN || '0 0 14 * * 2-6';
const cron = require('node-cron');
const plants = require('./data/plants.json');
const locations = require('./data/locations');
if (!xoxb) {
console.log('Slack bot OAuth token not found.');
return;
}
if (!channel) {
console.log('Recipient channel not specified.');
}
if (!Array.isArray(plants)) {
console.log('plant.json is not an array.');
return;
}
// console.log(prepare());
cron.schedule(cronPattern, () => {
const msg = prepare();
if (!msg) return;
send(msg);
});
function prepare() {
const getNames = (arr) =>
arr.reduce((acc, cur, idx, src) => {
if (idx === 0) return cur.name;
if (idx === src.length - 1)
if (idx === 1) return acc + ' and ' + cur.name;
else return acc + ', and ' + cur.name;
return acc + ', ' + cur.name;
}, '');
const dayOfWeek = new Date().getDay();
const waterToday = plants.filter((p) => p.days.includes(dayOfWeek));
const names = getNames(waterToday);
const keepMoist = plants.filter((p) => p.keepMoist);
const alsoNames = getNames(keepMoist);
const describeLocations = locations.reduce((acc, cur, idx, src) => {
const somePlants = [...waterToday, ...keepMoist].filter(
(p) => p.location === idx,
);
if (somePlants.length === 0) return acc;
let be = 'is';
if (somePlants.length > 1) be = 'are';
const n = getNames(somePlants);
if (idx === 0) return `${n} ${be} ${cur}.`;
return `${acc} ${n} ${be} ${cur}.`;
}, '');
if (waterToday.length === 0 && keepMoist.length === 0) return;
if (waterToday.length === 0)
return `Coo coo. Make sure the soil is moist for ${alsoNames}. ${describeLocations}`;
else
return `Coo coo. Don't forget to water ${names} today. Also, make sure the soil is moist for ${alsoNames}. ${describeLocations}`;
}
async function send(message) {
const bent = require('bent');
const url = 'https://slack.com/api';
const post = bent(
url,
'POST',
{
'Content-Type': 'application/json; charset=utf-8',
Authorization: 'Bearer ' + xoxb,
},
'json', //response encoding
200, //response status filter
);
const res = await post('/chat.postMessage', {
channel,
text: message,
});
console.log(res);
}