bfbb6a0a84a52832c086bec4c4ad8de0c300ce4d
2 Colorful user's timeline stream
4 from __future__
import print_function
5 from multiprocessing
import Process
6 from dateutil
import parser
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
24 from .interactive
import *
45 def draw(t
, keyword
=None):
52 screen_name
= t
['user']['screen_name']
53 name
= t
['user']['name']
54 created_at
= t
['created_at']
55 date
= parser
.parse(created_at
)
56 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
57 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
59 res
= db
.tweet_query(tid
)
62 res
= db
.tweet_query(tid
)
63 rid
= res
[0].rainbow_id
66 user
= cycle_color(name
) + grey(' ' + '@' + screen_name
+ ' ')
67 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + ']')
70 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
71 # Highlight screen_name
72 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
74 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
75 # Highlight search keyword
78 lambda x
: on_yellow(x
) if
79 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
83 tweet
= ' '.join(tweet
)
86 line1
= u
"{u:>{uw}}:".format(
90 line2
= u
"{c:>{cw}}".format(
102 def parse_arguments():
106 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
110 help='Timeout for the stream (seconds).')
113 '--heartbeat-timeout',
114 help='Set heartbeat timeout.',
120 help='Set stream to non-blocking.')
124 help='Search the stream for specific text.')
125 return parser
.parse_args()
130 Authenticate with Twitter OAuth
132 # When using rainbow stream you must authorize.
133 twitter_credential
= os
.environ
.get(
137 '')) + os
.sep
+ '.rainbow_oauth'
138 if not os
.path
.exists(twitter_credential
):
139 oauth_dance("Rainbow Stream",
143 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
151 def get_decorated_name():
153 Beginning of every line
155 t
= Twitter(auth
=authen())
156 name
= '@' + t
.account
.verify_credentials()['screen_name']
157 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
164 t
= Twitter(auth
=authen())
166 if g
['stuff'].isdigit():
168 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
177 t
= Twitter(auth
=authen())
178 user
= g
['stuff'].split()[0]
181 num
= int(g
['stuff'].split()[1])
184 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
188 printNicely(red('A name should begin with a \'@\''))
195 t
= Twitter(auth
=authen())
196 t
.statuses
.update(status
=g
['stuff'])
204 t
= Twitter(auth
=authen())
206 id = int(g
['stuff'].split()[0])
207 tid
= db
.rainbow_query(id)[0].tweet_id
208 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
210 printNicely(red('Sorry I can\'t retweet for you.'))
218 t
= Twitter(auth
=authen())
220 id = int(g
['stuff'].split()[0])
221 tid
= db
.rainbow_query(id)[0].tweet_id
222 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
223 status
= ' '.join(g
['stuff'].split()[1:])
224 status
= '@' + user
+ ' ' + status
.decode('utf-8')
225 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
227 printNicely(red('Sorry I can\'t understand.'))
235 t
= Twitter(auth
=authen())
237 id = int(g
['stuff'].split()[0])
238 tid
= db
.rainbow_query(id)[0].tweet_id
239 t
.statuses
.destroy(id=tid
)
240 printNicely(green('Okay it\'s gone.'))
242 printNicely(red('Sorry I can\'t delete this tweet for you.'))
249 t
= Twitter(auth
=authen())
251 if g
['stuff'][0] == '#':
252 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
254 printNicely('Newest tweets:')
255 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
256 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
259 printNicely(magenta('I\'m afraid there is no result'))
261 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
263 printNicely(red('Sorry I can\'t understand.'))
268 List of friend (following)
270 t
= Twitter(auth
=authen())
271 g
['friends'] = t
.friends
.ids()['ids']
272 for i
in g
['friends']:
273 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
274 user
= cycle_color('@' + screen_name
)
283 t
= Twitter(auth
=authen())
284 g
['followers'] = t
.followers
.ids()['ids']
285 for i
in g
['followers']:
286 screen_name
= t
.users
.lookup(user_id
=i
)[0]['screen_name']
287 user
= cycle_color('@' + screen_name
)
297 Hi boss! I'm ready to serve you right now!
298 -------------------------------------------------------------
299 "home" will show your timeline. "home 7" will show 7 tweet.
300 "view @bob" will show your friend @bob's home.
301 "t oops" will tweet "oops" immediately.
302 "rt 12345" will retweet to tweet with id "12345".
303 "rep 12345 oops" will reply "oops" to tweet with id "12345".
304 "del 12345" will delete tweet with id "12345".
305 "s #AKB48" will search for "AKB48" and return 5 newest tweet.
306 "fr" will list out your following people.
307 "fl" will list out your followers.
308 "h" will show this help again.
309 "c" will clear the terminal.
311 -------------------------------------------------------------
312 Have fun and hang tight!
329 os
.system('rm -rf rainbow.db')
330 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
339 printNicely(green('Need tips ? Type "h" and hit Enter key!'))
368 init_interactive_shell(cmdset
)
371 if g
['prefix'] and not first
:
372 line
= raw_input(g
['decorated_name'])
376 cmd
= line
.split()[0]
379 # Save cmd to global variable and call process
380 g
['stuff'] = ' '.join(line
.split()[1:])
389 args
= parse_arguments()
393 # These arguments are optional:
395 timeout
=args
.timeout
,
396 block
=not args
.no_block
,
397 heartbeat_timeout
=args
.heartbeat_timeout
)
401 if args
.track_keywords
:
402 query_args
['track'] = args
.track_keywords
405 stream
= TwitterStream(
409 tweet_iter
= stream
.user(**query_args
)
411 # Iterate over the sample stream.
412 for tweet
in tweet_iter
:
414 printNicely("-- None --")
415 elif tweet
is Timeout
:
416 printNicely("-- Timeout --")
417 elif tweet
is HeartbeatTimeout
:
418 printNicely("-- Heartbeat Timeout --")
419 elif tweet
is Hangup
:
420 printNicely("-- Hangup --")
421 elif tweet
.get('text'):
432 p
= Process(target
=stream
)
434 g
['stream_pid'] = p
.pid