Skip to content

Commit

Permalink
Added functionality for notifying everyone as well as capturing enter…
Browse files Browse the repository at this point in the history
…ed temperature. This is MVB.
  • Loading branch information
Vishal Parpia committed Mar 30, 2020
1 parent be24aca commit d688c48
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 31 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,5 @@ dist

# Credentials
credentials.json
token.json
token.json
.env.yaml
107 changes: 78 additions & 29 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,44 @@ const { WebClient } = require("@slack/web-api");
const token = process.env.slackToken;
const botId = process.env.slackBot;
const slack = new WebClient(token);
const { DateTime } = require('luxon');

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
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 celcius this one time.",
"🌡 Greetings human, for your own safety please reveal your current temperature",
"🌡 Sorry, my thermal camera is malfunctioning, please input your 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 🥶"
];

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 🤒"
];

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
let sendList = [];

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]);

// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client, params);
});
oAuth2Client.setCredentials(JSON.parse(process.env.gsuiteToken));
callback(oAuth2Client, params);
}

function writeUsers(auth, params) {
Expand All @@ -35,7 +50,9 @@ function writeUsers(auth, params) {

params.users.forEach(u => {
if (Object.keys(u).length) {
values.push([u.user.id, u.user.real_name, '@' + u.user.name]);
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([]);
}
Expand All @@ -51,19 +68,23 @@ function writeUsers(auth, params) {
values: values
}
}

console.log(params.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]) {
if (!row[1]) {
return slack.users.lookupByEmail({email: row[0]}).catch(e => {
console.log(e + ": " + row[0]);
return {};
});
} else {
sendList.push(row[1]);
return {}
}
});
Expand All @@ -89,30 +110,50 @@ function getUsers(auth, params) {
});
}

function sendMessage(u, c, m) {
function writeTemp(auth, params) {
const sheets = google.sheets({version: 'v4', auth});

//Date related garbage
new Date()

const req = {
spreadsheetId: '1dFmuyedPEKJz_BR9aVKOsd5NOm0W5g_H0HE91b-x29c',
range: 'Readings!A2:E',
valueInputOption: 'USER_ENTERED',
resource: {
majorDimension: "ROWS",
range: 'Readings!A2:E',
values: [[
params.u,
"=LOOKUP(A2,Users!B:B,Users!C:C)",
params.t,
DateTime.local().setZone("Asia/Singapore").toISODate(),
(DateTime.local().setZone("Asia/Singapore").hour >= 12) ? "PM" : "AM"
]]
}
}

sheets.spreadsheets.values.append(req).then((res) => console.log(res.data));
}

function sendMessage(u, m) {
(async () => {
// 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: c,
channel: u,
});

// The result contains an identifier for the message, `ts`.
console.log(`Successfully send message ${result.ts} in conversation ${c}`);
console.log(`Successfully send message ${result.ts} in conversation ${u}`);
})();
}

exports.notifyUsers = (req, res) => {
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), getUsers);
});

res.sendStatus(200);
}
exports.notifyEveryone = (req, res) => {
authorize(JSON.parse(process.env.gsuiteCreds), getUsers);
res.sendStatus(200);
};

exports.slackAttack = (req, res) => {
switch (req.body.type) {
Expand All @@ -123,8 +164,16 @@ exports.slackAttack = (req, res) => {
const e = req.body.event
res.sendStatus(200);
if (!e.bot_profile && e.channel_type == "im") {
console.log(req.body);
sendMessage(e.user, e.channel, "I hear you coming in from the other side!");
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 {
if (e.text > 50) {
sendMessage(e.user, "Wow that's really hot 🔥! Are you sure that's in *degrees celcius*?");
} else {
authorize(JSON.parse(process.env.gsuiteCreds), writeTemp, {u: e.user, t: e.text});
sendMessage(e.user, readingStrings[Math.floor(Math.random() * readingStrings.length)]);
}
}
}
break;
default:
Expand Down
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"dependencies": {
"@slack/events-api": "^2.3.2",
"@slack/web-api": "^5.8.0",
"googleapis": "^39.2.0"
"googleapis": "^39.2.0",
"luxon": "^1.22.2"
},
"devDependencies": {
"@google-cloud/functions-framework": "^1.5.0"
Expand Down

0 comments on commit d688c48

Please sign in to comment.