Last active
November 18, 2015 21:42
-
-
Save tjbrennan/b3fd718b76c5254be1a9 to your computer and use it in GitHub Desktop.
A cat facts bot for slack outgoing webhook
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
var http = require('http'); | |
var port = process.env.PORT || 8888; | |
var name = 'catfacts'; | |
function handle (req, res) { | |
res.setHeader('Content-Type', 'application/json'); | |
if (req.method === 'POST') { | |
var body = ''; | |
req.on('data', function(chunk) { | |
body += chunk; | |
}); | |
req.on('end', function() { | |
parse(body, function(error, result) { | |
var reply = {}; | |
if (error) { | |
reply.text = error; | |
} else { | |
reply.text = result; | |
} | |
res.end(JSON.stringify(reply)); | |
}); | |
}); | |
} else { | |
return res.end(); | |
} | |
} | |
function parse (text, callback) { | |
var result = ''; | |
var url = 'http://catfacts-api.appspot.com/api/facts'; | |
var body = ''; | |
// get cat fact | |
http.get(url, function(res) { | |
res.on('data', function(chunk) { | |
body += chunk; | |
}); | |
res.on('end', function() { | |
try { | |
body = JSON.parse(body); | |
if (body.success === 'true') { | |
result = body.facts[0]; | |
} | |
callback(null, result); | |
} catch (e) { | |
callback(e); | |
} | |
}); | |
}).on('error', function(error) { | |
callback(error); | |
}); | |
} | |
var server = http.createServer(handle); | |
server.listen(port, function() { | |
console.log(name + ' listening on port ' + port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment