Created
October 24, 2011 19:01
-
-
Save randysecrist/1309831 to your computer and use it in GitHub Desktop.
simple twitter feed in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import getpass | |
import urllib, urllib2 | |
import base64 | |
import json | |
import time | |
def fetch(uri, username='', password='', data=None): | |
headers = {} | |
if username and password: | |
headers['Authorization'] = 'Basic ' + base64.b64encode('%s:%s' % (username, | |
password)) | |
headers['User-Agent'] = 'BashoProServTwitterFeed' | |
req = urllib2.Request(uri, headers=headers) | |
if data: | |
req.add_data(urllib.urlencode(data)) | |
f = urllib2.urlopen(req) | |
return f | |
def main(): | |
username = raw_input('Twitter Username: ') | |
password = getpass.getpass('Twitter Password: ') | |
# track = raw_input('Tracking keyword? ') | |
try: | |
# f = fetch('http://stream.twitter.com/1/statuses/filter.json', username, | |
# password, {'track': track}) | |
f = fetch ('https://stream.twitter.com/1/statuses/sample.json', username, password) | |
# print 'Tracking... [Control + C to stop]' | |
while True: | |
line = f.readline() | |
if line: | |
status = json.loads(line) | |
try: | |
# user, time, message, message type (if it exists) | |
# what makes a user unique? what makes a message unique? (id, id_str) | |
# bucket by n minutes (30) | |
print '%s: %s' % (status['user']['screen_name'], status['id_str'] + "::" + status['created_at']) | |
except KeyError, e: | |
# something not handled yet | |
print '* FIXME *', line | |
else: | |
time.sleep(0.1) | |
except urllib2.HTTPError, e: | |
# Deal with unexpected disconnection (do this later) | |
raise e | |
except KeyboardInterrupt: | |
# End | |
f.close() | |
print 'Bye!' | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment