Created
April 16, 2010 08:12
-
-
Save mashiro/368155 to your computer and use it in GitHub Desktop.
User Stream
This file contains hidden or 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 | |
| # -*- encoding: utf-8 -*- | |
| import urllib2 | |
| import simplejson as json | |
| from datetime import datetime, timedelta, tzinfo | |
| from pit import Pit | |
| def parse_datetime(str): | |
| class FixedOffset(tzinfo): | |
| def __init__(self, offset, name): | |
| self.__offset = timedelta(minutes=offset) | |
| self.__name = name | |
| def utcoffset(self, dt): | |
| return self.__offset | |
| def tzname(self, dt): | |
| return self.__name | |
| def dst(self, dt): | |
| return timedelta(0) | |
| dt = datetime.strptime(str, '%a %b %d %H:%M:%S +0000 %Y') | |
| return dt.replace(tzinfo=FixedOffset(0, 'UTC')).astimezone(FixedOffset(60*9, 'JST')) | |
| def readline(response): | |
| buffer = '' | |
| while True: | |
| c = response.read(1) | |
| if c == '\n': | |
| return buffer.decode('utf-8') | |
| buffer += c | |
| def user_stream(username, password): | |
| password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() | |
| password_mgr.add_password(None, 'betastream.twitter.com', username, password) | |
| auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) | |
| opener = urllib2.build_opener(auth_handler) | |
| request = urllib2.Request('http://betastream.twitter.com/2b/user.json') | |
| response = opener.open(request) | |
| while True: | |
| try: | |
| buffer = readline(response).strip() | |
| if buffer != None: | |
| status = json.loads(buffer) | |
| if 'id' in status and 'user' in status: | |
| yield status | |
| except json.JSONDecodeError: | |
| pass | |
| def main(): | |
| config = Pit.get('user_stream', {'require': {'username': 'USERNAME', 'password': 'PASSWORD'}}) | |
| stream = user_stream(config['username'], config['password']) | |
| for status in stream: | |
| user = status['user'] | |
| created_at = parse_datetime(status['created_at']) | |
| print '[%s] %s: %s' % (created_at.strftime('%H:%M:%S'), user['screen_name'], status['text']) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment