Skip to content

Instantly share code, notes, and snippets.

@lishiyo
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lishiyo/9af0a7c4c4781c74f6d4 to your computer and use it in GitHub Desktop.
Save lishiyo/9af0a7c4c4781c74f6d4 to your computer and use it in GitHub Desktop.
Random Giphy Gif
# aText as "shell script" => ruby /path/to/this/script.rb <optional query>
# Returns random giphy gif from top 100 trending or by query
require 'net/http'
require 'json'
class GiphySearch
def initialize
@defaults = {
"api_key" => "dc6zaTOxFJmzC",
"limit" => "100",
# "ratings" => "pg-13"
}
end
# random pg-13 gif from top 100 trending
def get_trending
base = "http://api.giphy.com/v1/gifs/trending?"
url = base.concat(build_query_str(@defaults.clone))
gif_url = hit_api(url)
textify(gif_url)
end
# random pg-13 gif from query
def get_gif(query)
base = "http://api.giphy.com/v1/gifs/search?"
hash = @defaults.merge({ "q" => query })
url = base.concat(build_query_str(hash))
gif_url = hit_api(url)
textify(gif_url)
end
private
def hit_api(url) # returns single gif url
resp = Net::HTTP.get_response(URI.parse(url))
buffer = resp.body
result = JSON.parse(buffer)
data = result["data"]
rand_idx = rand(data.length)
data[rand_idx]["images"]["fixed_height"]["url"]
end
def textify(url)
'![LGTM]('.concat(url).concat(' "Looks good to me!")')
end
def build_query_str(hash)
arr = []
hash.each do |k, v|
arr << k.dup.concat("=").concat(v)
end
arr.join("&")
end
end
giphy = GiphySearch.new
if ARGV[0] # with search query
q = ARGV[0].dup
q = q.split(" ").join("+") if q.split(" ").length > 1
print giphy.get_gif(q)
else
print giphy.get_trending
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment