forked from ollionorg/mercury
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
281 lines (246 loc) · 9.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
//Unique bot identifiers and secrets from Slack
const botId = process.env.slackBot;
const clientId = process.env.clientId;
const clientSecret = process.env.clientSecret;
//Set APIs and libraries up
const { WebClient } = require("@slack/web-api");
const {google} = require('googleapis');
const { DateTime } = require('luxon');
const axios = require('axios');
//Ask for temperature
const temperatureStrings = [
"🌡 I know you're really cool ❄️, but could you quantify that specifically in degrees centigrade?",
"🌡 BOT DEMANDS YOUR TEMPERATURE! 🤖",
"🌡 Is that a thermometer in your pocket? 🦾",
"🌡 Aren't you looking hot today! No seriously, could you check your temperature? 🔥",
"🌡 What's the difference between an oral and a rectal thermometer? The taste. 🤢",
"🌡 Scientifically speaking you should be reporting in Kelvin, but I will accept Celsius this one time. 🤓",
"🌡 Greetings human, for your own safety please reveal your current temperature. 🤒",
"🌡 Sorry, my thermal camera is malfunctioning, please input your temperature. 📸",
"🌡 Hey, it's that time of day again. Do your thing! ⏲",
"🌡 Did you know Galileo is often mistaken to be the inventor of the thermometer? GALILEO FIGARO! 🎶",
"🌡 I'm feeling lonely today. Do you have a temperature to cheer me up? 🥺"
];
//Thank for temperature
const readingStrings = [
"Thank you! You've made this bot very happy! 🤖",
"You know I've seen a lot of temperatures in my time, but yours are always the best 💛",
"Thanks! Just so you know, my friends call me 'Freddie' 🎸",
"An excellent temperature 😙👌",
"You know you can't spell Hug without the Hg + U ❤️",
"Smokin'! No wait, that would be bad. Lukewarm! ☀️",
"What? That's perfect! That's the G.T.O.A.T.! 🐐",
"Stay chill my homosapien 🥶"
];
//Welcome to @mercury
const welcomeStrings = [
"Hi there! I'm @mercury and I'm a temperature taking bot. My job is to make sure my humans don't overheat 🤒. Just slack me your temperature and I'll remember it. If you forget to give me your morning temperature you can send me your reading suffixed with `AM` even in the afternoon."
];
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
let sendList = [];
let sheetId = "";
let slack = "";
function authorize(credentials, callback, params) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
oAuth2Client.setCredentials(JSON.parse(process.env.gsuiteToken));
callback(oAuth2Client, params);
}
function writeUsers(auth, params) {
const sheets = google.sheets({version: 'v4', auth});
let values = [];
console.log(params.users);
params.users.forEach(u => {
if (Object.keys(u).length) {
sendMessage(u.user.id, welcomeStrings[Math.floor(Math.random() * welcomeStrings.length)]);
values.push([u.user.id, u.user.real_name, '@' + u.user.name]);
sendList.push(u.user.id);
} else {
values.push([]);
}
});
const req = {
spreadsheetId: sheetId,
range: 'Users!B2:D' + params.rownum,
valueInputOption: 'USER_ENTERED',
resource: {
majorDimension: "ROWS",
range: 'Users!B2:D' + params.rownum,
values: values
}
}
sheets.spreadsheets.values.update(req).then((res) => console.log(res.data));
console.log(sendList);
sendList.forEach(u => {
sendMessage(u, temperatureStrings[Math.floor(Math.random() * temperatureStrings.length)]);
});
}
const resolveEmailsAndUpdateSheet = async (params) => {
const resolvedRows = params.rows.map(row => {
if (!row[1]) {
return slack.users.lookupByEmail({email: row[0]}).catch(e => {
console.log(e + ": " + row[0]);
return {};
});
} else {
sendList.push(row[1]);
return {}
}
});
const complete = await Promise.all(resolvedRows);
writeUsers(params.auth, {rownum: params.rows.length+1, users: complete});
}
function getUsers(auth, params) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: sheetId,
range: 'Users!A2:D',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
console.log("SheetResult = " + rows);
if (rows.length) {
resolveEmailsAndUpdateSheet({rows: rows, auth: auth});
} else {
console.log('No data found.');
}
});
}
function writeTemp(auth, params) {
console.log(params);
const sheets = google.sheets({version: 'v4', auth});
const req = {
spreadsheetId: sheetId,
range: 'Readings!A2:E',
valueInputOption: 'USER_ENTERED',
resource: {
majorDimension: "ROWS",
range: 'Readings!A2:E',
values: [[
params.u,
'=VLOOKUP(INDIRECT("A"&row()),Users!B:C,2, FALSE)',
params.t,
DateTime.local().setZone("Asia/Singapore").toISODate(),
(params.a) ? "AM" : ((DateTime.local().setZone("Asia/Singapore").hour >= 13) ? "PM" : "AM"),
DateTime.local().setZone("Asia/Singapore").toLocaleString(DateTime.DATETIME_SHORT)
]]
}
}
sheets.spreadsheets.values.append(req).then((res) => console.log(res.data));
}
function sendMessage(u, m) {
(async () => {
console.log(`Sending message to ${u}`);
// Post a message to the channel, and await the result.
// Find more arguments and details of the response: https://api.slack.com/methods/chat.postMessage
const result = await slack.chat.postMessage({
text: m,
channel: u,
}).catch(e => {
console.log(e);
});
// The result contains an identifier for the message, `ts`.
console.log(`Successfully send message ${result.ts} in conversation ${u}`);
})();
}
function kelvinToC(kelvin) {
celcius = kelvin - 273.15;
return celcius;
}
function fahrenheitToC(farnheit) {
celcius = (farnheit - 32) * (5/9);
return celcius;
}
function convertResponse(user, response) {
// Simple Number to Celcius/Fahrenheit/Kelvin converter
// Currently range based without RegEx for UoM
celcius = response;
if (response > 200) {
// Assuming Kelvin
celcius = kelvinToC(response);
sendMessage(user, `Guess we a' talkin' Kelvin then 🤓 BTW, for the mere mortals, that's ${celcius}℃`);
} else if (response > 75) {
// Assuming Fahrenheit
celcius = fahrenheitToC(response);
sendMessage(user, `Fahrenheit? 🥺 BTW, most of the world would say ${celcius}℃`);
}
return celcius;
}
exports.notifyEveryone = (req, res) => {
//Pull team data from environment
teamData = JSON.parse(process.env[req.query.slack]);
slack = new WebClient(teamData.slackToken);
sheetId = teamData.sheetId;
authorize(JSON.parse(process.env.gsuiteCreds), getUsers);
res.sendStatus(200);
};
exports.auth = (req, res) => {
if (req.query.code) {
console.log(req.query);
const c = req.query.code;
axios.post("https://slack.com/api/oauth.v2.access", "code=" + c, {
auth: {
username: clientId,
password: clientSecret
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
console.log(response.data);
res.send(response.data);
});
} else {
res.redirect(301, "https://slack.com/oauth/authorize?client_id=" + clientId + "&scope=channels:read chat:write:bot users.profile:read users:read users:read.email&redirect_uri=&state=")
}
};
exports.slackAttack = (req, res) => {
if (req.get("X-Slack-Retry-Num")) {
res.sendStatus(200);
console.log('Caught a retry #' + req.get("X-Slack-Retry-Num"))
} else {
switch (req.body.type) {
case "url_verification":
res.send(req.body);
break;
case "event_callback":
//Pull team data from environment
teamData = JSON.parse(process.env[req.body.team_id]);
slack = new WebClient(teamData.slackToken);
sheetId = teamData.sheetId;
const e = req.body.event;
let amFlag = false;
res.sendStatus(200);
if (!e.bot_profile && e.channel_type == "im") {
if (e.text.split(" ")[1] == "AM") {
amFlag = true;
e.text = e.text.split(" ")[0];
}
if (!isFinite(String(e.text).trim() || NaN)) {
sendMessage(e.user, "That doesn't appear to be a number and I don't do small talk. Could you please try again?");
} else {
userTempC = convertResponse(e.user, e.text);
if (userTempC > 50) {
sendMessage(e.user, "Wow that's really hot 🔥! Are you sure that's right?");
} else if (userTempC >= 35 && userTempC < 37.5) {
authorize(JSON.parse(process.env.gsuiteCreds), writeTemp, {u: e.user, t: userTempC, a: amFlag});
sendMessage(e.user, readingStrings[Math.floor(Math.random() * readingStrings.length)]);
} else if (userTempC < 35) {
sendMessage(e.user, "Wow that's really cold ❄️! I think your thermal measuring device requires calibration. Try again?");
} else {
authorize(JSON.parse(process.env.gsuiteCreds), writeTemp, {u: e.user, t: userTempC, a: amFlag});
sendMessage(e.user, "Fever detected! Alerting team! 🥵");
sendMessage(teamData.emergencyUser, "FEVER DETECTED in " + e.user);
}
}
}
break;
default:
res.sendStatus(500);
console.log("Well I couldn't figure that one out.")
break;
}
}
};