Created
April 27, 2017 13:40
-
-
Save BrandonMathis/be023de8c71dce343f10a6c4ea7b42da to your computer and use it in GitHub Desktop.
Watson Image Recognition Slack Bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config(); | |
const RtmClient = require('@slack/client').RtmClient; | |
const WebClient = require('@slack/client').WebClient; | |
const RTM_EVENTS = require('@slack/client').RTM_EVENTS; | |
const VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3'); | |
const fs = require('fs'); | |
const request = require('request'); | |
const path = require('path'); | |
const rtm = new RtmClient(process.env.SLACK_TOKEN); | |
const web = new WebClient(process.env.SLACK_TOKEN); | |
function recognize(image) { | |
const visual_recognition = new VisualRecognitionV3({ | |
api_key: process.env.WATSON_KEY, | |
version_date: '2016-05-19' | |
}); | |
const params = { | |
image_file: fs.createReadStream(image) | |
}; | |
return new Promise((resolve, reject) => { | |
visual_recognition.classify(params, function(err, res) { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(res); | |
} | |
}); | |
}); | |
} | |
rtm.on(RTM_EVENTS.MESSAGE, (message) => { | |
if (!message.text ) { return } | |
if (message.user === rtm.activeUserId) { return } | |
const permalink = message.text.replace('<', '').replace('>', ''); | |
if (permalink.match(/^http/) && permalink.match(/\.(png|gif|jpg|jpeg)$/)) { | |
const filename = "/tmp/" + Math.random().toString(36) + path.extname(permalink); | |
request({ | |
uri: permalink | |
}).pipe(fs.createWriteStream(filename)).on('close', () => { | |
recognize(filename) | |
.then((response) => { | |
const [primaryClass, ...secondaryClasses] = response.images[0].classifiers[0].classes; | |
const fields = secondaryClasses.map((aClass) => { | |
return { | |
short: true, | |
title: aClass['class'], | |
value: `${Math.round(aClass.score * 100)}%` | |
}; | |
}); | |
const slackResponse = { | |
as_user: true, | |
attachments: [ | |
{ | |
color: "#466BB0", | |
title: `Looks like you posted an image with a ${primaryClass['class']} in it.`, | |
text: "Other things I see:", | |
fields: fields | |
} | |
] | |
} | |
web.chat.postMessage(message.channel, '', slackResponse, (err) => { | |
console.log(err); | |
}); | |
}) | |
.catch((err) => { | |
console.log(err); | |
}); | |
}); | |
} | |
}); | |
rtm.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you please share the complete app? with packages.json and all files to use? thanks!