Skip to content

Instantly share code, notes, and snippets.

@elpeo
Created September 6, 2012 21:56
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 elpeo/3660662 to your computer and use it in GitHub Desktop.
Save elpeo/3660662 to your computer and use it in GitHub Desktop.
Google+ to Twitter with Photo and Coordinates
#!/usr/bin/env ruby
require 'net/https'
require 'open-uri'
require 'time'
require 'tmpdir'
require 'rubygems'
require 'oauth'
require 'json/pure'
user_id = '(Your Google+ user ID)'
api_key = '(Your Google API key)'
def shorten( uri )
data = {'longUrl' => uri}
r = nil
begin
Net::HTTP.version_1_2
https = Net::HTTP.new( 'www.googleapis.com',443 )
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
store = OpenSSL::X509::Store.new
store.set_default_paths
https.cert_store = store
res = https.start do |http|
http.post( '/urlshortener/v1/url?key='+api_key, data.to_json, 'Content-Type' => 'application/json' )
end
if res && obj = JSON.parse( res.body ) then
r = obj['id']
end
rescue
end
r || uri
end
consumer_key = '(Your OAuth consumer key)'
consumer_secret = '(Your OAuth consumer secret)'
consumer = OAuth::Consumer.new( consumer_key, consumer_secret, :site => "http://twitter.com")
access_token = '(Your OAuth access token)'
access_token_secret = '(Your OAuth access token secret)'
token = OAuth::AccessToken.new( consumer, access_token, access_token_secret )
tmpfile = Dir.tmpdir+'/gplus2twitter'
obj = open( "https://www.googleapis.com/plus/v1/people/#{user_id}/activities/public?key=#{api_key}" ){|f| JSON.parse( f.read )} rescue nil
exit unless obj
if File.exist?( tmpfile ) then
prev = open( tmpfile ){|f| Time.parse( f.read )}
else
prev = Time.now - 600 # 10 minutes if first time
end
r = []
obj['items'].each do |item|
date = Time.at( Time.parse( item['published'] ).to_i )
if date > prev then
title = item['title']
link = item['url']
ellipsis = ''
tinyurl = shorten( link )
while title.jlength + ellipsis.length + 1 + tinyurl.length > 140 do
title.chop!
ellipsis = '...'
end
param = {'status' => "#{title}#{ellipsis} #{tinyurl}"}
if geocode = item['geocode'] then
lat, long = geocode.split
param['lat'] = lat
param['long'] = long
end
if object = item['object'] then
if attachments = object['attachments'] then
if attachments0 = attachments.first then
if fullImage = attachments0['fullImage'] then
url = fullImage['url']
param['media'] = open( url ){|f| f.read}
end
end
end
end
r << [param, date]
end
end
r.sort_by{|i| i.last}.each do |param, date|
path = param.include?( 'media' ) ? 'https://upload.twitter.com/1/statuses/update_with_media.json' : 'http://api.twitter.com/1/statuses/update.json'
res = token.post( path, param )
break if res.code != '200'
open( tmpfile, "w" ){|f| f.print date.to_s}
end
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment