Created
November 18, 2016 06:05
-
-
Save agrimrules/5189e572cb5fe401ecf954f461a48edf to your computer and use it in GitHub Desktop.
gifsuggest.js
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
`use strict`; | |
var express = require('express'), | |
async = require('async'), | |
lodash = require('lodash'), | |
bodyParser = require('body-parser'), | |
awsServerless =require('aws-serverless-express/middleware'), | |
request = require('request-promise'); | |
var app = express(); | |
app.listen(3000,()=>{ | |
console.log('listening on 3000') //Not required but useful when you want to debug locally. | |
}); | |
app.use(bodyParser.urlencoded({extended: true})); //Since Slack sends all its data as x-www-form-urlencoded | |
app.use(awsServerless.eventContext()); //Binding the express lifecycle to the aws lambda lifecycle. | |
var options = { | |
method:'GET', | |
url: 'http://api.giphy.com/v1/gifs/search', | |
qs: { api_key: 'dc6zaTOxFJmzC', limit: 15 } //This is the public api key provided by giphy to everyone. | |
}; | |
app.post('/gifs',(req,res) => { | |
console.log(req.body); | |
options.qs.q = req.body.text; | |
fetchgifs(req.body.response_url, res); | |
}); | |
var fetchgifs = function(url, res){ | |
return request(options,(err, response, body)=>{ | |
if(err) throw new Error(error); | |
var data = lodash.dropRight(lodash.chain(JSON.parse(body).data) | |
.map(x => x.images.downsized.url) | |
.shuffle() | |
.value(),10); //Randomly chooses 10/15 images from the response. | |
delayed(data,url, res); | |
}); | |
}; | |
var delayed = function (gifs,url, res) { | |
var body = { | |
"text":"suggested gifs for "+options.qs.q, | |
"attachments": lodash.map(gifs,(d)=>{ | |
return {"image_url":d} | |
}), | |
}; | |
request({ | |
method:'POST', | |
url:url, | |
body: JSON.stringify(body), | |
},(err, res, body)=>{ | |
console.log(body); | |
}).then(()=>{ | |
console.log('*****sending response *******'); | |
res.send({"text":"Looking for gifs about "+options.qs.q}); | |
}); | |
}; | |
module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment