diff --git a/drawings.json b/drawings.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/drawings.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/src/drawing-handlers.js b/src/drawing-handlers.js new file mode 100644 index 0000000..985d51b --- /dev/null +++ b/src/drawing-handlers.js @@ -0,0 +1,28 @@ +const fs = require("fs"); +const { promisify } = require("util"); + +async function addImageToList(drawingInfo) { + // throws error if file doesn't exist + const drawingsListJson = await promisify(fs.readFile)( + "./drawings.json", + "utf-8" + ); + + // throws error if file is blank + let drawingsList = JSON.parse(drawingsListJson); + + // just in case drawings.json has some other type at the root of structure + if (!Array.isArray(drawingsList)) { + drawingsList = []; + } + + drawingsList.push(drawingInfo); + + const newJson = JSON.stringify(drawingsList, null, 2); + + return promisify(fs.writeFile)("./drawings.json", newJson); +} + +module.exports = { + addImageToList +}; diff --git a/src/rtm-handlers.js b/src/rtm-handlers.js index 8ed22ae..7a26e25 100644 --- a/src/rtm-handlers.js +++ b/src/rtm-handlers.js @@ -1,5 +1,6 @@ const fs = require("fs"); const prompts = require("./prompt-handlers"); +const drawings = require("./drawing-handlers"); const RtmClient = require("@slack/client").RtmClient; const CLIENT_EVENTS = require("@slack/client").CLIENT_EVENTS; const RTM_EVENTS = require("@slack/client").RTM_EVENTS; @@ -77,7 +78,9 @@ function onReceiveMessage(env) { responseText = "Hi I'm Penny; I can do the following if you `@` mention me!\n"; responseText += "`@penny_bot give prompt` \n"; - responseText += "`@penny_bot, submit prompt ''`"; + responseText += "`@penny_bot, submit prompt ''`\n "; + responseText += + "You can also DM me your drawings as attachments with the comment `submit drawing`"; // Channel to respond in message.channel == "C63GFH05V" @@ -85,9 +88,37 @@ function onReceiveMessage(env) { : env.rtm.sendMessage(responseText, message.channel); } } + + /** + * DMs to penny with attachments might not include penny's user id in the + * message, so this check happens outside the other if statement + */ + if (checkMessage("submit drawing") && message.channel === "D63S3TAM7") { + handleDrawingSubmission(env, message); + } }); } +const validFileTypes = ["jpg", "png", "gif"]; + +function handleDrawingSubmission(env, message) { + if (!message.file) { + env.rtm.sendMessage("Where is drawing?", message.channel); + } else if (message.file && !validFileTypes.includes(message.file.filetype)) { + env.rtm.sendMessage( + "I don't think you attached a drawing. Make sure you send me a .png, .jpg, or .gif", + message.channel + ); + } else { + env.rtm.sendMessage("Got drawing!", message.channel); + + drawings + .addImageToList(message.file) + .then(result => console.log("saved image info", result)) + .catch(error => console.error("error", error)); + } +} + function startRtm(env) { env.rtm.start(); }