9570fee261d8f43dcaece15dfb9e4371d35da010
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
46 tweet
= map(lambda x
: on_yellow(x
) if ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower() else x
, tweet
)
47 tweet
= ' '.join(tweet
)
50 line1
= u
"{u:>{uw}}:".format(
54 line2
= u
"{c:>{cw}}".format(
67 def parse_arguments():
72 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
77 help='Timeout for the stream (seconds).')
80 '--heartbeat-timeout',
81 help='Set heartbeat timeout.',
87 help='Set stream to non-blocking.')
91 help='Search the stream for specific text.')
92 return parser
.parse_args()
97 authenticate with Twitter OAuth
99 # When using rainbow stream you must authorize.
100 twitter_credential
= os
.environ
.get(
104 '')) + os
.sep
+ '.rainbow_oauth'
105 if not os
.path
.exists(twitter_credential
):
106 oauth_dance("Rainbow Stream",
110 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
118 def get_decorated_name():
120 Beginning of every line
122 t
= Twitter(auth
=authen())
123 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
124 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
131 t
= Twitter(auth
=authen())
132 t
.statuses
.update(status
=g
['stuff'])
139 t
= Twitter(auth
=authen())
140 rel
= t
.search
.tweets(q
='#' + g
['stuff'])['statuses']
141 printNicely(grey('**************************************************************************************\n'))
142 print('Newest',SEARCH_MAX_RECORD
, 'tweet: \n')
144 draw(t
=rel
[i
],keyword
=g
['stuff'].strip())
145 printNicely(grey('**************************************************************************************\n'))
153 Hi boss! I'm ready to serve you right now!
154 ----------------------------------------------------
155 "!" at the beginning will start to tweet immediately
156 "/" at the beginning will search for 5 newest tweet
157 "?" or "h" will print this help once again
158 "c" will clear the terminal
160 ----------------------------------------------------
161 Hvae fun and hang tight!
164 sys
.stdout
.write(g
['decorated_name'])
171 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
184 Process switch by start of line
193 }.get(line
[0],lambda: sys
.stdout
.write(g
['decorated_name']))
198 Listen to user's input
200 for line
in iter(stdin
.readline
, ''):
201 # Save cmd to global variable and call process
202 g
['stuff'] = line
[1:]
211 args
= parse_arguments()
215 # These arguments are optional:
217 timeout
=args
.timeout
,
218 block
=not args
.no_block
,
219 heartbeat_timeout
=args
.heartbeat_timeout
)
223 if args
.track_keywords
:
224 query_args
['track'] = args
.track_keywords
227 stream
= TwitterStream(
229 domain
= 'userstream.twitter.com',
231 tweet_iter
= stream
.user(**query_args
)
233 # Iterate over the sample stream.
234 for tweet
in tweet_iter
:
236 printNicely("-- None --")
237 elif tweet
is Timeout
:
238 printNicely("-- Timeout --")
239 elif tweet
is HeartbeatTimeout
:
240 printNicely("-- Heartbeat Timeout --")
241 elif tweet
is Hangup
:
242 printNicely("-- Hangup --")
243 elif tweet
.get('text'):
252 p
= Process(target
= stream
)
254 g
['stream_pid'] = p
.pid