2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
15 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
16 from twitter
.api
import *
17 from twitter
.oauth
import OAuth
, read_token_file
18 from twitter
.oauth_dance
import oauth_dance
19 from twitter
.util
import printNicely
20 from dateutil
import parser
28 def draw(t
, keyword
=None):
35 screen_name
= t
['user']['screen_name']
36 name
= t
['user']['name']
37 created_at
= t
['created_at']
38 date
= parser
.parse(created_at
)
39 time
= date
.strftime('%Y/%m/%d %H:%M:%S')
42 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
43 meta
= grey('[' + time
+ '] ['+ str(tid
) +']')
46 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
47 # Highlight screen_name
48 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
50 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
51 # Highlight search keyword
54 lambda x
: on_yellow(x
) if
55 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
59 tweet
= ' '.join(tweet
)
62 line1
= u
"{u:>{uw}}:".format(
66 line2
= u
"{c:>{cw}}".format(
79 def parse_arguments():
83 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
87 help='Timeout for the stream (seconds).')
90 '--heartbeat-timeout',
91 help='Set heartbeat timeout.',
97 help='Set stream to non-blocking.')
101 help='Search the stream for specific text.')
102 return parser
.parse_args()
107 authenticate with Twitter OAuth
109 # When using rainbow stream you must authorize.
110 twitter_credential
= os
.environ
.get(
114 '')) + os
.sep
+ '.rainbow_oauth'
115 if not os
.path
.exists(twitter_credential
):
116 oauth_dance("Rainbow Stream",
120 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
128 def get_decorated_name():
130 Beginning of every line
132 t
= Twitter(auth
=authen())
133 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
134 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
141 t
= Twitter(auth
=authen())
142 t
.statuses
.update(status
=g
['stuff'])
147 Authen and get timeline
149 t
= Twitter(auth
=authen())
150 count
= HOME_TWEET_NUM
151 if g
['stuff'].isdigit():
153 for tweet
in reversed(t
.statuses
.home_timeline(count
=count
)):
161 t
= Twitter(auth
=authen())
162 rel
= t
.search
.tweets(q
='#' + g
['stuff'])['statuses']
163 h
, w
= os
.popen('stty size', 'r').read().split()
165 printNicely(grey('*' * int(w
) + '\n'))
166 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
168 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
169 printNicely(grey('*' * int(w
) + '\n'))
174 List of friend (following)
176 t
= Twitter(auth
=authen())
177 g
['friends'] = t
.friends
.ids()['ids']
178 for i
in g
['friends']:
179 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
180 user
= cycle_color('@' + screen_name
)
189 t
= Twitter(auth
=authen())
190 g
['followers'] = t
.followers
.ids()['ids']
191 for i
in g
['followers']:
192 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
193 user
= cycle_color('@' + screen_name
)
203 Hi boss! I'm ready to serve you right now!
204 ----------------------------------------------------
205 "t" at the beginning will tweet immediately
206 "tl" at the beginning will tweet immediately
207 "s" and follow by any word will search and return 5 newest tweet
208 "fr" will list out your following people
209 "fl" will list out your followers
210 "h" or "help" will print this help once again
211 "c" will clear the terminal
213 ----------------------------------------------------
214 Have fun and hang tight!
217 sys
.stdout
.write(g
['decorated_name'])
231 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
237 Process switch by start of line
249 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
254 Listen to user's input
256 for line
in iter(stdin
.readline
, ''):
258 cmd
= line
.split()[0]
261 # Save cmd to global variable and call process
262 g
['stuff'] = ' '.join(line
.split()[1:])
271 args
= parse_arguments()
275 # These arguments are optional:
277 timeout
=args
.timeout
,
278 block
=not args
.no_block
,
279 heartbeat_timeout
=args
.heartbeat_timeout
)
283 if args
.track_keywords
:
284 query_args
['track'] = args
.track_keywords
287 stream
= TwitterStream(
289 domain
='userstream.twitter.com',
291 tweet_iter
= stream
.user(**query_args
)
293 # Iterate over the sample stream.
294 for tweet
in tweet_iter
:
296 printNicely("-- None --")
297 elif tweet
is Timeout
:
298 printNicely("-- Timeout --")
299 elif tweet
is HeartbeatTimeout
:
300 printNicely("-- Heartbeat Timeout --")
301 elif tweet
is Hangup
:
302 printNicely("-- Hangup --")
303 elif tweet
.get('text'):
312 p
= Process(target
=stream
)
314 g
['stream_pid'] = p
.pid