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 *
53 def draw(t
, iot
=False, keyword
=None, fil
=[], ig
=[]):
61 screen_name
= t
['user']['screen_name']
62 name
= t
['user']['name']
63 created_at
= t
['created_at']
64 favorited
= t
['favorited']
65 date
= parser
.parse(created_at
)
66 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
67 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
73 urls
= t
['entities']['urls']
75 expanded_url
.append(u
['expanded_url'])
84 media
= t
['entities']['media']
86 media_url
.append(m
['media_url'])
91 screen_name
= '@' + screen_name
92 if fil
and screen_name
not in fil
:
94 if ig
and screen_name
in ig
:
97 res
= db
.tweet_query(tid
)
100 res
= db
.tweet_query(tid
)
101 rid
= res
[0].rainbow_id
104 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
105 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
107 meta
= meta
+ green(u
'\u2605')
111 for index
in range(len(expanded_url
)):
113 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
116 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
117 # Highlight screen_name
118 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
120 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
121 # Highlight search keyword
124 lambda x
: on_yellow(x
) if
125 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
130 tweet
= ' '.join(tweet
)
133 line1
= u
"{u:>{uw}}:".format(
137 line2
= u
"{c:>{cw}}".format(
149 if iot
and media_url
:
151 response
= requests
.get(mu
)
152 image_to_display(StringIO(response
.content
))
155 def parse_arguments():
159 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
163 help='Timeout for the stream (seconds).')
166 '--heartbeat-timeout',
167 help='Set heartbeat timeout.',
173 help='Set stream to non-blocking.')
177 help='Search the stream for specific text.')
181 help='Filter specific screen_name.')
185 help='Ignore specific screen_name.')
190 help='Display all image on terminal.')
191 return parser
.parse_args()
196 Authenticate with Twitter OAuth
198 # When using rainbow stream you must authorize.
199 twitter_credential
= os
.environ
.get(
203 '')) + os
.sep
+ '.rainbow_oauth'
204 if not os
.path
.exists(twitter_credential
):
205 oauth_dance("Rainbow Stream",
209 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
217 def get_decorated_name():
219 Beginning of every line
221 t
= Twitter(auth
=authen())
222 name
= '@' + t
.account
.verify_credentials()['screen_name']
223 g
['original_name'] = name
[1:]
224 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
232 target
= g
['stuff'].split()[0]
235 args
= parse_arguments()
237 if g
['stuff'].split()[-1] == '-f':
238 only
= raw_input('Only nicks: ')
239 ignore
= raw_input('Ignore nicks: ')
240 args
.filter = filter(None, only
.split(','))
241 args
.ignore
= filter(None, ignore
.split(','))
242 elif g
['stuff'].split()[-1] == '-d':
243 args
.filter = ONLY_LIST
244 args
.ignore
= IGNORE_LIST
246 printNicely(red('Sorry, wrong format.'))
250 if target
== 'public':
251 keyword
= g
['stuff'].split()[1]
252 if keyword
[0] == '#':
253 keyword
= keyword
[1:]
255 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
256 args
.track_keywords
= keyword
264 g
['stream_pid'] = p
.pid
267 elif target
== 'mine':
269 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
278 g
['stream_pid'] = p
.pid
280 printNicely(green('Stream switched.'))
282 printNicely(cyan('Only: ' + str(args
.filter)))
284 printNicely(red('Ignore: ' + str(args
.ignore
)))
287 printNicely(red('Sorry I can\'t understand.'))
294 t
= Twitter(auth
=authen())
296 if g
['stuff'].isdigit():
298 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
299 draw(t
=tweet
, iot
=g
['iot'])
307 t
= Twitter(auth
=authen())
308 user
= g
['stuff'].split()[0]
311 num
= int(g
['stuff'].split()[1])
314 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
315 draw(t
=tweet
, iot
=g
['iot'])
318 printNicely(red('A name should begin with a \'@\''))
325 t
= Twitter(auth
=authen())
326 t
.statuses
.update(status
=g
['stuff'])
333 t
= Twitter(auth
=authen())
335 id = int(g
['stuff'].split()[0])
336 tid
= db
.rainbow_query(id)[0].tweet_id
337 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
339 printNicely(red('Sorry I can\'t retweet for you.'))
346 t
= Twitter(auth
=authen())
348 id = int(g
['stuff'].split()[0])
349 tid
= db
.rainbow_query(id)[0].tweet_id
350 t
.favorites
.create(_id
=tid
, include_entities
=False)
351 printNicely(green('Favorited.'))
352 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
354 printNicely(red('Omg some syntax is wrong.'))
361 t
= Twitter(auth
=authen())
363 id = int(g
['stuff'].split()[0])
364 tid
= db
.rainbow_query(id)[0].tweet_id
365 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
366 status
= ' '.join(g
['stuff'].split()[1:])
367 status
= '@' + user
+ ' ' + status
.decode('utf-8')
368 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
370 printNicely(red('Sorry I can\'t understand.'))
377 t
= Twitter(auth
=authen())
379 id = int(g
['stuff'].split()[0])
380 tid
= db
.rainbow_query(id)[0].tweet_id
381 t
.statuses
.destroy(id=tid
)
382 printNicely(green('Okay it\'s gone.'))
384 printNicely(red('Sorry I can\'t delete this tweet for you.'))
391 t
= Twitter(auth
=authen())
393 id = int(g
['stuff'].split()[0])
394 tid
= db
.rainbow_query(id)[0].tweet_id
395 t
.favorites
.destroy(_id
=tid
)
396 printNicely(green('Okay it\'s unfavorited.'))
397 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
399 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
406 t
= Twitter(auth
=authen())
408 if g
['stuff'][0] == '#':
409 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
411 printNicely('Newest tweets:')
412 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
415 keyword
=g
['stuff'].strip()[1:])
418 printNicely(magenta('I\'m afraid there is no result'))
420 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
422 printNicely(red('Sorry I can\'t understand.'))
429 t
= Twitter(auth
=authen())
431 target
= g
['stuff'].split()[0]
432 if target
!= 'image':
434 id = int(g
['stuff'].split()[1])
435 tid
= db
.rainbow_query(id)[0].tweet_id
436 tweet
= t
.statuses
.show(id=tid
)
437 media
= tweet
['entities']['media']
439 res
= requests
.get(m
['media_url'])
440 img
= Image
.open(StringIO(res
.content
))
443 printNicely(red('Sorry I can\'t show this image.'))
448 List friends for followers
450 t
= Twitter(auth
=authen())
452 target
= g
['stuff'].split()[0]
453 d
= {'fl': 'followers', 'fr': 'friends'}
457 while next_cursor
!= 0:
458 list = getattr(t
, d
[target
]).list(screen_name
=g
['original_name'],
461 include_entities
=False,
463 for u
in list['users']:
464 rel
[u
['name']] = '@' + u
['screen_name']
465 next_cursor
= list['next_cursor']
467 printNicely('All: ' + str(len(rel
)) + ' people.')
469 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
472 printNicely(red('Omg some syntax is wrong.'))
479 t
= Twitter(auth
=authen())
480 screen_name
= g
['stuff'].split()[0]
481 if screen_name
[0] == '@':
483 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
484 printNicely(green('You are following ' + screen_name
+ ' now!'))
486 printNicely(red('Sorry can not follow at this time.'))
488 printNicely(red('Sorry I can\'t understand.'))
495 t
= Twitter(auth
=authen())
496 screen_name
= g
['stuff'].split()[0]
497 if screen_name
[0] == '@':
499 t
.friendships
.destroy(
500 screen_name
=screen_name
[
502 include_entities
=False)
503 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
505 printNicely(red('Sorry can not unfollow at this time.'))
507 printNicely(red('Sorry I can\'t understand.'))
515 h
, w
= os
.popen('stty size', 'r').read().split()
518 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
519 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
521 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
522 usage
+= s
* 2 + green('switch public #AKB') + \
523 ' will switch to public stream and follow "' + \
524 yellow('AKB') + '" keyword.\n'
525 usage
+= s
* 2 + green('switch mine') + \
526 ' will switch to your personal stream.\n'
527 usage
+= s
* 2 + green('switch mine -f ') + \
528 ' will prompt to enter the filter.\n'
529 usage
+= s
* 3 + yellow('Only nicks') + \
530 ' filter will decide nicks will be INCLUDE ONLY.\n'
531 usage
+= s
* 3 + yellow('Ignore nicks') + \
532 ' filter will decide nicks will be EXCLUDE.\n'
533 usage
+= s
* 2 + green('switch mine -d') + \
534 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
535 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
537 usage
+= s
+ 'For more action: \n'
538 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
539 green('home 7') + ' will show 7 tweet.\n'
540 usage
+= s
* 2 + green('view @mdo') + \
541 ' will show ' + yellow('@mdo') + '\'s home.\n'
542 usage
+= s
* 2 + green('t oops ') + \
543 'will tweet "' + yellow('oops') + '" immediately.\n'
545 green('rt 12 ') + ' will retweet to tweet with ' + \
546 yellow('[id=12]') + '.\n'
548 green('fav 12 ') + ' will favorite the tweet with ' + \
549 yellow('[id=12]') + '.\n'
550 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
551 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
553 green('del 12 ') + ' will delete tweet with ' + \
554 yellow('[id=12]') + '.\n'
556 green('ufav 12 ') + ' will unfavorite tweet with ' + \
557 yellow('[id=12]') + '.\n'
558 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
559 yellow('AKB48') + '" and return 5 newest tweet.\n'
560 usage
+= s
* 2 + green('show image 12') + ' will show image in tweet with ' + \
561 yellow('[id=12]') + ' in your OS\'s image viewer.\n'
564 ' will list all followers (people who are following you).\n'
567 ' will list all friends (people who you are following).\n'
568 usage
+= s
* 2 + green('fl @dtvd88') + ' will follow ' + \
569 yellow('@dtvd88') + '.\n'
570 usage
+= s
* 2 + green('ufl @dtvd88') + ' will unfollow ' + \
571 yellow('@dtvd88') + '.\n'
572 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
573 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
574 usage
+= s
* 2 + green('q') + ' will quit.\n'
576 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
577 usage
+= s
+ 'Have fun and hang tight!\n'
593 os
.system('rm -rf rainbow.db')
594 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
603 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
637 Listen to user's input
642 ['public', 'mine'], # switch
652 ['image'], # show image
653 ['fl', 'fr'], # show image
661 init_interactive_shell(d
)
666 line
= raw_input(g
['decorated_name'])
670 cmd
= line
.split()[0]
673 # Save cmd to global variable and call process
674 g
['stuff'] = ' '.join(line
.split()[1:])
676 if cmd
in ['switch', 't', 'rt', 'rep']:
682 def stream(domain
, args
, name
='Rainbow Stream'):
690 PUBLIC_DOMAIN
: args
.track_keywords
,
691 SITE_DOMAIN
: 'Site Stream',
693 ascii_art(art_dict
[domain
])
695 # These arguments are optional:
697 timeout
=args
.timeout
,
698 block
=not args
.no_block
,
699 heartbeat_timeout
=args
.heartbeat_timeout
)
703 if args
.track_keywords
:
704 query_args
['track'] = args
.track_keywords
707 stream
= TwitterStream(
712 if domain
== USER_DOMAIN
:
713 tweet_iter
= stream
.user(**query_args
)
714 elif domain
== SITE_DOMAIN
:
715 tweet_iter
= stream
.site(**query_args
)
717 if args
.track_keywords
:
718 tweet_iter
= stream
.statuses
.filter(**query_args
)
720 tweet_iter
= stream
.statuses
.sample()
722 # Iterate over the stream.
723 for tweet
in tweet_iter
:
725 printNicely("-- None --")
726 elif tweet
is Timeout
:
727 printNicely("-- Timeout --")
728 elif tweet
is HeartbeatTimeout
:
729 printNicely("-- Heartbeat Timeout --")
730 elif tweet
is Hangup
:
731 printNicely("-- Hangup --")
732 elif tweet
.get('text'):
735 iot
=args
.image_on_term
,
736 keyword
=args
.track_keywords
,
746 # Spawn stream process
747 args
= parse_arguments()
749 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
752 # Start listen process
756 g
['stream_pid'] = p
.pid
757 g
['iot'] = args
.image_on_term