2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 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
21 from StringIO
import StringIO
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
52 def draw(t
, iot
=False, keyword
=None, fil
=[], ig
=[]):
60 screen_name
= t
['user']['screen_name']
61 name
= t
['user']['name']
62 created_at
= t
['created_at']
63 favorited
= t
['favorited']
64 date
= parser
.parse(created_at
)
65 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
66 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
72 urls
= t
['entities']['urls']
74 expanded_url
.append(u
['expanded_url'])
83 media
= t
['entities']['media']
85 media_url
.append(m
['media_url'])
90 screen_name
= '@' + screen_name
91 if fil
and screen_name
not in fil
:
93 if ig
and screen_name
in ig
:
96 res
= db
.tweet_query(tid
)
99 res
= db
.tweet_query(tid
)
100 rid
= res
[0].rainbow_id
103 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
104 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
106 meta
= meta
+ green(u
'\u2605')
110 for index
in range(len(expanded_url
)):
112 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
115 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
116 # Highlight screen_name
117 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
119 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
120 # Highlight search keyword
123 lambda x
: on_yellow(x
) if
124 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
129 tweet
= ' '.join(tweet
)
132 line1
= u
"{u:>{uw}}:".format(
136 line2
= u
"{c:>{cw}}".format(
148 if iot
and media_url
:
150 response
= requests
.get(mu
)
151 image_to_display(StringIO(response
.content
))
154 def parse_arguments():
158 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
162 help='Timeout for the stream (seconds).')
165 '--heartbeat-timeout',
166 help='Set heartbeat timeout.',
172 help='Set stream to non-blocking.')
176 help='Search the stream for specific text.')
180 help='Filter specific screen_name.')
184 help='Ignore specific screen_name.')
189 help='Display all image on terminal.')
190 return parser
.parse_args()
195 Authenticate with Twitter OAuth
197 # When using rainbow stream you must authorize.
198 twitter_credential
= os
.environ
.get(
202 '')) + os
.sep
+ '.rainbow_oauth'
203 if not os
.path
.exists(twitter_credential
):
204 oauth_dance("Rainbow Stream",
208 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
216 def get_decorated_name():
218 Beginning of every line
220 t
= Twitter(auth
=authen())
221 name
= '@' + t
.account
.verify_credentials()['screen_name']
222 g
['original_name'] = name
[1:]
223 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
231 target
= g
['stuff'].split()[0]
234 args
= parse_arguments()
236 if g
['stuff'].split()[-1] == '-f':
237 only
= raw_input('Only nicks: ')
238 ignore
= raw_input('Ignore nicks: ')
239 args
.filter = filter(None, only
.split(','))
240 args
.ignore
= filter(None, ignore
.split(','))
241 elif g
['stuff'].split()[-1] == '-d':
242 args
.filter = ONLY_LIST
243 args
.ignore
= IGNORE_LIST
245 printNicely(red('Sorry, wrong format.'))
249 if target
== 'public':
250 keyword
= g
['stuff'].split()[1]
251 if keyword
[0] == '#':
252 keyword
= keyword
[1:]
254 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
255 args
.track_keywords
= keyword
263 g
['stream_pid'] = p
.pid
266 elif target
== 'mine':
268 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
277 g
['stream_pid'] = p
.pid
279 printNicely(green('Stream switched.'))
281 printNicely(cyan('Only: ' + str(args
.filter)))
283 printNicely(red('Ignore: ' + str(args
.ignore
)))
286 printNicely(red('Sorry I can\'t understand.'))
293 t
= Twitter(auth
=authen())
295 if g
['stuff'].isdigit():
297 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
298 draw(t
=tweet
, iot
=g
['iot'])
306 t
= Twitter(auth
=authen())
307 user
= g
['stuff'].split()[0]
310 num
= int(g
['stuff'].split()[1])
313 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
314 draw(t
=tweet
, iot
=g
['iot'])
317 printNicely(red('A name should begin with a \'@\''))
324 t
= Twitter(auth
=authen())
325 t
.statuses
.update(status
=g
['stuff'])
332 t
= Twitter(auth
=authen())
334 id = int(g
['stuff'].split()[0])
335 tid
= db
.rainbow_query(id)[0].tweet_id
336 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
338 printNicely(red('Sorry I can\'t retweet for you.'))
345 t
= Twitter(auth
=authen())
347 id = int(g
['stuff'].split()[0])
348 tid
= db
.rainbow_query(id)[0].tweet_id
349 t
.favorites
.create(_id
=tid
, include_entities
=False)
350 printNicely(green('Favorited.'))
351 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
353 printNicely(red('Omg some syntax is wrong.'))
360 t
= Twitter(auth
=authen())
362 id = int(g
['stuff'].split()[0])
363 tid
= db
.rainbow_query(id)[0].tweet_id
364 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
365 status
= ' '.join(g
['stuff'].split()[1:])
366 status
= '@' + user
+ ' ' + status
.decode('utf-8')
367 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
369 printNicely(red('Sorry I can\'t understand.'))
376 t
= Twitter(auth
=authen())
378 id = int(g
['stuff'].split()[0])
379 tid
= db
.rainbow_query(id)[0].tweet_id
380 t
.statuses
.destroy(id=tid
)
381 printNicely(green('Okay it\'s gone.'))
383 printNicely(red('Sorry I can\'t delete this tweet for you.'))
390 t
= Twitter(auth
=authen())
392 id = int(g
['stuff'].split()[0])
393 tid
= db
.rainbow_query(id)[0].tweet_id
394 t
.favorites
.destroy(_id
=tid
)
395 printNicely(green('Okay it\'s unfavorited.'))
396 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
398 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
405 t
= Twitter(auth
=authen())
407 if g
['stuff'][0] == '#':
408 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
410 printNicely('Newest tweets:')
411 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
414 keyword
=g
['stuff'].strip()[1:])
417 printNicely(magenta('I\'m afraid there is no result'))
419 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
421 printNicely(red('Sorry I can\'t understand.'))
428 t
= Twitter(auth
=authen())
430 target
= g
['stuff'].split()[0]
431 if target
!= 'image':
433 id = int(g
['stuff'].split()[1])
434 tid
= db
.rainbow_query(id)[0].tweet_id
435 tweet
= t
.statuses
.show(id=tid
)
436 media
= tweet
['entities']['media']
438 res
= requests
.get(m
['media_url'])
439 img
= Image
.open(StringIO(res
.content
))
442 printNicely(red('Sorry I can\'t show this image.'))
449 t
= Twitter(auth
=authen())
450 screen_name
= g
['stuff'].split()[0]
451 if screen_name
[0] == '@':
453 t
.friendships
.create(screen_name
=screen_name
[1:],follow
=True)
454 printNicely(green('You are following ' + screen_name
+ ' now!'))
456 printNicely(red('Sorry can not follow at this time.'))
458 printNicely(red('Sorry I can\'t understand.'))
465 t
= Twitter(auth
=authen())
466 screen_name
= g
['stuff'].split()[0]
467 if screen_name
[0] == '@':
469 t
.friendships
.destroy(screen_name
=screen_name
[1:],include_entities
=False)
470 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
472 printNicely(red('Sorry can not unfollow at this time.'))
474 printNicely(red('Sorry I can\'t understand.'))
482 h
, w
= os
.popen('stty size', 'r').read().split()
485 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
486 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
488 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
489 usage
+= s
* 2 + green('switch public #AKB') + \
490 ' will switch to public stream and follow "' + \
491 yellow('AKB') + '" keyword.\n'
492 usage
+= s
* 2 + green('switch mine') + \
493 ' will switch to your personal stream.\n'
494 usage
+= s
* 2 + green('switch mine -f ') + \
495 ' will prompt to enter the filter.\n'
496 usage
+= s
* 3 + yellow('Only nicks') + \
497 ' filter will decide nicks will be INCLUDE ONLY.\n'
498 usage
+= s
* 3 + yellow('Ignore nicks') + \
499 ' filter will decide nicks will be EXCLUDE.\n'
500 usage
+= s
* 2 + green('switch mine -d') + \
501 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
502 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
504 usage
+= s
+ 'For more action: \n'
505 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
506 green('home 7') + ' will show 7 tweet.\n'
507 usage
+= s
* 2 + green('view @mdo') + \
508 ' will show ' + yellow('@mdo') + '\'s home.\n'
509 usage
+= s
* 2 + green('t oops ') + \
510 'will tweet "' + yellow('oops') + '" immediately.\n'
512 green('rt 12 ') + ' will retweet to tweet with ' + \
513 yellow('[id=12]') + '.\n'
515 green('fav 12 ') + ' will favorite the tweet with ' + \
516 yellow('[id=12]') + '.\n'
517 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
518 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
520 green('del 12 ') + ' will delete tweet with ' + \
521 yellow('[id=12]') + '.\n'
523 green('ufav 12 ') + ' will unfavorite tweet with ' + \
524 yellow('[id=12]') + '.\n'
525 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
526 yellow('AKB48') + '" and return 5 newest tweet.\n'
527 usage
+= s
* 2 + green('show image 12') + ' will show image in tweet with ' + \
528 yellow('[id=12]') + ' in your OS\'s image viewer.\n'
529 usage
+= s
* 2 + green('fl @dtvd88') + ' will follow ' + \
530 yellow('@dtvd88') + '.\n'
531 usage
+= s
* 2 + green('ufl @dtvd88') + ' will unfollow ' + \
532 yellow('@dtvd88') + '.\n'
533 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
534 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
535 usage
+= s
* 2 + green('q') + ' will quit.\n'
537 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
538 usage
+= s
+ 'Have fun and hang tight!\n'
554 os
.system('rm -rf rainbow.db')
555 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
564 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
597 Listen to user's input
602 ['public #', 'mine'], # switch
612 ['image'], # show image
620 init_interactive_shell(d
)
625 line
= raw_input(g
['decorated_name'])
629 cmd
= line
.split()[0]
632 # Save cmd to global variable and call process
633 g
['stuff'] = ' '.join(line
.split()[1:])
635 if cmd
in ['switch', 't', 'rt', 'rep']:
641 def stream(domain
, args
, name
='Rainbow Stream'):
649 PUBLIC_DOMAIN
: args
.track_keywords
,
650 SITE_DOMAIN
: 'Site Stream',
652 ascii_art(art_dict
[domain
])
654 # These arguments are optional:
656 timeout
=args
.timeout
,
657 block
=not args
.no_block
,
658 heartbeat_timeout
=args
.heartbeat_timeout
)
662 if args
.track_keywords
:
663 query_args
['track'] = args
.track_keywords
666 stream
= TwitterStream(
671 if domain
== USER_DOMAIN
:
672 tweet_iter
= stream
.user(**query_args
)
673 elif domain
== SITE_DOMAIN
:
674 tweet_iter
= stream
.site(**query_args
)
676 if args
.track_keywords
:
677 tweet_iter
= stream
.statuses
.filter(**query_args
)
679 tweet_iter
= stream
.statuses
.sample()
681 # Iterate over the stream.
682 for tweet
in tweet_iter
:
684 printNicely("-- None --")
685 elif tweet
is Timeout
:
686 printNicely("-- Timeout --")
687 elif tweet
is HeartbeatTimeout
:
688 printNicely("-- Heartbeat Timeout --")
689 elif tweet
is Hangup
:
690 printNicely("-- Hangup --")
691 elif tweet
.get('text'):
694 iot
=args
.image_on_term
,
695 keyword
=args
.track_keywords
,
705 # Spawn stream process
706 args
= parse_arguments()
708 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
711 # Start listen process
715 g
['stream_pid'] = p
.pid
716 g
['iot'] = args
.image_on_term