Skip to content

Commit

Permalink
Fixed issue while sending notification to all users to log temperature
Browse files Browse the repository at this point in the history
  • Loading branch information
Aakash Thaiwat authored and Aakash Thaiwat committed May 11, 2020
1 parent adbf495 commit 3412beb
Showing 1 changed file with 46 additions and 42 deletions.
88 changes: 46 additions & 42 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const clientSecret = process.env.clientSecret;

//Set APIs and libraries up
const { WebClient } = require("@slack/web-api");
const {google} = require('googleapis');
const { google } = require('googleapis');
const { DateTime } = require('luxon');
const axios = require('axios');

Expand All @@ -20,7 +20,7 @@ const temperatureStrings = [
"🌡 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! 🎶",
"🌡 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? 🥺"
];

Expand Down Expand Up @@ -49,16 +49,16 @@ let sheetId = "";
let slack = "";

function authorize(credentials, callback, params) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
client_id, client_secret, redirect_uris[0]);

oAuth2Client.setCredentials(JSON.parse(process.env.gsuiteToken));
callback(oAuth2Client, params);
callback(oAuth2Client, params);
}

function writeUsers(auth, params) {
const sheets = google.sheets({version: 'v4', auth});
const sheets = google.sheets({ version: 'v4', auth });
let values = [];

console.log(params.users);
Expand All @@ -72,7 +72,7 @@ function writeUsers(auth, params) {
values.push([]);
}
});

const req = {
spreadsheetId: sheetId,
range: 'Users!B2:D' + params.rownum,
Expand All @@ -83,18 +83,18 @@ function writeUsers(auth, params) {
values: values
}
}

sheets.spreadsheets.values.update(req).then((res) => console.log(res.data));
console.log(sendList);
sendList.forEach(u => {
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 => {
if (!row[1]) {
return slack.users.lookupByEmail({ email: row[0] }).catch(e => {
console.log(e + ": " + row[0]);
return {};
});
Expand All @@ -105,31 +105,31 @@ const resolveEmailsAndUpdateSheet = async (params) => {
});

const complete = await Promise.all(resolvedRows);
writeUsers(params.auth, {rownum: params.rows.length+1, users: complete});
}
writeUsers(params.auth, { rownum: params.rows.length + 1, users: complete });
}

function getUsers(auth, params) {
const sheets = google.sheets({version: 'v4', auth});
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);
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});
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});
console.log(params);
const sheets = google.sheets({ version: 'v4', auth });

const req = {
spreadsheetId: sheetId,
Expand All @@ -139,16 +139,16 @@ function writeTemp(auth, params) {
majorDimension: "ROWS",
range: 'Readings!A2:E',
values: [[
params.u,
params.u,
'=VLOOKUP(INDIRECT("A"&row()),Users!B:C,2, FALSE)',
params.t,
DateTime.local().setZone("Asia/Singapore").toISODate(),
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));
}

Expand All @@ -160,12 +160,16 @@ function sendMessage(u, m) {
const result = await slack.chat.postMessage({
text: m,
channel: u,
}).catch(e => {
}).catch(e => {
console.log(e);
});

// The result contains an identifier for the message, `ts`.
console.log(`Successfully send message ${result.ts} in conversation ${u}`);
if (result && result.ok) {
console.log(`Successfully send message ${result.ts} in conversation ${u}`);
} else {
console.log(`Failed to send message in conversation ${u}`);
}
})();
}

Expand All @@ -175,7 +179,7 @@ function kelvinToC(kelvin) {
}

function fahrenheitToC(farnheit) {
celcius = (farnheit - 32) * (5/9);
celcius = (farnheit - 32) * (5 / 9);
return celcius;
}

Expand All @@ -185,11 +189,11 @@ function convertResponse(user, response) {
celcius = response;
if (response > 200) {
// Assuming Kelvin
celcius = kelvinToC(response);
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);
celcius = fahrenheitToC(response);
sendMessage(user, `Fahrenheit? 🥺 BTW, most of the world would say ${celcius}℃`);
}
return celcius;
Expand All @@ -201,7 +205,7 @@ exports.notifyEveryone = (req, res) => {

slack = new WebClient(teamData.slackToken);
sheetId = teamData.sheetId;

authorize(JSON.parse(process.env.gsuiteCreds), getUsers);
res.sendStatus(200);
};
Expand All @@ -219,13 +223,13 @@ exports.auth = (req, res) => {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
}).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=")
}
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) => {
Expand All @@ -237,40 +241,40 @@ exports.slackAttack = (req, res) => {
case "url_verification":
res.send(req.body);
break;
case "event_callback":
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);
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)]);
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});
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);
Expand Down

0 comments on commit 3412beb

Please sign in to comment.