-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (63 loc) · 2.18 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
require('dotenv') .config();
const https = require('https');
const GoogleSpreadsheet = require('google-spreadsheet');
const date = new Date();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const formattedDate = `${months[date.getMonth()]}${date.getDate()}`;
const POST_OPTIONS = {
hostname: 'hooks.slack.com',
path: `/services/${process.env.SLACK_KEY}`,
method: 'POST',
port: 443,
};
exports.handler = (event, context) => {
const doc = new GoogleSpreadsheet(process.env.SHEET_KEY);
doc.useServiceAccountAuth(
{
client_email: process.env.CLIENT_EMAIL,
private_key: process.env.PRIVATE_KEY.replace(/\\n/g, '\n'),
},
err => {
if (err) return console.log(err);
doc.getRows(
1,
{
limit: 5,
query: `date = ${formattedDate} & active = TRUE`,
},
(error, rows) => {
if (err) return console.err(error);
const info =
rows &&
rows.map(x => ({
name: x.name,
date: x.date,
cake: x.favouritecake,
active: x.active && x.active.toUpperCase() === 'TRUE',
}));
if (info && info.length > 0) {
const names = info.map(({ name }) => name).join(' & ');
const cakes = info.map(({ cake }) => cake).join(' & ');
const message = JSON.stringify({
username: 'Captain Picard',
icon_url: 'https://s3-us-west-2.amazonaws.com/intergalactic-assets/picard-avatar.jpg',
text: `Happy Birthday ${names}! Their favourite ${
info.length > 1 ? 'cakes are' : 'cake is'
} ${cakes} \n https://s3-us-west-2.amazonaws.com/intergalactic-assets/cake-it-so.jpg`,
});
const req = https.request(POST_OPTIONS, res => {
res.setEncoding('utf8');
res.on('data', data => context.succeed('Message Sent: ' + data));
});
req.on('error', e => {
context.fail(`Failed ${e}`);
});
req.write(message);
req.end();
}
return;
},
);
},
);
};