2 Colorful user's timeline stream
5 from __future__
import print_function
6 from multiprocessing
import Process
8 import os
, os
.path
, sys
,signal
9 import argparse
, time
, datetime
11 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
12 from twitter
.api
import *
13 from twitter
.oauth
import OAuth
, read_token_file
14 from twitter
.oauth_dance
import oauth_dance
15 from twitter
.util
import printNicely
16 from dateutil
import parser
25 def draw(t
, keyword
=None):
32 screen_name
= t
['user']['screen_name']
33 name
= t
['user']['name']
34 created_at
= t
['created_at']
35 date
= parser
.parse(created_at
)
36 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
37 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
39 res
= db
.tweet_query(tid
)
42 res
= db
.tweet_query(tid
)
43 rid
= res
[0].rainbow_id
46 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
47 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + ']')
50 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
51 # Highlight screen_name
52 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
54 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
55 # Highlight search keyword
58 lambda x
: on_yellow(x
) if
59 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
63 tweet
= ' '.join(tweet
)
66 line1
= u
"{u:>{uw}}:".format(
70 line2
= u
"{c:>{cw}}".format(
82 def parse_arguments():
86 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
90 help='Timeout for the stream (seconds).')
93 '--heartbeat-timeout',
94 help='Set heartbeat timeout.',
100 help='Set stream to non-blocking.')
104 help='Search the stream for specific text.')
105 return parser
.parse_args()
110 Authenticate with Twitter OAuth
112 # When using rainbow stream you must authorize.
113 twitter_credential
= os
.environ
.get(
117 '')) + os
.sep
+ '.rainbow_oauth'
118 if not os
.path
.exists(twitter_credential
):
119 oauth_dance("Rainbow Stream",
123 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
131 def get_decorated_name():
133 Beginning of every line
135 t
= Twitter(auth
=authen())
136 name
= '@' + t
.statuses
.user_timeline()[-1]['user']['screen_name']
137 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
144 t
= Twitter(auth
=authen())
145 count
= HOME_TWEET_NUM
146 if g
['stuff'].isdigit():
148 for tweet
in reversed(t
.statuses
.home_timeline(count
=count
)):
156 t
= Twitter(auth
=authen())
157 user
= g
['stuff'].split()[0]
160 count
= int(g
['stuff'].split()[1])
162 count
= HOME_TWEET_NUM
163 for tweet
in reversed(t
.statuses
.user_timeline(count
=count
, screen_name
=user
[1:])):
166 print(red('A name should begin with a \'@\''))
167 sys
.stdout
.write(g
['decorated_name'])
174 t
= Twitter(auth
=authen())
175 t
.statuses
.update(status
=g
['stuff'])
182 t
= Twitter(auth
=authen())
184 id = int(g
['stuff'].split()[0])
185 tid
= db
.rainbow_query(id)[0].tweet_id
186 t
.statuses
.retweet(id=tid
,include_entities
=False,trim_user
=True)
188 print(red('Sorry I can\'t retweet for you.'))
189 sys
.stdout
.write(g
['decorated_name'])
196 t
= Twitter(auth
=authen())
198 id = int(g
['stuff'].split()[0])
199 tid
= db
.rainbow_query(id)[0].tweet_id
200 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
201 status
= ' '.join(g
['stuff'].split()[1:])
202 status
= '@' + user
+ ' ' + status
.decode('utf-8')
203 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
205 print(red('Sorry I can\'t understand.'))
206 sys
.stdout
.write(g
['decorated_name'])
213 t
= Twitter(auth
=authen())
215 id = int(g
['stuff'].split()[0])
216 tid
= db
.rainbow_query(id)[0].tweet_id
217 t
.statuses
.destroy(id=tid
)
218 print(green('Okay it\'s gone.'))
220 print(red('Sorry I can\'t delete this tweet for you.'))
221 sys
.stdout
.write(g
['decorated_name'])
228 t
= Twitter(auth
=authen())
229 h
, w
= os
.popen('stty size', 'r').read().split()
230 if g
['stuff'][0] == '#':
231 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
232 printNicely(grey('*' * int(w
) + '\n'))
233 print('Newest', SEARCH_MAX_RECORD
, 'tweet: \n')
235 draw(t
=rel
[i
], keyword
=g
['stuff'].strip())
236 printNicely(grey('*' * int(w
) + '\n'))
238 print(red('A keyword should be a hashtag (like \'#AKB48\')'))
239 sys
.stdout
.write(g
['decorated_name'])
244 List of friend (following)
246 t
= Twitter(auth
=authen())
247 g
['friends'] = t
.friends
.ids()['ids']
248 for i
in g
['friends']:
249 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
250 user
= cycle_color('@' + screen_name
)
259 t
= Twitter(auth
=authen())
260 g
['followers'] = t
.followers
.ids()['ids']
261 for i
in g
['followers']:
262 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
263 user
= cycle_color('@' + screen_name
)
273 Hi boss! I'm ready to serve you right now!
274 ----------------------------------------------------
275 "home" will show your timeline. "home 7" will show 7 tweet.
276 "view @bob" will show your friend @bob's home.
277 "t oops" will tweet "oops" immediately.
278 "rt 12345" will retweet to tweet with id "12345".
279 "rep 12345 oops" will reply "oops" to tweet with id "12345".
280 "del 12345" will delete tweet with id "12345".
281 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
282 "fr" will list out your following people.
283 "fl" will list out your followers.
284 "h" will show this help again.
285 "c" will clear the terminal.
287 ----------------------------------------------------
288 Have fun and hang tight!
291 sys
.stdout
.write(g
['decorated_name'])
306 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
327 }.get(cmd
, lambda: sys
.stdout
.write(g
['decorated_name']))
332 Listen to user's input
334 for line
in iter(stdin
.readline
, ''):
336 cmd
= line
.split()[0]
339 # Save cmd to global variable and call process
340 g
['stuff'] = ' '.join(line
.split()[1:])
349 args
= parse_arguments()
355 # These arguments are optional:
357 timeout
=args
.timeout
,
358 block
=not args
.no_block
,
359 heartbeat_timeout
=args
.heartbeat_timeout
)
363 if args
.track_keywords
:
364 query_args
['track'] = args
.track_keywords
367 stream
= TwitterStream(
371 tweet_iter
= stream
.user(**query_args
)
373 # Iterate over the sample stream.
374 for tweet
in tweet_iter
:
376 printNicely("-- None --")
377 elif tweet
is Timeout
:
378 printNicely("-- Timeout --")
379 elif tweet
is HeartbeatTimeout
:
380 printNicely("-- Heartbeat Timeout --")
381 elif tweet
is Hangup
:
382 printNicely("-- Hangup --")
383 elif tweet
.get('text'):
393 p
= Process(target
=stream
)
395 g
['stream_pid'] = p
.pid