2 Colorful user's timeline stream
5 from __future__
import print_function
7 import os
, os
.path
, argparse
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 dateutil
import parser
24 screen_name
= t
['user']['screen_name']
25 name
= t
['user']['name']
26 created_at
= t
['created_at']
27 date
= parser
.parse(created_at
)
28 time
= date
.strftime('%Y/%m/%d %H:%M:%S')
31 user
= cycle_color(name
+ ' ' + '@' + screen_name
+ ' ')
32 clock
= grey('['+ time
+ ']')
34 tweet
= map(lambda x
: grey(x
) if x
=='RT' else x
, tweet
)
35 tweet
= map(lambda x
: cycle_color(x
) if x
[0]=='@' else x
, tweet
)
36 tweet
= map(lambda x
: cyan(x
) if x
[0:7]=='http://' else x
, tweet
)
37 tweet
= ' '.join(tweet
)
40 line1
= u
"{u:>{uw}}:".format(
44 line2
= u
"{c:>{cw}}".format(
51 return line1
, line2
, line3
, line4
54 def parse_arguments():
59 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
61 parser
.add_argument('-to', '--timeout', help='Timeout for the stream (seconds).')
62 parser
.add_argument('-ht', '--heartbeat-timeout', help='Set heartbeat timeout.', default
=90)
63 parser
.add_argument('-nb', '--no-block', action
='store_true', help='Set stream to non-blocking.')
64 parser
.add_argument('-tt', '--track-keywords', help='Search the stream for specific text.')
65 return parser
.parse_args()
69 args
= parse_arguments()
74 # When using rainbow stream you must authorize.
75 twitter_credential
= os
.environ
.get('HOME', os
.environ
.get('USERPROFILE', '')) + os
.sep
+ '.rainbow_oauth'
76 if not os
.path
.exists(twitter_credential
):
77 oauth_dance("Rainbow Stream",
81 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
82 auth
= OAuth(oauth_token
, oauth_token_secret
, CONSUMER_KEY
, CONSUMER_SECRET
)
84 # These arguments are optional:
87 block
=not args
.no_block
,
88 heartbeat_timeout
=args
.heartbeat_timeout
)
92 if args
.track_keywords
:
93 query_args
['track'] = args
.track_keywords
96 stream
= TwitterStream(auth
=auth
, domain
='userstream.twitter.com', **stream_args
)
97 tweet_iter
= stream
.user(**query_args
)
99 # Iterate over the sample stream.
100 for tweet
in tweet_iter
:
102 printNicely("-- None --")
103 elif tweet
is Timeout
:
104 printNicely("-- Timeout --")
105 elif tweet
is HeartbeatTimeout
:
106 printNicely("-- Heartbeat Timeout --")
107 elif tweet
is Hangup
:
108 printNicely("-- Hangup --")
109 elif tweet
.get('text'):
110 line1
, line2
, line3
, line4
= draw(t
= tweet
)