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]
156 count
= int(g
['stuff'].split()[1])
158 count
= HOME_TWEET_NUM
159 for tweet
in reversed(t
.statuses
.user_timeline(count
=count
, screen_name
=user
[1:])):
162 print(red('A name should begin with a \'@\''))
163 sys
.stdout
.write(g
['decorated_name'])
170 t
= Twitter(auth
=authen())
171 t
.statuses
.update(status
=g
['stuff'])
178 t
= Twitter(auth
=authen())
180 id = int(g
['stuff'].split()[0])
181 user
= t
.statuses
.show(id=id)['user']['screen_name']
182 status
= ' '.join(g
['stuff'].split()[1:])
183 status
= '@' + user
+ ' ' + status
.decode('utf-8')
184 t
.statuses
.update(status
=status
, in_reply_to_status_id
=id)
186 print(red('Sorry I can\'t understand.'))
187 sys
.stdout
.write(g
['decorated_name'])
194 t
= Twitter(auth
=authen())
196 id = int(g
['stuff'].split()[0])
197 t
.statuses
.destroy(id=id)
198 print(green('Okay it\'s gone.'))
200 print(red('Sorry I can\'t delete this tweet for you.'))
201 sys
.stdout
.write(g
['decorated_name'])
208 t
= Twitter(auth
=authen())
209 h
, w
= os
.popen('stty size', 'r').read().split()
210 if g
['stuff'][0] == '#':
211 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
212 printNicely(grey('*' * int(w
) + '\n'))
213 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
215 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
216 printNicely(grey('*' * int(w
) + '\n'))
218 print(red('A keyword should be a hashtag (like \'#AKB48\')'))
219 sys
.stdout
.write(g
['decorated_name'])
224 List of friend (following)
226 t
= Twitter(auth
=authen())
227 g
['friends'] = t
.friends
.ids()['ids']
228 for i
in g
['friends']:
229 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
230 user
= cycle_color('@' + screen_name
)
239 t
= Twitter(auth
=authen())
240 g
['followers'] = t
.followers
.ids()['ids']
241 for i
in g
['followers']:
242 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
243 user
= cycle_color('@' + screen_name
)
253 Hi boss! I'm ready to serve you right now!
254 ----------------------------------------------------
255 "home" will show your timeline. "home 7" will print 7 tweet.
256 "view @bob" will show your friend @bob's home.
257 "t oops" will tweet "oops" immediately.
258 "rep 12345 oops" will reply "oops" to tweet with id "12345".
259 "del 12345" will delete tweet with id "12345".
260 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
261 "fr" will list out your following people.
262 "fl" will list out your followers.
263 "h" or "help" will print this help once again.
264 "c" will clear the terminal.
266 ----------------------------------------------------
267 Have fun and hang tight!
270 sys
.stdout
.write(g
['decorated_name'])
284 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
305 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
310 Listen to user's input
312 for line
in iter(stdin
.readline
, ''):
314 cmd
= line
.split()[0]
317 # Save cmd to global variable and call process
318 g
['stuff'] = ' '.join(line
.split()[1:])
327 args
= parse_arguments()
331 # These arguments are optional:
333 timeout
=args
.timeout
,
334 block
=not args
.no_block
,
335 heartbeat_timeout
=args
.heartbeat_timeout
)
339 if args
.track_keywords
:
340 query_args
['track'] = args
.track_keywords
343 stream
= TwitterStream(
345 domain
='userstream.twitter.com',
347 tweet_iter
= stream
.user(**query_args
)
349 # Iterate over the sample stream.
350 for tweet
in tweet_iter
:
352 printNicely("-- None --")
353 elif tweet
is Timeout
:
354 printNicely("-- Timeout --")
355 elif tweet
is HeartbeatTimeout
:
356 printNicely("-- Heartbeat Timeout --")
357 elif tweet
is Hangup
:
358 printNicely("-- Hangup --")
359 elif tweet
.get('text'):
368 p
= Process(target
=stream
)
370 g
['stream_pid'] = p
.pid