2 Colorful user's timeline stream
4 from multiprocessing
import Process
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
24 from .consumer
import *
25 from .interactive
import *
27 from .c_image
import *
28 from .py3patch
import *
78 def parse_arguments():
82 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
86 help='Timeout for the stream (seconds).')
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
96 help='Set stream to non-blocking.')
100 help='Search the stream for specific text.')
104 help='Filter specific screen_name.')
108 help='Ignore specific screen_name.')
113 help='Display all image on terminal.')
114 return parser
.parse_args()
119 Authenticate with Twitter OAuth
121 # When using rainbow stream you must authorize.
122 twitter_credential
= os
.environ
.get(
126 '')) + os
.sep
+ '.rainbow_oauth'
127 if not os
.path
.exists(twitter_credential
):
128 oauth_dance("Rainbow Stream",
132 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
145 t
= Twitter(auth
=authen())
146 name
= '@' + t
.account
.verify_credentials()['screen_name']
147 g
['original_name'] = name
[1:]
148 g
['decorated_name'] = color_func(c
['DECORATED_NAME'])('[' + name
+ ']: ')
150 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
151 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
153 db
.theme_store(c
['THEME'])
155 db
.semaphore_store(False)
157 c
['IMAGE_ON_TERM'] = args
.image_on_term
164 target
= g
['stuff'].split()[0]
166 args
= parse_arguments()
168 if g
['stuff'].split()[-1] == '-f':
169 guide
= 'To ignore an option, just hit Enter key.'
170 printNicely(light_magenta(guide
))
171 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
172 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
173 args
.filter = filter(None, only
.split(','))
174 args
.ignore
= filter(None, ignore
.split(','))
175 elif g
['stuff'].split()[-1] == '-d':
176 args
.filter = c
['ONLY_LIST']
177 args
.ignore
= c
['IGNORE_LIST']
179 printNicely(red('Sorry, wrong format.'))
182 if target
== 'public':
183 keyword
= g
['stuff'].split()[1]
184 if keyword
[0] == '#':
185 keyword
= keyword
[1:]
187 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
188 args
.track_keywords
= keyword
196 g
['stream_pid'] = p
.pid
198 elif target
== 'mine':
200 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
209 g
['stream_pid'] = p
.pid
212 printNicely(cyan('Only: ' + str(args
.filter)))
214 printNicely(red('Ignore: ' + str(args
.ignore
)))
217 printNicely(red('Sorry I can\'t understand.'))
224 t
= Twitter(auth
=authen())
225 # Get country and town
227 country
= g
['stuff'].split()[0]
231 town
= g
['stuff'].split()[1]
234 avail
= t
.trends
.available()
237 trends
= t
.trends
.place(_id
=1)[0]['trends']
240 for location
in avail
:
241 # Search for country and Town
243 if location
['countryCode'] == country \
244 and location
['placeType']['name'] == 'Town' \
245 and location
['name'] == town
:
246 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
248 # Search for country only
250 if location
['countryCode'] == country \
251 and location
['placeType']['name'] == 'Country':
252 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
260 t
= Twitter(auth
=authen())
261 num
= c
['HOME_TWEET_NUM']
262 if g
['stuff'].isdigit():
263 num
= int(g
['stuff'])
264 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
273 t
= Twitter(auth
=authen())
274 user
= g
['stuff'].split()[0]
277 num
= int(g
['stuff'].split()[1])
279 num
= c
['HOME_TWEET_NUM']
280 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
284 printNicely(red('A name should begin with a \'@\''))
291 t
= Twitter(auth
=authen())
292 num
= c
['HOME_TWEET_NUM']
293 if g
['stuff'].isdigit():
294 num
= int(g
['stuff'])
295 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
304 t
= Twitter(auth
=authen())
305 t
.statuses
.update(status
=g
['stuff'])
312 t
= Twitter(auth
=authen())
314 id = int(g
['stuff'].split()[0])
316 printNicely(red('Sorry I can\'t understand.'))
318 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
319 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
326 t
= Twitter(auth
=authen())
328 id = int(g
['stuff'].split()[0])
330 printNicely(red('Sorry I can\'t understand.'))
332 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
333 tweet
= t
.statuses
.show(id=tid
)
334 screen_name
= tweet
['user']['screen_name']
336 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
337 quote
= quote
.encode('utf8')
338 notice
= light_magenta('Compose mode ')
339 notice
+= light_yellow('(Enter nothing will cancel the quote)')
340 notice
+= light_magenta(':')
342 extra
= raw_input(quote
)
344 t
.statuses
.update(status
=quote
+ extra
)
346 printNicely(light_magenta('No text added.'))
353 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 # Get display num if exist
363 num
= int(g
['stuff'].split()[1])
365 num
= c
['RETWEETS_SHOW_NUM']
366 # Get result and display
367 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
369 printNicely(magenta('This tweet has no retweet.'))
371 for tweet
in reversed(rt_ary
):
380 t
= Twitter(auth
=authen())
382 id = int(g
['stuff'].split()[0])
384 printNicely(red('Sorry I can\'t understand.'))
386 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
387 t
.favorites
.create(_id
=tid
, include_entities
=False)
388 printNicely(green('Favorited.'))
389 draw(t
.statuses
.show(id=tid
))
397 t
= Twitter(auth
=authen())
399 id = int(g
['stuff'].split()[0])
401 printNicely(red('Sorry I can\'t understand.'))
403 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
404 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
405 status
= ' '.join(g
['stuff'].split()[1:])
406 status
= '@' + user
+ ' ' + status
.decode('utf-8')
407 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
414 t
= Twitter(auth
=authen())
416 rid
= int(g
['stuff'].split()[0])
418 printNicely(red('Sorry I can\'t understand.'))
420 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
421 t
.statuses
.destroy(id=tid
)
422 printNicely(green('Okay it\'s gone.'))
429 t
= Twitter(auth
=authen())
431 id = int(g
['stuff'].split()[0])
433 printNicely(red('Sorry I can\'t understand.'))
435 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
436 t
.favorites
.destroy(_id
=tid
)
437 printNicely(green('Okay it\'s unfavorited.'))
438 draw(t
.statuses
.show(id=tid
))
446 t
= Twitter(auth
=authen())
447 g
['stuff'] = g
['stuff'].strip()
448 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
450 printNicely('Newest tweets:')
451 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
456 printNicely(magenta('I\'m afraid there is no result'))
461 Send a direct message
463 t
= Twitter(auth
=authen())
464 user
= g
['stuff'].split()[0]
465 if user
[0].startswith('@'):
467 content
= g
['stuff'].split()[1]
469 printNicely(red('Sorry I can\'t understand.'))
470 t
.direct_messages
.new(
471 screen_name
=user
[1:],
474 printNicely(green('Message sent.'))
476 printNicely(red('A name should begin with a \'@\''))
483 t
= Twitter(auth
=authen())
485 target
= g
['stuff'].split()[0]
486 if target
!= 'image':
488 id = int(g
['stuff'].split()[1])
489 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
490 tweet
= t
.statuses
.show(id=tid
)
491 media
= tweet
['entities']['media']
493 res
= requests
.get(m
['media_url'])
494 img
= Image
.open(BytesIO(res
.content
))
497 printNicely(red('Sorry I can\'t show this image.'))
504 t
= Twitter(auth
=authen())
506 if not g
['stuff'].isdigit():
508 tid
= db
.rainbow_to_tweet_query(g
['stuff'])[0].tweet_id
509 tweet
= t
.statuses
.show(id=tid
)
511 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
513 printNicely(light_magenta('No url here @.@!'))
515 for link
in link_ary
:
516 webbrowser
.open(link
)
518 printNicely(red('Sorry I can\'t open url in this tweet.'))
523 List friends for followers
525 t
= Twitter(auth
=authen())
528 name
= g
['stuff'].split()[1]
529 if name
.startswith('@'):
532 printNicely(red('A name should begin with a \'@\''))
533 raise Exception('Invalid name')
535 name
= g
['original_name']
536 # Get list followers or friends
538 target
= g
['stuff'].split()[0]
540 printNicely(red('Omg some syntax is wrong.'))
542 d
= {'fl': 'followers', 'fr': 'friends'}
546 while next_cursor
!= 0:
547 list = getattr(t
, d
[target
]).list(
551 include_entities
=False,
553 for u
in list['users']:
554 rel
[u
['name']] = '@' + u
['screen_name']
555 next_cursor
= list['next_cursor']
557 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
559 user
= ' ' + cycle_color(name
)
560 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
566 Inbox direct messages
568 t
= Twitter(auth
=authen())
569 num
= c
['MESSAGES_DISPLAY']
571 if g
['stuff'].isdigit():
574 # Max message per page is 20 so we have to loop
576 rel
= rel
+ t
.direct_messages(
579 include_entities
=False,
584 rel
= rel
+ t
.direct_messages(
587 include_entities
=False,
591 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
592 for m
in reversed(rel
):
601 t
= Twitter(auth
=authen())
602 num
= c
['MESSAGES_DISPLAY']
604 if g
['stuff'].isdigit():
605 num
= int(g
['stuff'])
607 # Max message per page is 20 so we have to loop
609 rel
= rel
+ t
.direct_messages
.sent(
612 include_entities
=False,
617 rel
= rel
+ t
.direct_messages
.sent(
620 include_entities
=False,
624 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
625 for m
in reversed(rel
):
634 t
= Twitter(auth
=authen())
636 rid
= int(g
['stuff'].split()[0])
638 printNicely(red('Sorry I can\'t understand.'))
639 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
640 t
.direct_messages
.destroy(id=mid
)
641 printNicely(green('Message deleted.'))
646 Show profile of a specific user
648 t
= Twitter(auth
=authen())
649 screen_name
= g
['stuff'].split()[0]
650 if screen_name
.startswith('@'):
653 screen_name
=screen_name
[1:],
654 include_entities
=False)
657 printNicely(red('Omg no user.'))
659 printNicely(red('A name should begin with a \'@\''))
666 t
= Twitter(auth
=authen())
667 screen_name
= g
['stuff'].split()[0]
668 if screen_name
.startswith('@'):
669 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
670 printNicely(green('You are following ' + screen_name
+ ' now!'))
672 printNicely(red('A name should begin with a \'@\''))
679 t
= Twitter(auth
=authen())
680 screen_name
= g
['stuff'].split()[0]
681 if screen_name
.startswith('@'):
682 t
.friendships
.destroy(
683 screen_name
=screen_name
[1:],
684 include_entities
=False)
685 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
687 printNicely(red('A name should begin with a \'@\''))
694 t
= Twitter(auth
=authen())
696 screen_name
= g
['stuff'].split()[0]
698 printNicely(red('A name should be specified. '))
700 if screen_name
.startswith('@'):
701 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
702 if isinstance(rel
, dict):
703 printNicely(green(screen_name
+ ' is muted.'))
705 printNicely(red(rel
))
707 printNicely(red('A name should begin with a \'@\''))
714 t
= Twitter(auth
=authen())
716 screen_name
= g
['stuff'].split()[0]
718 printNicely(red('A name should be specified. '))
720 if screen_name
.startswith('@'):
721 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
722 if isinstance(rel
, dict):
723 printNicely(green(screen_name
+ ' is unmuted.'))
725 printNicely(red(rel
))
727 printNicely(red('A name should begin with a \'@\''))
734 t
= Twitter(auth
=authen())
739 while next_cursor
!= 0:
740 list = t
.mutes
.users
.list(
741 screen_name
=g
['original_name'],
744 include_entities
=False,
746 for u
in list['users']:
747 rel
[u
['name']] = '@' + u
['screen_name']
748 next_cursor
= list['next_cursor']
750 printNicely('All: ' + str(len(rel
)) + ' people.')
752 user
= ' ' + cycle_color(name
)
753 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
761 t
= Twitter(auth
=authen())
762 screen_name
= g
['stuff'].split()[0]
763 if screen_name
.startswith('@'):
765 screen_name
=screen_name
[1:],
766 include_entities
=False,
768 printNicely(green('You blocked ' + screen_name
+ '.'))
770 printNicely(red('A name should begin with a \'@\''))
777 t
= Twitter(auth
=authen())
778 screen_name
= g
['stuff'].split()[0]
779 if screen_name
.startswith('@'):
781 screen_name
=screen_name
[1:],
782 include_entities
=False,
784 printNicely(green('Unblock ' + screen_name
+ ' success!'))
786 printNicely(red('A name should begin with a \'@\''))
791 Report a user as a spam account
793 t
= Twitter(auth
=authen())
794 screen_name
= g
['stuff'].split()[0]
795 if screen_name
.startswith('@'):
797 screen_name
=screen_name
[1:])
798 printNicely(green('You reported ' + screen_name
+ '.'))
800 printNicely(red('Sorry I can\'t understand.'))
808 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
809 # Get list name and owner
811 owner
, slug
= list_name
.split('/')
812 if slug
.startswith('@'):
817 light_magenta('List name should follow "@owner/list_name" format.'))
818 raise Exception('Wrong list name')
825 rel
= t
.lists
.list(screen_name
=g
['original_name'])
829 printNicely(light_magenta('You belong to no lists :)'))
836 owner
, slug
= get_slug()
837 res
= t
.lists
.statuses(
839 owner_screen_name
=owner
,
841 include_entities
=False)
851 owner
, slug
= get_slug()
855 while next_cursor
!= 0:
858 owner_screen_name
=owner
,
860 include_entities
=False)
862 rel
[u
['name']] = '@' + u
['screen_name']
863 next_cursor
= m
['next_cursor']
864 printNicely('All: ' + str(len(rel
)) + ' members.')
866 user
= ' ' + cycle_color(name
)
867 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
871 def list_subscribers(t
):
875 owner
, slug
= get_slug()
879 while next_cursor
!= 0:
880 m
= t
.lists
.subscribers(
882 owner_screen_name
=owner
,
884 include_entities
=False)
886 rel
[u
['name']] = '@' + u
['screen_name']
887 next_cursor
= m
['next_cursor']
888 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
890 user
= ' ' + cycle_color(name
)
891 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
897 Add specific user to a list
899 owner
, slug
= get_slug()
901 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
902 if user_name
.startswith('@'):
903 user_name
= user_name
[1:]
905 t
.lists
.members
.create(
907 owner_screen_name
=owner
,
908 screen_name
=user_name
)
909 printNicely(light_green('Added.'))
911 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
916 Remove specific user from a list
918 owner
, slug
= get_slug()
920 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
921 if user_name
.startswith('@'):
922 user_name
= user_name
[1:]
924 t
.lists
.members
.destroy(
926 owner_screen_name
=owner
,
927 screen_name
=user_name
)
928 printNicely(light_green('Gone.'))
930 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
933 def list_subscribe(t
):
937 owner
, slug
= get_slug()
940 t
.lists
.subscribers
.create(
942 owner_screen_name
=owner
)
943 printNicely(light_green('Done.'))
946 light_magenta('I\'m sorry you can not subscribe to this list.'))
949 def list_unsubscribe(t
):
953 owner
, slug
= get_slug()
956 t
.lists
.subscribers
.destroy(
958 owner_screen_name
=owner
)
959 printNicely(light_green('Done.'))
962 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
971 while next_cursor
!= 0:
972 res
= t
.lists
.ownerships(
973 screen_name
=g
['original_name'],
976 next_cursor
= res
['next_cursor']
980 printNicely(light_magenta('You own no lists :)'))
987 name
= raw_input(light_magenta('New list\'s name: '))
988 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
989 description
= raw_input(light_magenta('New list\'s description: '))
994 description
=description
)
995 printNicely(light_green(name
+ ' list is created.'))
997 printNicely(red('Oops something is wrong with Twitter :('))
1004 slug
= raw_input(light_magenta('Your list that you want to update: '))
1005 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1006 mode
= raw_input(light_magenta('Update mode (public/private): '))
1007 description
= raw_input(light_magenta('Update description: '))
1011 slug
='-'.join(slug
.split()),
1012 owner_screen_name
=g
['original_name'],
1015 description
=description
)
1019 owner_screen_name
=g
['original_name'],
1021 description
=description
)
1022 printNicely(light_green(slug
+ ' list is updated.'))
1024 printNicely(red('Oops something is wrong with Twitter :('))
1031 slug
= raw_input(light_magenta('Your list that you want to update: '))
1034 slug
='-'.join(slug
.split()),
1035 owner_screen_name
=g
['original_name'])
1036 printNicely(light_green(slug
+ ' list is deleted.'))
1038 printNicely(red('Oops something is wrong with Twitter :('))
1045 t
= Twitter(auth
=authen())
1046 # List all lists or base on action
1048 g
['list_action'] = g
['stuff'].split()[0]
1055 'all_mem': list_members
,
1056 'all_sub': list_subscribers
,
1059 'sub': list_subscribe
,
1060 'unsub': list_unsubscribe
,
1063 'update': list_update
,
1067 return action_ary
[g
['list_action']](t
)
1069 printNicely(red('Please try again.'))
1074 Unix's command `cal`
1077 rel
= os
.popen('cal').read().split('\n')
1080 show_calendar(month
, date
, rel
)
1085 Browse and change config
1087 all_config
= get_all_config()
1088 g
['stuff'] = g
['stuff'].strip()
1091 for k
in all_config
:
1093 light_green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1095 guide
= 'Detailed explanation can be found at ' + \
1096 color_func(c
['TWEET']['link'])(
1097 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1099 # Print specific config
1100 elif len(g
['stuff'].split()) == 1:
1101 if g
['stuff'] in all_config
:
1104 light_green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1107 printNicely(red('No such config key.'))
1108 # Print specific config's default value
1109 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1110 key
= g
['stuff'].split()[0]
1112 value
= get_default_config(key
)
1113 line
= ' ' * 2 + light_green(key
) + ': ' + light_magenta(value
)
1116 printNicely(light_magenta('This config key does not exist in default.'))
1117 # Delete specific config key in config file
1118 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1119 key
= g
['stuff'].split()[0]
1122 printNicely(light_green('Config key is dropped.'))
1124 printNicely(red('No such config key.'))
1125 # Set specific config
1126 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1127 key
= g
['stuff'].split()[0]
1128 value
= g
['stuff'].split()[-1]
1130 set_config(key
, value
)
1131 printNicely(light_green('Updated successfully.'))
1133 printNicely(light_magenta('Not valid value.'))
1137 printNicely(light_magenta('Sorry I can\'s understand.'))
1142 List and change theme
1146 for theme
in g
['themes']:
1147 line
= light_magenta(theme
)
1148 if c
['THEME'] == theme
:
1149 line
= ' ' * 2 + light_yellow('* ') + line
1151 line
= ' ' * 4 + line
1153 elif g
['stuff'] == 'current_as_default':
1155 set_config('THEME', c
['THEME'])
1156 printNicely(light_green('Okay it will be applied from next time :)'))
1161 if g
['stuff'] != 'custom':
1162 new_config
= os
.path
.dirname(
1163 __file__
) + '/colorset/' + g
['stuff'] + '.json'
1165 new_config
= os
.environ
.get(
1166 'HOME', os
.environ
.get(
1168 '')) + os
.sep
+ '.rainbow_config.json'
1169 new_config
= load_config(new_config
)
1171 for nc
in new_config
:
1172 c
[nc
] = new_config
[nc
]
1173 # Update db and reset colors
1174 db
.theme_update(g
['stuff'])
1175 c
['THEME'] = g
['stuff']
1177 g
['decorated_name'] = color_func(
1178 c
['DECORATED_NAME'])(
1179 '[@' + g
['original_name'] + ']: ')
1180 printNicely(green('Theme changed.'))
1182 printNicely(red('No such theme exists.'))
1185 def help_discover():
1190 # Discover the world
1192 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1193 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1194 'You can try ' + light_green('trend US') + ' or ' + \
1195 light_green('trend JP Tokyo') + '.\n'
1196 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1197 light_green('home 7') + ' will show 7 tweets.\n'
1198 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1199 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1200 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1201 magenta('@mdo') + '.\n'
1202 usage
+= s
* 2 + light_green('view @mdo') + \
1203 ' will show ' + magenta('@mdo') + '\'s home.\n'
1204 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1205 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1206 'Search can be performed with or without hashtag.\n'
1217 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1218 usage
+= s
* 2 + light_green('t oops ') + \
1219 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1221 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1222 light_yellow('[id=12]') + '.\n'
1224 light_green('quote 12 ') + ' will quote the tweet with ' + \
1225 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1226 'the quote will be canceled.\n'
1228 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1229 light_yellow('[id=12]') + '.\n'
1230 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1231 light_yellow('oops') + '" to tweet with ' + \
1232 light_yellow('[id=12]') + '.\n'
1234 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1235 light_yellow('[id=12]') + '.\n'
1237 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1238 light_yellow('[id=12]') + '.\n'
1240 light_green('del 12 ') + ' will delete tweet with ' + \
1241 light_yellow('[id=12]') + '.\n'
1242 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1243 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1244 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1245 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1249 def help_messages():
1256 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1257 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1258 light_green('inbox 7') + ' will show newest 7 messages.\n'
1259 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1260 light_green('sent 7') + ' will show newest 7 messages.\n'
1261 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1262 magenta('@dtvd88') + '.\n'
1263 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1264 light_yellow('[message_id=5]') + '.\n'
1268 def help_friends_and_followers():
1270 Friends and Followers
1273 # Follower and following
1275 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1277 light_green('ls fl') + \
1278 ' will list all followers (people who are following you).\n'
1280 light_green('ls fr') + \
1281 ' will list all friends (people who you are following).\n'
1282 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1283 magenta('@dtvd88') + '.\n'
1284 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1285 magenta('@dtvd88') + '.\n'
1286 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1289 magenta('@dtvd88') + '.\n'
1290 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1291 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1292 magenta('@dtvd88') + '.\n'
1293 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1294 magenta('@dtvd88') + '.\n'
1295 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1296 magenta('@dtvd88') + ' as a spam account.\n'
1307 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1308 usage
+= s
* 2 + light_green('list') + \
1309 ' will show all lists you are belong to.\n'
1310 usage
+= s
* 2 + light_green('list home') + \
1311 ' will show timeline of list. You will be asked for list\'s name.\n'
1312 usage
+= s
* 2 + light_green('list all_mem') + \
1313 ' will show list\'s all members.\n'
1314 usage
+= s
* 2 + light_green('list all_sub') + \
1315 ' will show list\'s all subscribers.\n'
1316 usage
+= s
* 2 + light_green('list add') + \
1317 ' will add specific person to a list owned by you.' + \
1318 ' You will be asked for list\'s name and person\'s name.\n'
1319 usage
+= s
* 2 + light_green('list rm') + \
1320 ' will remove specific person from a list owned by you.' + \
1321 ' You will be asked for list\'s name and person\'s name.\n'
1322 usage
+= s
* 2 + light_green('list sub') + \
1323 ' will subscribe you to a specific list.\n'
1324 usage
+= s
* 2 + light_green('list unsub') + \
1325 ' will unsubscribe you from a specific list.\n'
1326 usage
+= s
* 2 + light_green('list own') + \
1327 ' will show all list owned by you.\n'
1328 usage
+= s
* 2 + light_green('list new') + \
1329 ' will create a new list.\n'
1330 usage
+= s
* 2 + light_green('list update') + \
1331 ' will update a list owned by you.\n'
1332 usage
+= s
* 2 + light_green('list del') + \
1333 ' will delete a list owned by you.\n'
1344 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1345 usage
+= s
* 2 + light_green('switch public #AKB') + \
1346 ' will switch to public stream and follow "' + \
1347 light_yellow('AKB') + '" keyword.\n'
1348 usage
+= s
* 2 + light_green('switch mine') + \
1349 ' will switch to your personal stream.\n'
1350 usage
+= s
* 2 + light_green('switch mine -f ') + \
1351 ' will prompt to enter the filter.\n'
1352 usage
+= s
* 3 + light_yellow('Only nicks') + \
1353 ' filter will decide nicks will be INCLUDE ONLY.\n'
1354 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1355 ' filter will decide nicks will be EXCLUDE.\n'
1356 usage
+= s
* 2 + light_green('switch mine -d') + \
1357 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1366 h
, w
= os
.popen('stty size', 'r').read().split()
1369 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1370 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1371 usage
+= s
+ 'You are ' + \
1372 light_yellow('already') + ' on your personal stream.\n'
1373 usage
+= s
+ 'Any update from Twitter will show up ' + \
1374 light_yellow('immediately') + '.\n'
1375 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1376 # Twitter help section
1378 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1379 usage
+= s
* 2 + light_green('h discover') + \
1380 ' will show help for discover commands.\n'
1381 usage
+= s
* 2 + light_green('h tweets') + \
1382 ' will show help for tweets commands.\n'
1383 usage
+= s
* 2 + light_green('h messages') + \
1384 ' will show help for messages commands.\n'
1385 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1386 ' will show help for friends and followers commands.\n'
1387 usage
+= s
* 2 + light_green('h list') + \
1388 ' will show help for list commands.\n'
1389 usage
+= s
* 2 + light_green('h stream') + \
1390 ' will show help for stream commands.\n'
1393 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1394 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1395 'will be evaluate by Python interpreter.\n'
1396 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1397 ' for current month.\n'
1400 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1401 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1402 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1403 ' theme immediately.\n'
1404 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1406 light_green('config ASCII_ART') + ' will output current value of ' +\
1407 light_yellow('ASCII_ART') + ' config key.\n'
1409 light_green('config TREND_MAX default') + ' will output default value of ' + \
1410 light_yellow('TREND_MAX') + ' config key.\n'
1412 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1413 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1415 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1416 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1417 light_yellow('True') + '.\n'
1420 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1421 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1422 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1423 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1426 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1427 usage
+= s
+ 'Have fun and hang tight! \n'
1430 'discover': help_discover
,
1431 'tweets': help_tweets
,
1432 'messages': help_messages
,
1433 'friends_and_followers': help_friends_and_followers
,
1435 'stream': help_stream
,
1438 d
[g
['stuff'].strip()]()
1455 os
.system('rm -rf rainbow.db')
1456 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
1462 Reset prefix of line
1465 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1468 printNicely(str(eval(g
['cmd'])))
1523 Listen to user's input
1528 ['public', 'mine'], # switch
1543 ['image'], # show image
1545 ['fl', 'fr'], # list
1572 [key
for key
in dict(get_all_config())], # config
1573 g
['themes'] + ['current_as_default'], # theme
1578 'friends_and_followers',
1586 init_interactive_shell(d
)
1591 line
= raw_input(g
['decorated_name'])
1595 cmd
= line
.split()[0]
1600 # Lock the semaphore
1601 db
.semaphore_update(True)
1602 # Save cmd to global variable and call process
1603 g
['stuff'] = ' '.join(line
.split()[1:])
1604 # Process the command
1607 if cmd
in ['switch', 't', 'rt', 'rep']:
1611 # Release the semaphore lock
1612 db
.semaphore_update(False)
1614 printNicely(red('OMG something is wrong with Twitter right now.'))
1617 def stream(domain
, args
, name
='Rainbow Stream'):
1623 c
['USER_DOMAIN']: name
,
1624 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1625 c
['SITE_DOMAIN']: name
,
1628 ascii_art(art_dict
[domain
])
1629 # These arguments are optional:
1631 timeout
=args
.timeout
,
1632 block
=not args
.no_block
,
1633 heartbeat_timeout
=args
.heartbeat_timeout
)
1636 if args
.track_keywords
:
1637 query_args
['track'] = args
.track_keywords
1639 stream
= TwitterStream(
1644 if domain
== c
['USER_DOMAIN']:
1645 tweet_iter
= stream
.user(**query_args
)
1646 elif domain
== c
['SITE_DOMAIN']:
1647 tweet_iter
= stream
.site(**query_args
)
1649 if args
.track_keywords
:
1650 tweet_iter
= stream
.statuses
.filter(**query_args
)
1652 tweet_iter
= stream
.statuses
.sample()
1653 for tweet
in tweet_iter
:
1655 printNicely("-- None --")
1656 elif tweet
is Timeout
:
1657 printNicely("-- Timeout --")
1658 elif tweet
is HeartbeatTimeout
:
1659 printNicely("-- Heartbeat Timeout --")
1660 elif tweet
is Hangup
:
1661 printNicely("-- Hangup --")
1662 elif tweet
.get('text'):
1665 keyword
=args
.track_keywords
,
1666 check_semaphore
=True,
1670 elif tweet
.get('direct_message'):
1671 print_message(tweet
['direct_message'])
1672 except TwitterHTTPError
:
1675 magenta("We have maximum connection problem with twitter'stream API right now :("))
1683 args
= parse_arguments()
1686 except TwitterHTTPError
:
1689 magenta("Something wrong with Twitter Oauth right now :("))
1691 magenta("Please delete ~/.rainbow_oauth and try again."))
1693 os
.system('rm -rf rainbow.db')
1695 # Spawn stream process
1701 g
['original_name']))
1703 # Start listen process
1707 g
['stream_pid'] = p
.pid