2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
8 import os
, os
.path
, argparse
, sys
, time
, signal
10 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
11 from twitter
.api
import *
12 from twitter
.oauth
import OAuth
, read_token_file
13 from twitter
.oauth_dance
import oauth_dance
14 from twitter
.util
import printNicely
15 from dateutil
import parser
22 def draw(t
,keyword
=None):
28 screen_name
= t
['user']['screen_name']
29 name
= t
['user']['name']
30 created_at
= t
['created_at']
31 date
= parser
.parse(created_at
)
32 time
= date
.strftime('%Y/%m/%d %H:%M:%S')
35 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
36 clock
= grey('[' + time
+ ']')
39 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
40 # Highlight screen_name
41 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
43 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
44 # Highlight search keyword
45 tweet
= map(lambda x
: on_yellow(x
) if ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower() else x
, tweet
)
46 tweet
= ' '.join(tweet
)
49 line1
= u
"{u:>{uw}}:".format(
53 line2
= u
"{c:>{cw}}".format(
66 def parse_arguments():
71 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
76 help='Timeout for the stream (seconds).')
79 '--heartbeat-timeout',
80 help='Set heartbeat timeout.',
86 help='Set stream to non-blocking.')
90 help='Search the stream for specific text.')
91 return parser
.parse_args()
96 authenticate with Twitter OAuth
98 # When using rainbow stream you must authorize.
99 twitter_credential
= os
.environ
.get(
103 '')) + os
.sep
+ '.rainbow_oauth'
104 if not os
.path
.exists(twitter_credential
):
105 oauth_dance("Rainbow Stream",
109 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
117 def get_decorated_name():
119 Beginning of every line
121 t
= Twitter(auth
=authen())
122 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
123 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
130 t
= Twitter(auth
=authen())
131 t
.statuses
.update(status
=g
['stuff'])
138 t
= Twitter(auth
=authen())
139 rel
= t
.search
.tweets(q
='#' + g
['stuff'])['statuses']
140 printNicely(grey('**************************************************************************************\n'))
141 print('Newest',SEARCH_MAX_RECORD
, 'tweet: \n')
143 draw(t
=rel
[i
],keyword
=g
['stuff'].strip())
144 printNicely(grey('**************************************************************************************\n'))
152 Hi boss! I'm ready to serve you right now!
153 ----------------------------------------------------
154 "!" at the beginning will start to tweet immediately
155 "/" at the beginning will search for 5 newest tweet
156 "?" or "h" will print this help once again
157 "c" will clear the terminal
159 ----------------------------------------------------
160 Hvae fun and hang tight!
163 sys
.stdout
.write(g
['decorated_name'])
170 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
183 Process switch by start of line
192 }.get(line
[0],lambda: sys
.stdout
.write(g
['decorated_name']))
197 Listen to user's input
199 for line
in iter(stdin
.readline
, ''):
200 # Save cmd to global variable and call process
201 g
['stuff'] = line
[1:]
210 args
= parse_arguments()
214 # These arguments are optional:
216 timeout
=args
.timeout
,
217 block
=not args
.no_block
,
218 heartbeat_timeout
=args
.heartbeat_timeout
)
222 if args
.track_keywords
:
223 query_args
['track'] = args
.track_keywords
226 stream
= TwitterStream(
228 domain
= 'userstream.twitter.com',
230 tweet_iter
= stream
.user(**query_args
)
232 # Iterate over the sample stream.
233 for tweet
in tweet_iter
:
235 printNicely("-- None --")
236 elif tweet
is Timeout
:
237 printNicely("-- Timeout --")
238 elif tweet
is HeartbeatTimeout
:
239 printNicely("-- Heartbeat Timeout --")
240 elif tweet
is Hangup
:
241 printNicely("-- Hangup --")
242 elif tweet
.get('text'):
251 p
= Process(target
= stream
)
253 g
['stream_pid'] = p
.pid