Skip to content

Instantly share code, notes, and snippets.

@randysecrist
Created October 24, 2011 19:01
Show Gist options
  • Save randysecrist/1309831 to your computer and use it in GitHub Desktop.
Save randysecrist/1309831 to your computer and use it in GitHub Desktop.
simple twitter feed in python
#!/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? ')
print
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]'
print
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