Yak Shaving

just me

Archive for the ‘twitter’ Category

Twitter Bot

without comments

While bored I wrote the following python twitter bot. It gets the rss feed from uk hot deals and then tweets the deals. Its pretty basic as it just checks the top item on the list instead of doing dates and times. It uses python-twitter-0.5.

The script is run by cron currently every minute.

#!/usr/bin/env python

import twitter
import urllib
from xml.dom import minidom
import simplejson

api = twitter.Api(username='username', password='passwd')

def shorten(param):
	""" Using bit.ly to shorten the url """
	url = param
	request = "http://api.bit.ly/shorten?version=2.0.1&longUrl="
	request += url
	request += "&login=username&apiKey=APIKEY"

	# fire off request for bit.ly
	sock = urllib.urlopen(request)
	json = sock.read()
	sock.close()

	# get the json
	json = simplejson.loads(json)
	return json['results'][url]['shortUrl']

# get the rss feed
sock = urllib.urlopen("http://www.hotukdeals.com/rss/hot")
rss = sock.read()
sock.close()  

# parse the rss into ready xml
xmldoc = minidom.parseString(rss)

# eextract our results
items = xmldoc.getElementsByTagName('item')
result = items[0].getElementsByTagName('title')[0].childNodes[0].nodeValue
result += " " +shorten(items[0].getElementsByTagName('link')[0].childNodes[0].nodeValue)

# open the temp file and read in old value
f = open('/tmp/workfile', 'w+')
existing = f.read()
existing = existing.replace('\n', '')

unicode_result = unicode(result)

# if the new value from the top of the rss feed is different tweet and record it
if unicode_result.encode('utf-8') != existing:
	unicode_string = unicode(result)
	f.write(unicode_string.encode('utf-8'))
	if len(result) > 0:
		api.PostUpdate(result)

f.close()

Written by channam

February 23rd, 2009 at 2:33 pm

Posted in bit.ly,python,twitter