Created
January 6, 2010 17:43
-
-
Save swinton/270452 to your computer and use it in GitHub Desktop.
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 | |
""" | |
Have OS X read tweets aloud to you. | |
usage: | |
tweet_speak.py -u <user> [-p <password>] [-f <comma-seperated list of twitter user ids to follow> | -t <comma-seperated list of keywords to track>] | |
""" | |
# Inspired by this gist: http://gist.github.com/267147 | |
# Uses the Twitter streaming API, and TweetStream (http://bitbucket.org/runeh/tweetstream/src/) | |
import getopt, getpass, socket, subprocess, sys, tweetstream | |
# 'default_bufsize = 0' trick via http://blog.persistent.info/2009/08/twitter-streaming-api-from-python.html | |
socket._fileobject.default_bufsize = 0 | |
def say(s): | |
subprocess.call(['say', str(s)]) | |
def speak_tweets(user, passwd, follow=None, track=None): | |
# Ensure we have either a list of people to follow, or a list of keywords to track | |
keywords_or_followees = None | |
stream_class = None | |
if track == None and follow == None: | |
raise Exception('Error: You must specify either a list of people to follow, or a list of keywords to track.') | |
elif follow != None: | |
sys.stdout.write("Following %s...\n" % ", ".join(follow)) | |
keywords_or_followees = follow | |
stream_class = tweetstream.FollowStream | |
elif track != None: | |
sys.stdout.write("Tracking %s...\n" % ", ".join(track)) | |
keywords_or_followees = track | |
stream_class = tweetstream.TrackStream | |
try: | |
stream = stream_class(user, passwd, keywords_or_followees) | |
for tweet in stream: | |
say('%s says: %s' % (tweet['user']['name'], tweet['text'])) | |
except KeyboardInterrupt: | |
sys.exit(0) | |
def usage(): | |
sys.stdout.write("tweet_speak.py -u <user> [-p <password>] [-f <comma-seperated list of twitter user ids to follow> | -t <comma-seperated list of keywords to track>]\n") | |
def main(argv): | |
try: | |
opts, args = getopt.getopt(argv, "u:p:f:t:", ["user=", "password=", "follow=", "track="]) | |
except getopt.GetoptError: | |
usage() | |
sys.exit(2) | |
user = None | |
passwd = None | |
follow = None | |
track = None | |
for o, a in opts: | |
if o in ("-u", "--user"): | |
user = a | |
elif o in ("-p", "--password"): | |
passwd = a | |
elif o in ("-f", "--follow"): | |
follow = a.split(",") | |
elif o in ("-t", "--track"): | |
track = a.split(",") | |
if user == None or (follow == None and track == None): | |
usage() | |
sys.exit(2) | |
if passwd == None: | |
passwd = getpass.getpass() | |
speak_tweets(user, passwd, follow, track) | |
if __name__ == '__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment