2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 from dateutil
import parser
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
23 from .consumer
import *
24 from .interactive
import *
48 def draw(t
, keyword
=None, fil
=[], ig
=[]):
56 screen_name
= t
['user']['screen_name']
57 name
= t
['user']['name']
58 created_at
= t
['created_at']
59 favorited
= t
['favorited']
60 date
= parser
.parse(created_at
)
61 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
62 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
65 screen_name
= '@' + screen_name
66 if fil
and screen_name
not in fil
:
68 if ig
and screen_name
in ig
:
71 res
= db
.tweet_query(tid
)
74 res
= db
.tweet_query(tid
)
75 rid
= res
[0].rainbow_id
78 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
79 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
81 meta
= meta
+ green(u
'\u2605')
84 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
85 # Highlight screen_name
86 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
88 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
89 # Highlight search keyword
92 lambda x
: on_yellow(x
) if
93 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
97 tweet
= ' '.join(tweet
)
100 line1
= u
"{u:>{uw}}:".format(
104 line2
= u
"{c:>{cw}}".format(
116 def parse_arguments():
120 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
124 help='Timeout for the stream (seconds).')
127 '--heartbeat-timeout',
128 help='Set heartbeat timeout.',
134 help='Set stream to non-blocking.')
138 help='Search the stream for specific text.')
142 help='Filter specific screen_name.')
146 help='Ignore specific screen_name.')
147 return parser
.parse_args()
152 Authenticate with Twitter OAuth
154 # When using rainbow stream you must authorize.
155 twitter_credential
= os
.environ
.get(
159 '')) + os
.sep
+ '.rainbow_oauth'
160 if not os
.path
.exists(twitter_credential
):
161 oauth_dance("Rainbow Stream",
165 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
173 def get_decorated_name():
175 Beginning of every line
177 t
= Twitter(auth
=authen())
178 name
= '@' + t
.account
.verify_credentials()['screen_name']
179 g
['original_name'] = name
[1:]
180 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
188 target
= g
['stuff'].split()[0]
191 args
= parse_arguments()
193 if g
['stuff'].split()[-1] == '-f':
194 only
= raw_input('Only nicks: ')
195 ignore
= raw_input('Ignore nicks: ')
196 args
.filter = filter(None, only
.split(','))
197 args
.ignore
= filter(None, ignore
.split(','))
198 elif g
['stuff'].split()[-1] == '-d':
199 args
.filter = ONLY_LIST
200 args
.ignore
= IGNORE_LIST
202 printNicely(red('Sorry, wrong format.'))
206 if target
== 'public':
207 keyword
= g
['stuff'].split()[1]
208 if keyword
[0] == '#':
209 keyword
= keyword
[1:]
211 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
212 args
.track_keywords
= keyword
220 g
['stream_pid'] = p
.pid
223 elif target
== 'mine':
225 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
234 g
['stream_pid'] = p
.pid
236 printNicely(green('Stream switched.'))
238 printNicely(cyan('Only: ' + str(args
.filter)))
240 printNicely(red('Ignore: ' + str(args
.ignore
)))
243 printNicely(red('Sorry I can\'t understand.'))
250 t
= Twitter(auth
=authen())
252 if g
['stuff'].isdigit():
254 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
263 t
= Twitter(auth
=authen())
264 user
= g
['stuff'].split()[0]
267 num
= int(g
['stuff'].split()[1])
270 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
274 printNicely(red('A name should begin with a \'@\''))
281 t
= Twitter(auth
=authen())
282 t
.statuses
.update(status
=g
['stuff'])
289 t
= Twitter(auth
=authen())
291 id = int(g
['stuff'].split()[0])
292 tid
= db
.rainbow_query(id)[0].tweet_id
293 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
295 printNicely(red('Sorry I can\'t retweet for you.'))
302 t
= Twitter(auth
=authen())
304 id = int(g
['stuff'].split()[0])
305 tid
= db
.rainbow_query(id)[0].tweet_id
306 t
.favorites
.create(_id
=tid
, include_entities
=False)
307 printNicely(green('Favorited.'))
308 draw(t
.statuses
.show(id=tid
))
310 printNicely(red('Omg some syntax is wrong.'))
317 t
= Twitter(auth
=authen())
319 id = int(g
['stuff'].split()[0])
320 tid
= db
.rainbow_query(id)[0].tweet_id
321 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
322 status
= ' '.join(g
['stuff'].split()[1:])
323 status
= '@' + user
+ ' ' + status
.decode('utf-8')
324 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
326 printNicely(red('Sorry I can\'t understand.'))
333 t
= Twitter(auth
=authen())
335 id = int(g
['stuff'].split()[0])
336 tid
= db
.rainbow_query(id)[0].tweet_id
337 t
.statuses
.destroy(id=tid
)
338 printNicely(green('Okay it\'s gone.'))
340 printNicely(red('Sorry I can\'t delete this tweet for you.'))
347 t
= Twitter(auth
=authen())
349 id = int(g
['stuff'].split()[0])
350 tid
= db
.rainbow_query(id)[0].tweet_id
351 t
.favorites
.destroy(_id
=tid
)
352 printNicely(green('Okay it\'s unfavorited.'))
353 draw(t
.statuses
.show(id=tid
))
355 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
362 t
= Twitter(auth
=authen())
364 if g
['stuff'][0] == '#':
365 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
367 printNicely('Newest tweets:')
368 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
369 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
372 printNicely(magenta('I\'m afraid there is no result'))
374 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
376 printNicely(red('Sorry I can\'t understand.'))
381 List of friend (following)
383 t
= Twitter(auth
=authen())
384 g
['friends'] = t
.friends
.ids()['ids']
385 for i
in g
['friends']:
386 name
= t
.users
.lookup(user_id
=i
)[0]['name']
387 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
388 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
396 t
= Twitter(auth
=authen())
397 g
['followers'] = t
.followers
.ids()['ids']
398 for i
in g
['followers']:
399 name
= t
.users
.lookup(user_id
=i
)[0]['name']
400 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
401 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
410 h
, w
= os
.popen('stty size', 'r').read().split()
413 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
414 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
416 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
417 usage
+= s
* 2 + green('switch public #AKB') + \
418 ' will switch to public stream and follow "' + \
419 yellow('AKB') + '" keyword.\n'
420 usage
+= s
* 2 + green('switch mine') + \
421 ' will switch to your personal stream.\n'
422 usage
+= s
* 2 + green('switch mine -f ') + \
423 ' will prompt to enter the filter.\n'
424 usage
+= s
* 3 + yellow('Only nicks') + \
425 ' filter will decide nicks will be INCLUDE ONLY.\n'
426 usage
+= s
* 3 + yellow('Ignore nicks') + \
427 ' filter will decide nicks will be EXCLUDE.\n'
428 usage
+= s
* 2 + green('switch mine -d') + \
429 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
430 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
432 usage
+= s
+ 'For more action: \n'
433 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
434 green('home 7') + ' will show 7 tweet.\n'
435 usage
+= s
* 2 + green('view @mdo') + \
436 ' will show ' + yellow('@mdo') + '\'s home.\n'
437 usage
+= s
* 2 + green('t oops ') + \
438 'will tweet "' + yellow('oops') + '" immediately.\n'
440 green('rt 12 ') + ' will retweet to tweet with ' + \
441 yellow('[id=12]') + '.\n'
443 green('fav 12 ') + ' will favorite the tweet with ' + \
444 yellow('[id=12]') + '.\n'
445 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
446 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
448 green('del 12 ') + ' will delete tweet with ' + \
449 yellow('[id=12]') + '.\n'
451 green('ufav 12 ') + ' will unfavorite tweet with ' + \
452 yellow('[id=12]') + '.\n'
453 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
454 yellow('AKB48') + '" and return 5 newest tweet.\n'
455 usage
+= s
* 2 + green('fr') + ' will list out your following people.\n'
456 usage
+= s
* 2 + green('fl') + ' will list out your follower.\n'
457 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
458 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
459 usage
+= s
* 2 + green('q') + ' will quit.\n'
461 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
462 usage
+= s
+ 'Have fun and hang tight!\n'
477 os
.system('rm -rf rainbow.db')
478 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
487 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
519 Listen to user's input
524 ['public #', 'mine'], # switch
539 init_interactive_shell(d
)
543 line
= raw_input(g
['decorated_name'])
547 cmd
= line
.split()[0]
550 # Save cmd to global variable and call process
551 g
['stuff'] = ' '.join(line
.split()[1:])
553 if cmd
in ['switch', 't', 'rt', 'rep']:
559 def stream(domain
, args
, name
='Rainbow Stream'):
567 PUBLIC_DOMAIN
: args
.track_keywords
,
568 SITE_DOMAIN
: 'Site Stream',
570 ascii_art(art_dict
[domain
])
572 # These arguments are optional:
574 timeout
=args
.timeout
,
575 block
=not args
.no_block
,
576 heartbeat_timeout
=args
.heartbeat_timeout
)
580 if args
.track_keywords
:
581 query_args
['track'] = args
.track_keywords
584 stream
= TwitterStream(
589 if domain
== USER_DOMAIN
:
590 tweet_iter
= stream
.user(**query_args
)
591 elif domain
== SITE_DOMAIN
:
592 tweet_iter
= stream
.site(**query_args
)
594 if args
.track_keywords
:
595 tweet_iter
= stream
.statuses
.filter(**query_args
)
597 tweet_iter
= stream
.statuses
.sample()
599 # Iterate over the stream.
600 for tweet
in tweet_iter
:
602 printNicely("-- None --")
603 elif tweet
is Timeout
:
604 printNicely("-- Timeout --")
605 elif tweet
is HeartbeatTimeout
:
606 printNicely("-- Heartbeat Timeout --")
607 elif tweet
is Hangup
:
608 printNicely("-- Hangup --")
609 elif tweet
.get('text'):
612 keyword
=args
.track_keywords
,
621 # Spawn stream process
622 args
= parse_arguments()
624 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
627 # Start listen process
631 g
['stream_pid'] = p
.pid