Skip to content

Instantly share code, notes, and snippets.

@yongfook
Last active May 20, 2020 05:05
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 yongfook/a857e9bfaf5b3f29042406da0304d965 to your computer and use it in GitHub Desktop.
Save yongfook/a857e9bfaf5b3f29042406da0304d965 to your computer and use it in GitHub Desktop.
A simple file I have in my static site generator root that loops through all pages and generates opengraph images using Bannerbear
require 'httparty'
require 'open-uri'
namespace :bannerbear do
task :generate do
puts "Starting json request"
response = HTTParty.get(ENV['LOCAL_BB_SITE_ALL_POSTS'])
begin
json = JSON.parse response.body
puts "Number of pages: #{json.size}"
json.each_with_index do |page,i|
puts "#{i} ---------------------------------------"
puts "Checking file exists for"
path = './source/images/opengraph/' + page['image_url']
puts path
if !File.file?(path)
puts "File doesn't exists, lets create!"
general_template_id = ENV['BB_SITE_GENERAL_OG_TEMPLATE']
blog_template_id = ENV['BB_SITE_BLOG_OG_TEMPLATE']
template = general_template_id
mods = [
{
:name => "title",
:text => page['title']
}
]
if page['blog_date']
template = blog_template_id
mods = [
{
:name => "title",
:text => page['title']
},
{
:name => "date",
:text => page['blog_date']
}
]
end
payload = {
:template => template,
:modifications => mods,
}
puts "Creating Bannerbear API request"
puts payload
response = HTTParty.post("https://api.bannerbear.com/v2/images", {
body: payload,
headers: {"Authorization" => "Bearer #{ENV['BANNERBEAR_SOCIAL_MEDIA_PROJECT_API_KEY']}"}
})
image_json = JSON.parse response.body
counter = 1
#poll for image to complete
5.times do |attempt|
puts "Attempt #{attempt}"
counter = counter+1
response = HTTParty.get(image_json['self'], {
headers: {"Authorization" => "Bearer #{ENV['BANNERBEAR_SOCIAL_MEDIA_PROJECT_API_KEY']}"}
})
image_json = JSON.parse response.body
if image_json['image_url_png']
puts "Image generated!"
puts image_json['image_url_png']
download = open(image_json['image_url_png'])
IO.copy_stream(download, path)
break
end
sleep 1
end
if !image_json['image_url_png']
puts "Failed to generate image in 5 attempts"
end
end
puts "Moving to next page..."
end
rescue => e
puts "Rescued #{e.inspect}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment