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 twitter
.ansi
import *
14 from dateutil
import parser
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')
32 user
= cycle_color(name
+ ' ' + '@' + screen_name
+ ' ')
33 clock
= grey('['+ time
+ ']')
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
)
41 line1
= u
"{u:>{uw}}:".format(
45 line2
= u
"{c:>{cw}}".format(
52 return line1
, line2
, line3
, line4
55 def parse_arguments():
60 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
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()
70 args
= parse_arguments()
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",
82 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
83 auth
= OAuth(oauth_token
, oauth_token_secret
, CONSUMER_KEY
, CONSUMER_SECRET
)
85 # These arguments are optional:
88 block
=not args
.no_block
,
89 heartbeat_timeout
=args
.heartbeat_timeout
)
93 if args
.track_keywords
:
94 query_args
['track'] = args
.track_keywords
97 stream
= TwitterStream(auth
=auth
, domain
='userstream.twitter.com', **stream_args
)
98 tweet_iter
= stream
.user(**query_args
)
100 # Iterate over the sample stream.
101 for tweet
in tweet_iter
:
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
)
117 if __name__
== '__main__':