Last active
November 5, 2018 17:28
-
-
Save thorpj/da3ccd0357fadeebb74c3d895af83094 to your computer and use it in GitHub Desktop.
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
#!/usr/local/bin/ruby -w | |
# There doesn't seem to be an easy way to download a gif from giphy.com from the url type | |
# that people tend to use when posting in forums | |
# Usage: | |
# ruby giphy_dl.py <giphy url> | |
require 'giphy' | |
require 'open-uri' | |
def get_filename(url) | |
url_part = get_url_part(url) | |
File.basename(url_part) + ".gif" | |
end | |
def get_title(gif) | |
gif.instance_variable_get("@hash")["title"] | |
end | |
def get_image_url(gif) | |
gif.instance_variable_get("@hash")["images"]["downsized_large"]["url"] | |
end | |
def download_file(url, filename) | |
begin | |
puts "Downloading #{url}" | |
open(filename, "wb") do |file| | |
file << open(url).read | |
end | |
puts "Saved to #{filename}" | |
rescue Exception | |
puts "Failed to download #{url} as #{filename}" | |
end | |
end | |
def download_gif(url) | |
gif_id = url.sub("https://giphy.com/gifs/", "") | |
if gif_id.include? '-' | |
gif_id = (url.split("-"))[-1] | |
end | |
gif = Giphy.gif_by_id(gif_id) | |
title = get_title(gif) | |
image_url = get_image_url(gif) | |
download_file(image_url, "#{title}.gif") | |
end | |
if ARGV[0].nil? | |
puts "No url given" | |
else | |
download_gif(ARGV[0]) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment