Skip to content

Instantly share code, notes, and snippets.

@soramugi
Last active October 31, 2017 22:21
Show Gist options
  • Save soramugi/2b259a2bcf37fcdad2d3 to your computer and use it in GitHub Desktop.
Save soramugi/2b259a2bcf37fcdad2d3 to your computer and use it in GitHub Desktop.
sitemapからurlをランダムに取得して画像付きツイート
FROM ruby:2.4
RUN gem install twitter nokogiri
COPY sitemap_to_tweet.rb /
CMD ["ruby", "sitemap_to_tweet.rb"]
require 'open-uri'
require 'twitter'
require 'kconv'
require 'zlib'
require 'nokogiri'
def generate_url_image_title
if ENV['sitemap'] =~ /\.gz/
xml = Nokogiri::XML Zlib::GzipReader.open(open(ENV['sitemap'])).read
else
xml = Nokogiri::XML open(ENV['sitemap'])
end
urls = xml.css('loc').map(&:text).select{|u| !(u =~ /tag/)}
url = urls.sample
if url =~ /\.xml/
xml = Nokogiri::XML open(url)
urls = xml.css('loc').map(&:text).select{|u| !(u =~ /tag/)}
url = urls.sample
end
html = open(url, "r:binary").read
page = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
image = title = nil
page.search('meta').each do |meta|
next unless meta.attribute('property')
image = meta.attribute('content').text if meta.attribute('property').text == 'og:image'
title = meta.attribute('content').text if meta.attribute('property').text == 'og:title'
end
[url, image, title]
end
def update(client)
url, image, title = generate_url_image_title
p url, image, title
client.update_with_media(title + ' ' + url, open(image))
#rescue TypeError
# 'TypeError'
#rescue => e
# p e
# sleep 60
# retry
end
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['consumer_key']
config.consumer_secret = ENV['consumer_secret']
config.access_token = ENV['access_token']
config.access_token_secret = ENV['access_token_secret']
end
p update(client)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment