Thursday, 11 February 2010

Google Buzz: How to publish to Twitter automatically

At present, Google Buzz has the ability to import, index and display your Tweets. One feature that is notably missing, however, is the ability to tweet from Buzz. You can't export Google Buzz to Twitter. At least, not officially.

I've written a python script to grab your Google Buzz feed (as detailed in the Buzz API), and automatically post your Buzz-es to Twitter. It includes a link back to the original Buzz URL (shortened with Bit.ly) It also uses a local sqlite database to store previous posts, and print bit.ly statistics for your published links.

You'll need to have python installed, and the following modules:
python-twitter
python-bitly
python-sqlite
feedparser
You'll also need a free account at Twitter and Bit.ly, and a Bit.ly API key.

Download the python source code from Google Code, or copy the text below. Please let me know if you found this useful, or have any improvements or modifications to suggest.


Update: To run this script every minute, add the following line to your crontab:
* * * * * /path/to/buzz-twitter-bot.py
This will update Twitter with your Google Buzz posts at least once per minute.

Code:

#!/usr/bin/python
from time import strftime
import sqlite3
import sys
import re

import twitter     #http://code.google.com/p/python-twitter/
import bitly       #http://code.google.com/p/python-bitly/
import feedparser  #available at feedparser.org


DATABASE = "tweets.sqlite"

BITLY_LOGIN = "username"
BITLY_API_KEY = "insert_your_key"

TWITTER_USER = "username"
TWITTER_PASSWORD = "secret"

def print_stats():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
c = conn.cursor()

b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)

c.execute('SELECT title, url, short_url from RSSContent')
all_links = c.fetchall()

for row in all_links:

short_url = row['short_url']

if short_url is None:
short_url = b.shorten(row['url'])
c.execute('UPDATE RSSContent SET `short_url`=? WHERE `url`=?',(short_url,row['url']))


stats = b.stats(short_url)
print "%s - User clicks %s, total clicks: %s" % (row['title'], stats.user_clicks,stats.total_clicks)

conn.commit()

def tweet_rss(url):
print "Opening database...."
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
c = conn.cursor()
print "Database opened."

#create the table if it doesn't exist
c.execute('CREATE TABLE IF NOT EXISTS RSSContent (`url`, `title`, `dateAdded`, `content`, `short_url`)')

print "Logging in to Twitter...."
api = twitter.Api(username=TWITTER_USER, password=TWITTER_PASSWORD)
print "Logging in to Bitly...."
b = bitly.Api(login=BITLY_LOGIN,apikey=BITLY_API_KEY)

print "Parsing feed...."
d = feedparser.parse(url)

for entry in d.entries:

#check for duplicates
c.execute('select * from RSSContent where url=?', (entry.link,))
if not c.fetchall():
print entry
#Get data from this entry
title = entry.title
content = entry.content[0].value
link = entry.link
updated = entry.updated
#Strip HTML from content
r = re.compile(r'<[^<]*?/?>')
content = r.sub('', content)

print "Found new item"
print "Title: "+title
print "Content: "+content
print "Link: "+link
tweet_text = "Buzz: %s" % content

#Shorten link
print "Shortening link...."
shortened_link = b.shorten(link)
print "Shortened link: "+shortened_link

#Add this entry to the database
t = (link, title, updated, content, shortened_link)
c.execute('insert into RSSContent (`url`, `title`,`dateAdded`, `content`, `short_url`) values (?,?,?,?,?)', t)
print "%s.. %s" % (tweet_text[:115], shortened_link)

#Post to twitter
print "Posting to twitter...."
api.PostUpdate("%s.. %s" % (tweet_text[:115], shortened_link))
print "Post complete."

conn.commit()

if __name__ == '__main__':
tweet_rss(sys.argv[1])
print "Listing stats...."
print_stats()

Special Thanks to Halotis for the RSS Twitter Bot, and love-python.blogspot.com for how to strip HTML tags.