91c115cdce61f2279242b4dac35dd873083e0845
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
26 from .consumer
import *
27 from .interactive
import *
29 from .c_image
import *
68 def parse_arguments():
72 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
76 help='Timeout for the stream (seconds).')
79 '--heartbeat-timeout',
80 help='Set heartbeat timeout.',
86 help='Set stream to non-blocking.')
90 help='Search the stream for specific text.')
94 help='Filter specific screen_name.')
98 help='Ignore specific screen_name.')
103 help='Display all image on terminal.')
104 return parser
.parse_args()
109 Authenticate with Twitter OAuth
111 # When using rainbow stream you must authorize.
112 twitter_credential
= os
.environ
.get(
116 '')) + os
.sep
+ '.rainbow_oauth'
117 if not os
.path
.exists(twitter_credential
):
118 oauth_dance("Rainbow Stream",
122 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
130 def get_decorated_name():
132 Beginning of every line
134 t
= Twitter(auth
=authen())
135 name
= '@' + t
.account
.verify_credentials()['screen_name']
136 g
['original_name'] = name
[1:]
137 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
145 target
= g
['stuff'].split()[0]
148 args
= parse_arguments()
150 if g
['stuff'].split()[-1] == '-f':
151 only
= raw_input('Only nicks: ')
152 ignore
= raw_input('Ignore nicks: ')
153 args
.filter = filter(None, only
.split(','))
154 args
.ignore
= filter(None, ignore
.split(','))
155 elif g
['stuff'].split()[-1] == '-d':
156 args
.filter = ONLY_LIST
157 args
.ignore
= IGNORE_LIST
159 printNicely(red('Sorry, wrong format.'))
163 if target
== 'public':
164 keyword
= g
['stuff'].split()[1]
165 if keyword
[0] == '#':
166 keyword
= keyword
[1:]
168 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
169 args
.track_keywords
= keyword
177 g
['stream_pid'] = p
.pid
180 elif target
== 'mine':
182 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
191 g
['stream_pid'] = p
.pid
193 printNicely(green('Stream switched.'))
195 printNicely(cyan('Only: ' + str(args
.filter)))
197 printNicely(red('Ignore: ' + str(args
.ignore
)))
200 printNicely(red('Sorry I can\'t understand.'))
207 t
= Twitter(auth
=authen())
208 # Get country and town
210 country
= g
['stuff'].split()[0]
214 town
= g
['stuff'].split()[1]
218 avail
= t
.trends
.available()
221 trends
= t
.trends
.place(_id
=1)[0]['trends']
224 for location
in avail
:
225 # Search for country and Town
227 if location
['countryCode'] == country \
228 and location
['placeType']['name'] == 'Town' \
229 and location
['name'] == town
:
230 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
232 # Search for country only
234 if location
['countryCode'] == country \
235 and location
['placeType']['name'] == 'Country':
236 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
244 t
= Twitter(auth
=authen())
246 if g
['stuff'].isdigit():
247 num
= int(g
['stuff'])
248 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
249 draw(t
=tweet
, iot
=g
['iot'])
257 t
= Twitter(auth
=authen())
258 user
= g
['stuff'].split()[0]
261 num
= int(g
['stuff'].split()[1])
264 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
265 draw(t
=tweet
, iot
=g
['iot'])
268 printNicely(red('A name should begin with a \'@\''))
275 t
= Twitter(auth
=authen())
277 if g
['stuff'].isdigit():
278 num
= int(g
['stuff'])
279 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
280 draw(t
=tweet
, iot
=g
['iot'])
288 t
= Twitter(auth
=authen())
289 t
.statuses
.update(status
=g
['stuff'])
296 t
= Twitter(auth
=authen())
298 id = int(g
['stuff'].split()[0])
300 printNicely(red('Sorry I can\'t understand.'))
302 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
303 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
310 t
= Twitter(auth
=authen())
313 id = int(g
['stuff'].split()[0])
315 printNicely(red('Sorry I can\'t understand.'))
317 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
318 # Get display num if exist
320 num
= int(g
['stuff'].split()[1])
322 num
= RETWEETS_SHOW_NUM
323 # Get result and display
324 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
326 printNicely(magenta('This tweet has no retweet.'))
328 for tweet
in reversed(rt_ary
):
329 draw(t
=tweet
, iot
=g
['iot'])
337 t
= Twitter(auth
=authen())
339 id = int(g
['stuff'].split()[0])
341 printNicely(red('Sorry I can\'t understand.'))
343 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
344 t
.favorites
.create(_id
=tid
, include_entities
=False)
345 printNicely(green('Favorited.'))
346 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
354 t
= Twitter(auth
=authen())
356 id = int(g
['stuff'].split()[0])
358 printNicely(red('Sorry I can\'t understand.'))
360 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
361 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
362 status
= ' '.join(g
['stuff'].split()[1:])
363 status
= '@' + user
+ ' ' + status
.decode('utf-8')
364 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
371 t
= Twitter(auth
=authen())
373 rid
= int(g
['stuff'].split()[0])
375 printNicely(red('Sorry I can\'t understand.'))
377 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
378 t
.statuses
.destroy(id=tid
)
379 printNicely(green('Okay it\'s gone.'))
386 t
= Twitter(auth
=authen())
388 id = int(g
['stuff'].split()[0])
390 printNicely(red('Sorry I can\'t understand.'))
392 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
393 t
.favorites
.destroy(_id
=tid
)
394 printNicely(green('Okay it\'s unfavorited.'))
395 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
403 t
= Twitter(auth
=authen())
404 if g
['stuff'].startswith('#'):
405 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
407 printNicely('Newest tweets:')
408 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
411 keyword
=g
['stuff'].strip()[1:])
414 printNicely(magenta('I\'m afraid there is no result'))
416 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
421 Send a direct message
423 t
= Twitter(auth
=authen())
424 user
= g
['stuff'].split()[0]
425 if user
[0].startswith('@'):
427 content
= g
['stuff'].split()[1]
429 printNicely(red('Sorry I can\'t understand.'))
430 t
.direct_messages
.new(
431 screen_name
=user
[1:],
434 printNicely(green('Message sent.'))
436 printNicely(red('A name should begin with a \'@\''))
443 t
= Twitter(auth
=authen())
445 target
= g
['stuff'].split()[0]
446 if target
!= 'image':
448 id = int(g
['stuff'].split()[1])
449 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
450 tweet
= t
.statuses
.show(id=tid
)
451 media
= tweet
['entities']['media']
453 res
= requests
.get(m
['media_url'])
454 img
= Image
.open(StringIO(res
.content
))
457 printNicely(red('Sorry I can\'t show this image.'))
462 List friends for followers
464 t
= Twitter(auth
=authen())
467 name
= g
['stuff'].split()[1]
468 if name
.startswith('@'):
471 printNicely(red('A name should begin with a \'@\''))
472 raise Exception('Invalid name')
474 name
= g
['original_name']
475 # Get list followers or friends
477 target
= g
['stuff'].split()[0]
479 printNicely(red('Omg some syntax is wrong.'))
481 d
= {'fl': 'followers', 'fr': 'friends'}
485 while next_cursor
!= 0:
486 list = getattr(t
, d
[target
]).list(
490 include_entities
=False,
492 for u
in list['users']:
493 rel
[u
['name']] = '@' + u
['screen_name']
494 next_cursor
= list['next_cursor']
496 printNicely('All: ' + str(len(rel
)) + ' people.')
498 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
504 Inbox direct messages
506 t
= Twitter(auth
=authen())
507 num
= MESSAGES_DISPLAY
509 if g
['stuff'].isdigit():
512 # Max message per page is 20 so we have to loop
514 rel
= rel
+ t
.direct_messages(
517 include_entities
=False,
522 rel
= rel
+ t
.direct_messages(
525 include_entities
=False,
529 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
530 for m
in reversed(rel
):
539 t
= Twitter(auth
=authen())
540 num
= MESSAGES_DISPLAY
542 if g
['stuff'].isdigit():
543 num
= int(g
['stuff'])
545 # Max message per page is 20 so we have to loop
547 rel
= rel
+ t
.direct_messages
.sent(
550 include_entities
=False,
555 rel
= rel
+ t
.direct_messages
.sent(
558 include_entities
=False,
562 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
563 for m
in reversed(rel
):
572 t
= Twitter(auth
=authen())
574 rid
= int(g
['stuff'].split()[0])
576 printNicely(red('Sorry I can\'t understand.'))
577 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
578 t
.direct_messages
.destroy(id=mid
)
579 printNicely(green('Message deleted.'))
584 Show profile of a specific user
586 t
= Twitter(auth
=authen())
587 screen_name
= g
['stuff'].split()[0]
588 if screen_name
.startswith('@'):
591 screen_name
=screen_name
[1:],
592 include_entities
=False)
593 show_profile(user
, g
['iot'])
595 printNicely(red('Omg no user.'))
597 printNicely(red('A name should begin with a \'@\''))
604 t
= Twitter(auth
=authen())
605 screen_name
= g
['stuff'].split()[0]
606 if screen_name
.startswith('@'):
607 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
608 printNicely(green('You are following ' + screen_name
+ ' now!'))
610 printNicely(red('A name should begin with a \'@\''))
617 t
= Twitter(auth
=authen())
618 screen_name
= g
['stuff'].split()[0]
619 if screen_name
.startswith('@'):
620 t
.friendships
.destroy(
621 screen_name
=screen_name
[1:],
622 include_entities
=False)
623 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
625 printNicely(red('A name should begin with a \'@\''))
632 t
= Twitter(auth
=authen())
634 screen_name
= g
['stuff'].split()[0]
636 printNicely(red('A name should be specified. '))
638 if screen_name
.startswith('@'):
639 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
640 if isinstance(rel
, dict):
641 printNicely(green(screen_name
+ ' is muted.'))
643 printNicely(red(rel
))
645 printNicely(red('A name should begin with a \'@\''))
652 t
= Twitter(auth
=authen())
654 screen_name
= g
['stuff'].split()[0]
656 printNicely(red('A name should be specified. '))
658 if screen_name
.startswith('@'):
659 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
660 if isinstance(rel
, dict):
661 printNicely(green(screen_name
+ ' is unmuted.'))
663 printNicely(red(rel
))
665 printNicely(red('A name should begin with a \'@\''))
672 t
= Twitter(auth
=authen())
674 d
= {'fl': 'followers', 'fr': 'friends'}
678 while next_cursor
!= 0:
679 list = t
.mutes
.users
.list(
680 screen_name
=g
['original_name'],
683 include_entities
=False,
685 for u
in list['users']:
686 rel
[u
['name']] = '@' + u
['screen_name']
687 next_cursor
= list['next_cursor']
689 printNicely('All: ' + str(len(rel
)) + ' people.')
691 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
699 t
= Twitter(auth
=authen())
700 screen_name
= g
['stuff'].split()[0]
701 if screen_name
.startswith('@'):
703 screen_name
=screen_name
[1:],
704 include_entities
=False,
706 printNicely(green('You blocked ' + screen_name
+ '.'))
708 printNicely(red('A name should begin with a \'@\''))
715 t
= Twitter(auth
=authen())
716 screen_name
= g
['stuff'].split()[0]
717 if screen_name
.startswith('@'):
719 screen_name
=screen_name
[1:],
720 include_entities
=False,
722 printNicely(green('Unblock ' + screen_name
+ ' success!'))
724 printNicely(red('A name should begin with a \'@\''))
729 Report a user as a spam account
731 t
= Twitter(auth
=authen())
732 screen_name
= g
['stuff'].split()[0]
733 if screen_name
.startswith('@'):
735 screen_name
=screen_name
[1:])
736 printNicely(green('You reported ' + screen_name
+ '.'))
738 printNicely(red('Sorry I can\'t understand.'))
746 rel
= os
.popen('cal').read().split('\n')
748 month
= random_rainbow(month
)
750 date
= ' '.join([cycle_color(i
) for i
in date
.split(' ')])
751 today
= str(int(os
.popen('date +\'%d\'').read().strip()))
756 ary
= line
.split(' ')
757 ary
= map(lambda x
: on_grey(x
) if x
== today
else grey(x
), ary
)
766 h
, w
= os
.popen('stty size', 'r').read().split()
770 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
771 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
772 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
773 usage
+= s
+ 'Any update from Twitter will show up ' + \
774 yellow('immediately') + '.\n'
775 usage
+= s
+ 'In addtion, following commands are available right now:\n'
779 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
780 usage
+= s
* 2 + green('trend') + ' will show global trending topics. ' + \
781 'You can try ' + green('trend US') + ' or ' + \
782 green('trend JP Tokyo') + '.\n'
783 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
784 green('home 7') + ' will show 7 tweets.\n'
785 usage
+= s
* 2 + green('mentions') + ' will show mentions timeline. ' + \
786 green('mentions 7') + ' will show 7 mention tweets.\n'
787 usage
+= s
* 2 + green('whois @mdo') + ' will show profile of ' + \
788 magenta('@mdo') + '.\n'
789 usage
+= s
* 2 + green('view @mdo') + \
790 ' will show ' + magenta('@mdo') + '\'s home.\n'
791 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
792 yellow('AKB48') + '" and return 5 newest tweet.\n'
796 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
797 usage
+= s
* 2 + green('t oops ') + \
798 'will tweet "' + yellow('oops') + '" immediately.\n'
800 green('rt 12 ') + ' will retweet to tweet with ' + \
801 yellow('[id=12]') + '.\n'
803 green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
804 yellow('[id=12]') + '.\n'
805 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
806 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
808 green('fav 12 ') + ' will favorite the tweet with ' + \
809 yellow('[id=12]') + '.\n'
811 green('ufav 12 ') + ' will unfavorite tweet with ' + \
812 yellow('[id=12]') + '.\n'
814 green('del 12 ') + ' will delete tweet with ' + \
815 yellow('[id=12]') + '.\n'
816 usage
+= s
* 2 + green('show image 12') + ' will show image in tweet with ' + \
817 yellow('[id=12]') + ' in your OS\'s image viewer.\n'
821 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
822 usage
+= s
* 2 + green('inbox') + ' will show inbox messages. ' + \
823 green('inbox 7') + ' will show newest 7 messages.\n'
824 usage
+= s
* 2 + green('sent') + ' will show sent messages. ' + \
825 green('sent 7') + ' will show newest 7 messages.\n'
826 usage
+= s
* 2 + green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
827 magenta('@dtvd88') + '.\n'
828 usage
+= s
* 2 + green('trash 5') + ' will remove message with ' + \
829 yellow('[message_id=5]') + '.\n'
831 # Follower and following
833 usage
+= s
+ grey(u
'\u266A' + ' Fiends and followers \n')
836 ' will list all followers (people who are following you).\n'
839 ' will list all friends (people who you are following).\n'
840 usage
+= s
* 2 + green('fl @dtvd88') + ' will follow ' + \
841 magenta('@dtvd88') + '.\n'
842 usage
+= s
* 2 + green('ufl @dtvd88') + ' will unfollow ' + \
843 magenta('@dtvd88') + '.\n'
844 usage
+= s
* 2 + green('mute @dtvd88') + ' will mute ' + \
845 magenta('@dtvd88') + '.\n'
846 usage
+= s
* 2 + green('unmute @dtvd88') + ' will unmute ' + \
847 magenta('@dtvd88') + '.\n'
848 usage
+= s
* 2 + green('muting') + ' will list muting users.\n'
849 usage
+= s
* 2 + green('block @dtvd88') + ' will block ' + \
850 magenta('@dtvd88') + '.\n'
851 usage
+= s
* 2 + green('unblock @dtvd88') + ' will unblock ' + \
852 magenta('@dtvd88') + '.\n'
853 usage
+= s
* 2 + green('report @dtvd88') + ' will report ' + \
854 magenta('@dtvd88') + ' as a spam account.\n'
858 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
859 usage
+= s
* 2 + green('switch public #AKB') + \
860 ' will switch to public stream and follow "' + \
861 yellow('AKB') + '" keyword.\n'
862 usage
+= s
* 2 + green('switch mine') + \
863 ' will switch to your personal stream.\n'
864 usage
+= s
* 2 + green('switch mine -f ') + \
865 ' will prompt to enter the filter.\n'
866 usage
+= s
* 3 + yellow('Only nicks') + \
867 ' filter will decide nicks will be INCLUDE ONLY.\n'
868 usage
+= s
* 3 + yellow('Ignore nicks') + \
869 ' filter will decide nicks will be EXCLUDE.\n'
870 usage
+= s
* 2 + green('switch mine -d') + \
871 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
872 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
876 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
877 usage
+= s
* 2 + green('111111 * 9 / 7') + ' or any math expression ' + \
878 'will be evaluate by Python interpreter.\n'
879 usage
+= s
* 2 + 'Even ' + green('cal') + ' will show the calendar' + \
880 ' for current month.\n'
884 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
885 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
886 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
887 usage
+= s
* 2 + green('q') + ' will quit.\n'
891 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
892 usage
+= s
+ 'Have fun and hang tight! \n'
908 os
.system('rm -rf rainbow.db')
909 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
918 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
971 Listen to user's input
976 ['public', 'mine'], # switch
990 ['image'], # show image
1010 init_interactive_shell(d
)
1015 line
= raw_input(g
['decorated_name'])
1019 cmd
= line
.split()[0]
1023 # Save cmd to global variable and call process
1025 g
['stuff'] = ' '.join(line
.split()[1:])
1028 printNicely(red('OMG something is wrong with Twitter right now.'))
1029 # Not redisplay prefix
1030 if cmd
in ['switch', 't', 'rt', 'rep']:
1036 def stream(domain
, args
, name
='Rainbow Stream'):
1044 PUBLIC_DOMAIN
: args
.track_keywords
,
1045 SITE_DOMAIN
: 'Site Stream',
1047 ascii_art(art_dict
[domain
])
1049 # These arguments are optional:
1051 timeout
=args
.timeout
,
1052 block
=not args
.no_block
,
1053 heartbeat_timeout
=args
.heartbeat_timeout
)
1057 if args
.track_keywords
:
1058 query_args
['track'] = args
.track_keywords
1061 stream
= TwitterStream(
1066 if domain
== USER_DOMAIN
:
1067 tweet_iter
= stream
.user(**query_args
)
1068 elif domain
== SITE_DOMAIN
:
1069 tweet_iter
= stream
.site(**query_args
)
1071 if args
.track_keywords
:
1072 tweet_iter
= stream
.statuses
.filter(**query_args
)
1074 tweet_iter
= stream
.statuses
.sample()
1076 # Iterate over the stream.
1077 for tweet
in tweet_iter
:
1079 printNicely("-- None --")
1080 elif tweet
is Timeout
:
1081 printNicely("-- Timeout --")
1082 elif tweet
is HeartbeatTimeout
:
1083 printNicely("-- Heartbeat Timeout --")
1084 elif tweet
is Hangup
:
1085 printNicely("-- Hangup --")
1086 elif tweet
.get('text'):
1089 iot
=args
.image_on_term
,
1090 keyword
=args
.track_keywords
,
1100 # Spawn stream process
1101 args
= parse_arguments()
1102 get_decorated_name()
1103 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
1106 # Start listen process
1110 g
['stream_pid'] = p
.pid
1111 g
['iot'] = args
.image_on_term