Skip to content

Instantly share code, notes, and snippets.

@sunnygleason
Created January 28, 2017 17:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunnygleason/70d60bbba1cb93db5ffa6c4880a084b8 to your computer and use it in GitHub Desktop.
Save sunnygleason/70d60bbba1cb93db5ffa6c4880a084b8 to your computer and use it in GitHub Desktop.
PubNub GifChat BLOCK w/ Giphy
export default (request) => {
const xhr = require('xhr');
const query = require('codec/query_string');
const apiKey = 'YOUR_API_KEY';
const apiUrl = 'http://api.giphy.com/v1/gifs/search';
const regex = /\/gif\s\(([^.?]*)\)|\/gif\s\w+/g;
let textToAnalyze = request.message.text;
const matches = textToAnalyze.match(regex) || [];
const rets = [];
matches.forEach((match) => {
const queryParams = {
api_key: apiKey,
limit: 1,
rating: 'g',
q: match.split('/gif')[1]
};
let url = apiUrl + '?' + query.stringify(queryParams);
const a = xhr.fetch(url)
.then((r) => {
const body = JSON.parse(r.body || r);
return body.data[0].images.fixed_height.url;
})
.catch((e) => {
console.error(e);
});
rets.push(a);
});
return Promise.all(rets).then((values) => {
request.message.gifs = values;
request.message.text = textToAnalyze.replace(/\/gif\s\(([^.?]*)\)/g, '$1').replace(/\/gif\s/g, '');
return request.ok();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment