9016815066bbf6892fa08e3f5c003045d2f21e93
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
+ '] [id=' + 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(
78 def parse_arguments():
82 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
86 help='Timeout for the stream (seconds).')
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
96 help='Set stream to non-blocking.')
100 help='Search the stream for specific text.')
101 return parser
.parse_args()
106 Authenticate with Twitter OAuth
108 # When using rainbow stream you must authorize.
109 twitter_credential
= os
.environ
.get(
113 '')) + os
.sep
+ '.rainbow_oauth'
114 if not os
.path
.exists(twitter_credential
):
115 oauth_dance("Rainbow Stream",
119 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
127 def get_decorated_name():
129 Beginning of every line
131 t
= Twitter(auth
=authen())
132 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
133 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
140 t
= Twitter(auth
=authen())
141 count
= HOME_TWEET_NUM
142 if g
['stuff'].isdigit():
144 for tweet
in reversed(t
.statuses
.home_timeline(count
=count
)):
152 t
= Twitter(auth
=authen())
153 user
= g
['stuff'].split()[0]
155 count
= int(g
['stuff'].split()[1])
157 count
= HOME_TWEET_NUM
158 for tweet
in reversed(t
.statuses
.user_timeline(count
=count
, screen_name
=user
)):
166 t
= Twitter(auth
=authen())
167 t
.statuses
.update(status
=g
['stuff'])
174 t
= Twitter(auth
=authen())
176 id = int(g
['stuff'].split()[0])
177 user
= t
.statuses
.show(id=id)['user']['screen_name']
178 status
= ' '.join(g
['stuff'].split()[1:])
179 status
= '@' + user
+ ' ' + status
.decode('utf-8')
180 t
.statuses
.update(status
=status
, in_reply_to_status_id
=id)
182 print(red('Sorry I can\'t understand.'))
189 t
= Twitter(auth
=authen())
191 id = int(g
['stuff'].split()[0])
192 t
.statuses
.destroy(id=id)
193 print(green('Okay it\'s gone.'))
195 print(red('Sorry I can\'t delete this tweet for you.'))
202 t
= Twitter(auth
=authen())
203 rel
= t
.search
.tweets(q
='#' + g
['stuff'])['statuses']
204 h
, w
= os
.popen('stty size', 'r').read().split()
206 printNicely(grey('*' * int(w
) + '\n'))
207 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
209 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
210 printNicely(grey('*' * int(w
) + '\n'))
215 List of friend (following)
217 t
= Twitter(auth
=authen())
218 g
['friends'] = t
.friends
.ids()['ids']
219 for i
in g
['friends']:
220 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
221 user
= cycle_color('@' + screen_name
)
230 t
= Twitter(auth
=authen())
231 g
['followers'] = t
.followers
.ids()['ids']
232 for i
in g
['followers']:
233 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
234 user
= cycle_color('@' + screen_name
)
244 Hi boss! I'm ready to serve you right now!
245 ----------------------------------------------------
246 "home" will show your timeline. "home 7" will print 7 tweet.
247 "view bob" will show your friend @bob's home.
248 "t oops" will tweet "oops" immediately.
249 "rep 12345 oops" will reply "oops" to tweet with id "12345".
250 "del 12345" will delete tweet with id "12345".
251 "s AKB48" will search for "AKB48" and return 5 newest tweet.
252 "fr" will list out your following people.
253 "fl" will list out your followers.
254 "h" or "help" will print this help once again.
255 "c" will clear the terminal.
257 ----------------------------------------------------
258 Have fun and hang tight!
261 sys
.stdout
.write(g
['decorated_name'])
275 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
296 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
301 Listen to user's input
303 for line
in iter(stdin
.readline
, ''):
305 cmd
= line
.split()[0]
308 # Save cmd to global variable and call process
309 g
['stuff'] = ' '.join(line
.split()[1:])
318 args
= parse_arguments()
322 # These arguments are optional:
324 timeout
=args
.timeout
,
325 block
=not args
.no_block
,
326 heartbeat_timeout
=args
.heartbeat_timeout
)
330 if args
.track_keywords
:
331 query_args
['track'] = args
.track_keywords
334 stream
= TwitterStream(
336 domain
='userstream.twitter.com',
338 tweet_iter
= stream
.user(**query_args
)
340 # Iterate over the sample stream.
341 for tweet
in tweet_iter
:
343 printNicely("-- None --")
344 elif tweet
is Timeout
:
345 printNicely("-- Timeout --")
346 elif tweet
is HeartbeatTimeout
:
347 printNicely("-- Heartbeat Timeout --")
348 elif tweet
is Hangup
:
349 printNicely("-- Hangup --")
350 elif tweet
.get('text'):
359 p
= Process(target
=stream
)
361 g
['stream_pid'] = p
.pid