View Single Post
Old 06-17-2009, 10:53 PM   #500 (permalink)
hayroob
Administrator
 
hayroob's Avatar
 
Join Date: Mar 2008
Location: Detroitish
Posts: 1,654
I've got some working python that will run in the background and check for tweets from a particular user to another particular user and then based on that criteria forward the message to a push notification.

Code:
from twitter import *
from xml.dom.minidom import parse, parseString
from ConfigParser import SafeConfigParser
import socket, ssl, json, struct
import urllib, time, sys, os
import pickle

# Export your "Apple Development Push Services" certificate from your Keychain (important: select it from the "My Certificates" category in the sidebar). Export the certificate as a "Personal Information Exchange (.p12) file. You shouldn't give the exported file a password (well you could but YMMV).
# Convert the .p12 file you just exported into a pem file:
# openssl pkcs12 -in certificates.p12 -out dist_cert.pem -nodes -clcerts

# The first time you launch this or if your d.pkl file is deleted/corrupted use the --prime switch to make sure you don't send old notifications

def getTweets(d):
	credentials = loadConfig(os.path.join(os.getcwd(), 'config'))
	twitter = Twitter(credentials.get('user'), credentials.get('pass')) # create a file called config with your username and password for the account receiving the tweet
	tweets = twitter.replies()
	t = []
	for tweet in tweets:
		x = tweet.get('user')
		if x.get('screen_name') == 'someusername': #this is the user name the tweet is coming from
			time = tweet.get('created_at')
			body = tweet.get('text')
			if not(time in d):
				print 'Send notification:'
				send(body[15:])
				d[time] = body
	return d


def prime(d):
	credentials = loadConfig(os.path.join(os.getcwd(), 'config'))
	twitter = Twitter(credentials.get('user'), credentials.get('pass'))
	tweets = twitter.replies()
	t = []
	for tweet in tweets:
		x = tweet.get('user')
		if x.get('screen_name') == 'hayroob':
			time = tweet.get('created_at')
			body = tweet.get('text')
			if not(time in d):
				d[time] = body
	return d


def send(Message):
	print Message
	url = 'http://yourfeed.com/feed'
	data = ''
	filehandle = urllib.urlopen(url, data)
	
	time.sleep(5)
	xml = filehandle.read()
	xmldoc = parseString(xml)
	nodeArray = xmldoc.getElementsByTagName('deviceToken')
	tokens = []
	for node in nodeArray:
		try:
			deviceToken = node.firstChild.toxml()
			tokens.append(deviceToken)
		except:
			continue
	
	sound = 'keithandthegirl.com.caf' #sound in your resources file
	
	for deviceToken in tokens:
		thePayLoad = {
			'aps': {
				'alert':Message,
				'sound':sound,
				'badge':1,
				},
			}
		
		theCertfile = 'dist_cert.pem'
		theHost = ('gateway.push.apple.com', 2195)
		
		data = json.dumps(thePayLoad)
		deviceToken = deviceToken.replace(' ','').decode('hex')
		
		theFormat = '!BH32sH%ds' % len(data)
		theNotification = struct.pack(theFormat, 0, 32, deviceToken, len(data), data)
		
		ssl_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), certfile=theCertfile)
		ssl_sock.connect(theHost)
		ssl_sock.write(theNotification)
		ssl_sock.close()


def loadConfig(filename):
	options = ({})
	if os.path.exists(filename):
		cp = SafeConfigParser()
		cp.read([filename])
		if cp.has_option('twitter', 'user'):
			options['user'] = cp.get('twitter', 'user')
		if cp.has_option('twitter', 'pass'):
			options['pass'] = cp.get('twitter', 'pass')
	return options


try:
	pkl_file = open('d.pkl', 'rb')
	d = pickle.load(pkl_file)
except:
	d = ({})

for arg in sys.argv:
	if arg.startswith('--prime'):
		prime(d)
		print 'Primed'

try:
	doAction = lambda : getTweets(d)
	while True:
		d = doAction()
		time.sleep(180)
except KeyboardInterrupt:
	output = open('d.pkl', 'wb')
	pickle.dump(d, output)
	output.close()
	print >>sys.stderr, '\n[Keyboard Interrupt]'
	pass
and the config file:

Code:
[twitter]
user : yourusername
pass : yourpassword
You'll need python 2.6 and http://mike.verdone.ca/twitter/

Last edited by hayroob; 06-17-2009 at 11:28 PM.
(Offline)   Reply With Quote