Wednesday, December 13, 2006

Using Ruby to post articles to Blogger

I'm learning Ruby and so I think I may write some Ruby code to post articles to Blogger.  After studying the Google Blogger API, I wrap the API into Ruby functions:

Authentication


Posting article to Blogger requires authentication using HTTPS POST request:

# Login to Google
# @email - your google email address
# @passwd - your login password
# returns true if login successful, otherwise false
# @auth holds the returned authentication keys

def login
h = Net::HTTP.new 'www.google.com', 443
h.use_ssl = true
resp, data = h.post '/accounts/ClientLogin',
"Email=#{@email}&Passwd=#{@passwd}&service=blogger",
{ 'Content-Type' => 'application/x-www-form-urlencoded' }
return false if resp.code != '200'
# save the authentication keys
@auth = {}
data.each do |s|
key, val = s.chomp.split('=')
@auth[key] = val
end
true
end


Posting


After successfully authenticated, you can now post articles:

# Post an article to Blogger:
# title - title of the article
# body - content of the article
# labels - array of labels for the article, e.g. [ 'Ruby', 'Programming' ]
# @userid - your Blogger ID

def post title, body, labels
headers = { 'Authorization' => "GoogleLogin auth=#{@auth['Auth']}",
'Content-Type' => 'application/atom+xml' }
data = "<?xml version='1.0'?>"
data << "<entry xmlns='http://www.w3.org/2005/Atom'>"
data << "<title type='text'>#{title}</title>"
data << "<content type='xhtml'>#{body}</content>"
labels.each do |lbl|
data << "<category scheme='http://www.blogger.com/atom/ns#' term='#{lbl}'></category>"
end
data << "</entry>"
h = Net::HTTP.new "#{@userid}.blogspot.com"
resp, data = h.post '/feeds/posts/default', data, headers
end

This function is very primitive and doesn't handle HTML tags inside the
body that may cause problem, but it shows the possibility of posting
content using Ruby.

No comments: