View Single Post
Old 07-07-2009, 04:22 PM   #610 (permalink)
hayroob
Administrator
 
hayroob's Avatar
 
Join Date: Mar 2008
Location: Detroitish
Posts: 1,654
I may have already posted this, but I am too lazy to go back and look and I have tuned it a little. It works with the PHP token server I posted a while back. You export your cert as a .p12 and convert to pem, I've posted some stuff about that somewhere in this thread.

Code:
#----------------------------------------------------------------------------
#	Name: TwitterNotifications.py
#	Author: Doug Russell
#	Last Modified: 07-07-09
#	Created with Python 2.6
#	Description: Allows for APNS pushes from twitter
#	Usage: Set up a twitter account for receiving the @ messages and then
#	add that to the config file, then add your user that the message will
#	come from where it is marked below. The first time you launch add the 
#	--prime flag so that old messages won't get resent.
#	Require: Python Twitter Tools
#----------------------------------------------------------------------------
#	Copyright (C) 2008 Doug Russell
#	
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

def getTweets(d):
	credentials = loadConfig(os.path.join(os.getcwd(), 'config'))
	try:
		twitter = Twitter(credentials.get('user'), credentials.get('pass'))
		tweets = twitter.replies()
	except:
		return d
	t = []
	for tweet in tweets:
		x = tweet.get('user')
		if x.get('screen_name').lower() == 'YOURSENDINGUSER': # add in your user here
			time = tweet.get('created_at')
			body = tweet.get('text')
			if not(time in d):
				print 'Send notification:'
				send(body[9:])
				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').lower() == 'YOURSENDINGUSER':
			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://YOURWEBSITE.com/tokenLog.php'
	data = 'userid=YOURUSERID&password=YOURPASSWORD&submit=Submit'
	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'
	
	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:
		print time.strftime("%a, %d %b %Y %H:%M:%S")
		d = doAction()
		time.sleep(40)
except KeyboardInterrupt:
	output = open('d.pkl', 'wb')
	pickle.dump(d, output)
	output.close()
	print >>sys.stderr, '\n[Keyboard Interrupt]'
	pass
config file
Quote:
[twitter]
user : YOURRECEIVINGUSER
pass : YOURPASSWORD
(Offline)   Reply With Quote