From d688c48b1fd30c34d46aa9d46860acc87abe3de2 Mon Sep 17 00:00:00 2001 From: Vishal Parpia Date: Mon, 30 Mar 2020 16:55:21 +0800 Subject: [PATCH] Added functionality for notifying everyone as well as capturing entered temperature. This is MVB. --- .gitignore | 3 +- index.js | 107 +++++++++++++++++++++++++++++++++------------- package-lock.json | 5 +++ package.json | 3 +- 4 files changed, 87 insertions(+), 31 deletions(-) diff --git a/.gitignore b/.gitignore index d8fc980..cad50e4 100644 --- a/.gitignore +++ b/.gitignore @@ -105,4 +105,5 @@ dist # Credentials credentials.json -token.json \ No newline at end of file +token.json +.env.yaml \ No newline at end of file diff --git a/index.js b/index.js index f033a7e..6a599a4 100644 --- a/index.js +++ b/index.js @@ -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) { @@ -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([]); } @@ -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 {} } }); @@ -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) { @@ -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: diff --git a/package-lock.json b/package-lock.json index 2cd1c33..2eb3169 100644 --- a/package-lock.json +++ b/package-lock.json @@ -799,6 +799,11 @@ "yallist": "^3.0.2" } }, + "luxon": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-1.22.2.tgz", + "integrity": "sha512-vq6eSaOOw1fKob+JXwfu0e3/UFUT4G4HTFRJab7dch8J1OdOGW/vXqCiJsY7rm2In+5gKNYx0EtnYT0Tc5V4Qw==" + }, "media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", diff --git a/package.json b/package.json index 5155454..e4a0e04 100644 --- a/package.json +++ b/package.json @@ -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"