Last active
November 21, 2015 18:57
-
-
Save nickdandakis/da4af4dde558e0d28f8e to your computer and use it in GitHub Desktop.
UrbanDictionary Word Of The Day + Giphy GIF
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
// npm install request and cheerio, if these aren't working | |
var request = require('request'); | |
var cheerio = require('cheerio'); | |
var sendGIFToClient = function(url) { | |
// TODO | |
console.log(url); | |
}; | |
var sendWordToClient = function(word, definition, example) { | |
// TODO | |
console.log(word); | |
console.log(definition); | |
console.log(example); | |
}; | |
// Recursively iterate through terms and attempt to get a GIF from Giphy for that term | |
var getGIF = function(terms, index) { | |
if(index > terms.length - 1) { | |
console.log('No GIFs found for all possible search terms'); | |
} else { | |
var giphyURL = 'http://api.giphy.com/v1/gifs/search?q=' + encodeURIComponent(terms[index]) + '&api_key=dc6zaTOxFJmzC'; | |
request(giphyURL, function(error, response, body) { | |
var giphyResponse = JSON.parse(body); | |
if(!error) { | |
if(giphyResponse.data.length > 0) { | |
console.log('GIF found for ' + terms[index]); | |
var GIF = giphyResponse.data[0].images.original.url; | |
sendGIFToClient(GIF); | |
} else { | |
console.log('No GIFs found for ' + terms[index]); | |
getGIF(terms, ++index); | |
} | |
} else { | |
console.log(error); | |
} | |
}); | |
} | |
}; | |
// Grab the word of the day from UrbanDictionary | |
request('http://urbandictionary.com', function(error, response, body) { | |
if(!error) { | |
var $ = cheerio.load(body); | |
var wordEndpoint = $('.word').attr('href').replace(/\.php/, ''); | |
var wordURL = 'http://api.urbandictionary.com/v0' + wordEndpoint; | |
// Get all data associated with word of the day | |
request(wordURL, function(error, response, body) { | |
if(!error) { | |
var wordResponse = JSON.parse(body); | |
var word = wordResponse.list[0].word; | |
var wordDefinition = wordResponse.list[0].definition; | |
var wordExample = wordResponse.list[0].example; | |
var wordTags = wordResponse.tags; | |
// Construct a list of possible search terms to search Giphy for | |
// TODO: add in words with high frequency from the definition and examples? | |
var possibleSearchTerms = []; | |
possibleSearchTerms.push(word); | |
possibleSearchTerms = possibleSearchTerms.concat(wordTags); | |
possibleSearchTerms = possibleSearchTerms.concat(word.split(' ')); | |
sendWordToClient(word, wordDefinition, wordExample); | |
getGIF(possibleSearchTerms, 0); | |
} else { | |
console.log(error); | |
} | |
}); | |
} else { | |
console.log(error); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment