c08920ba6f4cf8b0cd6be97e63bc7746894fe214
[rainbowstream.git] / rainbowstream / rainbow.py
1 """
2 Colorful user's timeline stream
3 """
4
5 from __future__ import print_function
6
7 import os, os.path, argparse
8
9 from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
10 from twitter.oauth import OAuth, read_token_file
11 from twitter.oauth_dance import oauth_dance
12 from twitter.util import printNicely
13 from twitter.ansi import *
14 from dateutil import parser
15
16 from colors import *
17 from config import *
18
19 def draw(t):
20 """
21 Draw the rainbow
22 """
23 # Retrieve tweet
24 text = t['text']
25 screen_name = t['user']['screen_name']
26 name = t['user']['name']
27 created_at = t['created_at']
28 date = parser.parse(created_at)
29 time = date.strftime('%Y/%m/%d %H:%M:%S')
30
31 # Format info
32 user = cycle_color(name + ' ' + '@' + screen_name + ' ')
33 clock = grey('['+ time + ']')
34 tweet = text.split()
35 tweet = map(lambda x: grey(x) if x=='RT' else x, tweet)
36 tweet = map(lambda x: cycle_color(x) if x[0]=='@' else x, tweet)
37 tweet = map(lambda x: cyan(x) if x[0:7]=='http://' else x, tweet)
38 tweet = ' '.join(tweet)
39
40 # Draw rainbow
41 line1 = u"{u:>{uw}}:".format(
42 u = user,
43 uw = len(user) + 2,
44 )
45 line2 = u"{c:>{cw}}".format(
46 c = clock,
47 cw = len(clock) + 2,
48 )
49 line3 = ' ' + tweet
50 line4 = '\n'
51
52 return line1, line2, line3, line4
53
54
55 def parse_arguments():
56 """
57 Parse the arguments
58 """
59
60 parser = argparse.ArgumentParser(description=__doc__ or "")
61
62 parser.add_argument('-to', '--timeout', help='Timeout for the stream (seconds).')
63 parser.add_argument('-ht', '--heartbeat-timeout', help='Set heartbeat timeout.', default=90)
64 parser.add_argument('-nb', '--no-block', action='store_true', help='Set stream to non-blocking.')
65 parser.add_argument('-tt', '--track-keywords', help='Search the stream for specific text.')
66 return parser.parse_args()
67
68
69 def main():
70 args = parse_arguments()
71
72 # The Logo
73 ascii_art()
74
75 # When using rainbow stream you must authorize.
76 twitter_credential = os.environ.get('HOME', os.environ.get('USERPROFILE', '')) + os.sep + '.rainbow_oauth'
77 if not os.path.exists(twitter_credential):
78 oauth_dance("Rainbow Stream",
79 CONSUMER_KEY,
80 CONSUMER_SECRET,
81 twitter_credential)
82 oauth_token, oauth_token_secret = read_token_file(twitter_credential)
83 auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)
84
85 # These arguments are optional:
86 stream_args = dict(
87 timeout=args.timeout,
88 block=not args.no_block,
89 heartbeat_timeout=args.heartbeat_timeout)
90
91 # Track keyword
92 query_args = dict()
93 if args.track_keywords:
94 query_args['track'] = args.track_keywords
95
96 # Get stream
97 stream = TwitterStream(auth=auth, domain='userstream.twitter.com', **stream_args)
98 tweet_iter = stream.user(**query_args)
99
100 # Iterate over the sample stream.
101 for tweet in tweet_iter:
102 if tweet is None:
103 printNicely("-- None --")
104 elif tweet is Timeout:
105 printNicely("-- Timeout --")
106 elif tweet is HeartbeatTimeout:
107 printNicely("-- Heartbeat Timeout --")
108 elif tweet is Hangup:
109 printNicely("-- Hangup --")
110 elif tweet.get('text'):
111 line1, line2, line3, line4 = draw(t = tweet)
112 printNicely(line1)
113 printNicely(line2)
114 printNicely(line3)
115 printNicely(line4)
116
117 if __name__ == '__main__':
118 main()