2 Colorful user's timeline stream
14 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
15 from twitter
.api
import *
16 from twitter
.oauth
import OAuth
, read_token_file
17 from twitter
.oauth_dance
import oauth_dance
18 from twitter
.util
import printNicely
23 from .consumer
import *
24 from .interactive
import *
25 from .c_image
import *
26 from .py3patch
import *
32 StreamLock
= threading
.Lock()
35 def parse_arguments():
39 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
43 help='Timeout for the stream (seconds).')
47 help='Search the stream for specific text.')
51 help='Filter specific screen_name.')
55 help='Ignore specific screen_name.')
60 help='Display all image on terminal.')
61 return parser
.parse_args()
66 Authenticate with Twitter OAuth
68 # When using rainbow stream you must authorize.
69 twitter_credential
= os
.environ
.get(
73 '')) + os
.sep
+ '.rainbow_oauth'
74 if not os
.path
.exists(twitter_credential
):
75 oauth_dance("Rainbow Stream",
79 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
87 def build_mute_dict(dict_data
=False):
91 t
= Twitter(auth
=authen())
97 while next_cursor
!= 0:
98 list = t
.mutes
.users
.list(
99 screen_name
=g
['original_name'],
102 include_entities
=False,
104 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
105 name_list
+= [u
['name'] for u
in list['users']]
106 next_cursor
= list['next_cursor']
107 # Return dict or list
109 return dict(zip(screen_name_list
, name_list
))
111 return screen_name_list
119 ctrl_c_handler
= lambda signum
, frame
: quit()
120 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
122 t
= Twitter(auth
=authen())
123 name
= '@' + t
.account
.verify_credentials()['screen_name']
124 if not get_config('PREFIX'):
125 set_config('PREFIX', name
)
126 g
['original_name'] = name
[1:]
127 g
['decorated_name'] = lambda x
: color_func(
128 c
['DECORATED_NAME'])('[' + x
+ ']: ')
130 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
131 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
138 # Init tweet dict and message dict
140 c
['message_dict'] = []
142 c
['IMAGE_ON_TERM'] = args
.image_on_term
143 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
145 c
['IGNORE_LIST'] += build_mute_dict()
153 target
= g
['stuff'].split()[0]
155 args
= parse_arguments()
157 if g
['stuff'].split()[-1] == '-f':
158 guide
= 'To ignore an option, just hit Enter key.'
159 printNicely(light_magenta(guide
))
160 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
161 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
162 args
.filter = filter(None, only
.split(','))
163 args
.ignore
= filter(None, ignore
.split(','))
164 elif g
['stuff'].split()[-1] == '-d':
165 args
.filter = c
['ONLY_LIST']
166 args
.ignore
= c
['IGNORE_LIST']
168 printNicely(red('Sorry, wrong format.'))
171 if target
== 'public':
172 keyword
= g
['stuff'].split()[1]
173 if keyword
[0] == '#':
174 keyword
= keyword
[1:]
176 g
['stream_stop'] = True
177 args
.track_keywords
= keyword
179 th
= threading
.Thread(
187 elif target
== 'mine':
189 g
['stream_stop'] = True
191 th
= threading
.Thread(
201 printNicely(cyan('Only: ' + str(args
.filter)))
203 printNicely(red('Ignore: ' + str(args
.ignore
)))
206 printNicely(red('Sorry I can\'t understand.'))
213 t
= Twitter(auth
=authen())
214 # Get country and town
216 country
= g
['stuff'].split()[0]
220 town
= g
['stuff'].split()[1]
223 avail
= t
.trends
.available()
226 trends
= t
.trends
.place(_id
=1)[0]['trends']
229 for location
in avail
:
230 # Search for country and Town
232 if location
['countryCode'] == country \
233 and location
['placeType']['name'] == 'Town' \
234 and location
['name'] == town
:
235 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
237 # Search for country only
239 if location
['countryCode'] == country \
240 and location
['placeType']['name'] == 'Country':
241 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
249 t
= Twitter(auth
=authen())
250 num
= c
['HOME_TWEET_NUM']
251 if g
['stuff'].isdigit():
252 num
= int(g
['stuff'])
253 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
262 t
= Twitter(auth
=authen())
263 user
= g
['stuff'].split()[0]
266 num
= int(g
['stuff'].split()[1])
268 num
= c
['HOME_TWEET_NUM']
269 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
273 printNicely(red('A name should begin with a \'@\''))
280 t
= Twitter(auth
=authen())
281 num
= c
['HOME_TWEET_NUM']
282 if g
['stuff'].isdigit():
283 num
= int(g
['stuff'])
284 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
293 t
= Twitter(auth
=authen())
294 t
.statuses
.update(status
=g
['stuff'])
301 t
= Twitter(auth
=authen())
303 id = int(g
['stuff'].split()[0])
305 printNicely(red('Sorry I can\'t understand.'))
307 tid
= c
['tweet_dict'][id]
308 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
316 t
= Twitter(auth
=authen())
318 id = int(g
['stuff'].split()[0])
320 printNicely(red('Sorry I can\'t understand.'))
322 tid
= c
['tweet_dict'][id]
323 tweet
= t
.statuses
.show(id=tid
)
324 screen_name
= '@' + tweet
['user']['screen_name']
326 # Validate quote format
327 if '#owner' not in c
['QUOTE_FORMAT']:
328 printNicely(light_magenta('Quote should contains #owner'))
330 if '#comment' not in c
['QUOTE_FORMAT']:
331 printNicely(light_magenta('Quote format should have #comment'))
334 notice
= light_magenta('Current quote format is: ')
335 notice
+= light_green(c
['QUOTE_FORMAT'])
340 formater
= c
['QUOTE_FORMAT']
341 formater
= screen_name
.join(formater
.split('#owner'))
342 formater
= text
.join(formater
.split('#tweet'))
343 formater
= u2str(formater
)
347 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
348 comment
= raw_input(prefix
)
350 quote
= comment
.join(formater
.split('#comment'))
351 t
.statuses
.update(status
= quote
)
353 printNicely(light_magenta('No text added.'))
360 t
= Twitter(auth
=authen())
363 id = int(g
['stuff'].split()[0])
365 printNicely(red('Sorry I can\'t understand.'))
367 tid
= c
['tweet_dict'][id]
368 # Get display num if exist
370 num
= int(g
['stuff'].split()[1])
372 num
= c
['RETWEETS_SHOW_NUM']
373 # Get result and display
374 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
376 printNicely(magenta('This tweet has no retweet.'))
378 for tweet
in reversed(rt_ary
):
387 t
= Twitter(auth
=authen())
389 id = int(g
['stuff'].split()[0])
391 printNicely(red('Sorry I can\'t understand.'))
393 tid
= c
['tweet_dict'][id]
394 t
.favorites
.create(_id
=tid
, include_entities
=False)
395 printNicely(green('Favorited.'))
396 draw(t
.statuses
.show(id=tid
))
404 t
= Twitter(auth
=authen())
406 id = int(g
['stuff'].split()[0])
408 printNicely(red('Sorry I can\'t understand.'))
410 tid
= c
['tweet_dict'][id]
411 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
412 status
= ' '.join(g
['stuff'].split()[1:])
413 status
= '@' + user
+ ' ' + str2u(status
)
414 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
421 t
= Twitter(auth
=authen())
423 id = int(g
['stuff'].split()[0])
425 printNicely(red('Sorry I can\'t understand.'))
427 tid
= c
['tweet_dict'][id]
428 t
.statuses
.destroy(id=tid
)
429 printNicely(green('Okay it\'s gone.'))
436 t
= Twitter(auth
=authen())
438 id = int(g
['stuff'].split()[0])
440 printNicely(red('Sorry I can\'t understand.'))
442 tid
= c
['tweet_dict'][id]
443 t
.favorites
.destroy(_id
=tid
)
444 printNicely(green('Okay it\'s unfavorited.'))
445 draw(t
.statuses
.show(id=tid
))
453 t
= Twitter(auth
=authen())
454 g
['stuff'] = g
['stuff'].strip()
455 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
457 printNicely('Newest tweets:')
458 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
463 printNicely(magenta('I\'m afraid there is no result'))
468 Send a direct message
470 t
= Twitter(auth
=authen())
471 user
= g
['stuff'].split()[0]
472 if user
[0].startswith('@'):
474 content
= g
['stuff'].split()[1]
476 printNicely(red('Sorry I can\'t understand.'))
477 t
.direct_messages
.new(
478 screen_name
=user
[1:],
481 printNicely(green('Message sent.'))
483 printNicely(red('A name should begin with a \'@\''))
490 t
= Twitter(auth
=authen())
492 target
= g
['stuff'].split()[0]
493 if target
!= 'image':
495 id = int(g
['stuff'].split()[1])
496 tid
= c
['tweet_dict'][id]
497 tweet
= t
.statuses
.show(id=tid
)
498 media
= tweet
['entities']['media']
500 res
= requests
.get(m
['media_url'])
501 img
= Image
.open(BytesIO(res
.content
))
504 printNicely(red('Sorry I can\'t show this image.'))
511 t
= Twitter(auth
=authen())
513 if not g
['stuff'].isdigit():
515 tid
= c
['tweet_dict'][int(g
['stuff'])]
516 tweet
= t
.statuses
.show(id=tid
)
518 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
520 printNicely(light_magenta('No url here @.@!'))
522 for link
in link_ary
:
523 webbrowser
.open(link
)
525 printNicely(red('Sorry I can\'t open url in this tweet.'))
530 List friends for followers
532 t
= Twitter(auth
=authen())
535 name
= g
['stuff'].split()[1]
536 if name
.startswith('@'):
539 printNicely(red('A name should begin with a \'@\''))
540 raise Exception('Invalid name')
542 name
= g
['original_name']
543 # Get list followers or friends
545 target
= g
['stuff'].split()[0]
547 printNicely(red('Omg some syntax is wrong.'))
549 d
= {'fl': 'followers', 'fr': 'friends'}
553 while next_cursor
!= 0:
554 list = getattr(t
, d
[target
]).list(
558 include_entities
=False,
560 for u
in list['users']:
561 rel
[u
['name']] = '@' + u
['screen_name']
562 next_cursor
= list['next_cursor']
564 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
566 user
= ' ' + cycle_color(name
)
567 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
573 Inbox direct messages
575 t
= Twitter(auth
=authen())
576 num
= c
['MESSAGES_DISPLAY']
578 if g
['stuff'].isdigit():
581 # Max message per page is 20 so we have to loop
583 rel
= rel
+ t
.direct_messages(
586 include_entities
=False,
591 rel
= rel
+ t
.direct_messages(
594 include_entities
=False,
598 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
599 for m
in reversed(rel
):
608 t
= Twitter(auth
=authen())
609 num
= c
['MESSAGES_DISPLAY']
611 if g
['stuff'].isdigit():
612 num
= int(g
['stuff'])
614 # Max message per page is 20 so we have to loop
616 rel
= rel
+ t
.direct_messages
.sent(
619 include_entities
=False,
624 rel
= rel
+ t
.direct_messages
.sent(
627 include_entities
=False,
631 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
632 for m
in reversed(rel
):
641 t
= Twitter(auth
=authen())
643 id = int(g
['stuff'].split()[0])
645 printNicely(red('Sorry I can\'t understand.'))
646 mid
= c
['message_dict'][id]
647 t
.direct_messages
.destroy(id=mid
)
648 printNicely(green('Message deleted.'))
653 Show profile of a specific user
655 t
= Twitter(auth
=authen())
656 screen_name
= g
['stuff'].split()[0]
657 if screen_name
.startswith('@'):
660 screen_name
=screen_name
[1:],
661 include_entities
=False)
664 printNicely(red('Omg no user.'))
666 printNicely(red('A name should begin with a \'@\''))
673 t
= Twitter(auth
=authen())
674 screen_name
= g
['stuff'].split()[0]
675 if screen_name
.startswith('@'):
676 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
677 printNicely(green('You are following ' + screen_name
+ ' now!'))
679 printNicely(red('A name should begin with a \'@\''))
686 t
= Twitter(auth
=authen())
687 screen_name
= g
['stuff'].split()[0]
688 if screen_name
.startswith('@'):
689 t
.friendships
.destroy(
690 screen_name
=screen_name
[1:],
691 include_entities
=False)
692 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
694 printNicely(red('A name should begin with a \'@\''))
701 t
= Twitter(auth
=authen())
703 screen_name
= g
['stuff'].split()[0]
705 printNicely(red('A name should be specified. '))
707 if screen_name
.startswith('@'):
709 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
710 if isinstance(rel
, dict):
711 printNicely(green(screen_name
+ ' is muted.'))
712 c
['IGNORE_LIST'] += [unc(screen_name
)]
713 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
715 printNicely(red(rel
))
717 printNicely(red('Something is wrong, can not mute now :('))
719 printNicely(red('A name should begin with a \'@\''))
726 t
= Twitter(auth
=authen())
728 screen_name
= g
['stuff'].split()[0]
730 printNicely(red('A name should be specified. '))
732 if screen_name
.startswith('@'):
734 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
735 if isinstance(rel
, dict):
736 printNicely(green(screen_name
+ ' is unmuted.'))
737 c
['IGNORE_LIST'].remove(screen_name
)
739 printNicely(red(rel
))
741 printNicely(red('Maybe you are not muting this person ?'))
743 printNicely(red('A name should begin with a \'@\''))
750 # Get dict of muting users
751 md
= build_mute_dict(dict_data
=True)
752 printNicely('All: ' + str(len(md
)) + ' people.')
754 user
= ' ' + cycle_color(md
[name
])
755 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
757 # Update from Twitter
758 c
['IGNORE_LIST'] = [n
for n
in md
]
765 t
= Twitter(auth
=authen())
766 screen_name
= g
['stuff'].split()[0]
767 if screen_name
.startswith('@'):
769 screen_name
=screen_name
[1:],
770 include_entities
=False,
772 printNicely(green('You blocked ' + screen_name
+ '.'))
774 printNicely(red('A name should begin with a \'@\''))
781 t
= Twitter(auth
=authen())
782 screen_name
= g
['stuff'].split()[0]
783 if screen_name
.startswith('@'):
785 screen_name
=screen_name
[1:],
786 include_entities
=False,
788 printNicely(green('Unblock ' + screen_name
+ ' success!'))
790 printNicely(red('A name should begin with a \'@\''))
795 Report a user as a spam account
797 t
= Twitter(auth
=authen())
798 screen_name
= g
['stuff'].split()[0]
799 if screen_name
.startswith('@'):
801 screen_name
=screen_name
[1:])
802 printNicely(green('You reported ' + screen_name
+ '.'))
804 printNicely(red('Sorry I can\'t understand.'))
812 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
813 # Get list name and owner
815 owner
, slug
= list_name
.split('/')
816 if slug
.startswith('@'):
821 light_magenta('List name should follow "@owner/list_name" format.'))
822 raise Exception('Wrong list name')
829 rel
= t
.lists
.list(screen_name
=g
['original_name'])
833 printNicely(light_magenta('You belong to no lists :)'))
840 owner
, slug
= get_slug()
841 res
= t
.lists
.statuses(
843 owner_screen_name
=owner
,
845 include_entities
=False)
855 owner
, slug
= get_slug()
859 while next_cursor
!= 0:
862 owner_screen_name
=owner
,
864 include_entities
=False)
866 rel
[u
['name']] = '@' + u
['screen_name']
867 next_cursor
= m
['next_cursor']
868 printNicely('All: ' + str(len(rel
)) + ' members.')
870 user
= ' ' + cycle_color(name
)
871 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
875 def list_subscribers(t
):
879 owner
, slug
= get_slug()
883 while next_cursor
!= 0:
884 m
= t
.lists
.subscribers(
886 owner_screen_name
=owner
,
888 include_entities
=False)
890 rel
[u
['name']] = '@' + u
['screen_name']
891 next_cursor
= m
['next_cursor']
892 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
894 user
= ' ' + cycle_color(name
)
895 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
901 Add specific user to a list
903 owner
, slug
= get_slug()
905 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
906 if user_name
.startswith('@'):
907 user_name
= user_name
[1:]
909 t
.lists
.members
.create(
911 owner_screen_name
=owner
,
912 screen_name
=user_name
)
913 printNicely(green('Added.'))
915 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
920 Remove specific user from a list
922 owner
, slug
= get_slug()
924 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
925 if user_name
.startswith('@'):
926 user_name
= user_name
[1:]
928 t
.lists
.members
.destroy(
930 owner_screen_name
=owner
,
931 screen_name
=user_name
)
932 printNicely(green('Gone.'))
934 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
937 def list_subscribe(t
):
941 owner
, slug
= get_slug()
944 t
.lists
.subscribers
.create(
946 owner_screen_name
=owner
)
947 printNicely(green('Done.'))
950 light_magenta('I\'m sorry you can not subscribe to this list.'))
953 def list_unsubscribe(t
):
957 owner
, slug
= get_slug()
960 t
.lists
.subscribers
.destroy(
962 owner_screen_name
=owner
)
963 printNicely(green('Done.'))
966 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
975 while next_cursor
!= 0:
976 res
= t
.lists
.ownerships(
977 screen_name
=g
['original_name'],
980 next_cursor
= res
['next_cursor']
984 printNicely(light_magenta('You own no lists :)'))
991 name
= raw_input(light_magenta('New list\'s name: '))
992 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
993 description
= raw_input(light_magenta('New list\'s description: '))
998 description
=description
)
999 printNicely(green(name
+ ' list is created.'))
1001 printNicely(red('Oops something is wrong with Twitter :('))
1008 slug
= raw_input(light_magenta('Your list that you want to update: '))
1009 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1010 mode
= raw_input(light_magenta('Update mode (public/private): '))
1011 description
= raw_input(light_magenta('Update description: '))
1015 slug
='-'.join(slug
.split()),
1016 owner_screen_name
=g
['original_name'],
1019 description
=description
)
1023 owner_screen_name
=g
['original_name'],
1025 description
=description
)
1026 printNicely(green(slug
+ ' list is updated.'))
1028 printNicely(red('Oops something is wrong with Twitter :('))
1035 slug
= raw_input(light_magenta('Your list that you want to update: '))
1038 slug
='-'.join(slug
.split()),
1039 owner_screen_name
=g
['original_name'])
1040 printNicely(green(slug
+ ' list is deleted.'))
1042 printNicely(red('Oops something is wrong with Twitter :('))
1049 t
= Twitter(auth
=authen())
1050 # List all lists or base on action
1052 g
['list_action'] = g
['stuff'].split()[0]
1059 'all_mem': list_members
,
1060 'all_sub': list_subscribers
,
1063 'sub': list_subscribe
,
1064 'unsub': list_unsubscribe
,
1067 'update': list_update
,
1071 return action_ary
[g
['list_action']](t
)
1073 printNicely(red('Please try again.'))
1078 Unix's command `cal`
1081 rel
= os
.popen('cal').read().split('\n')
1084 show_calendar(month
, date
, rel
)
1089 Browse and change config
1091 all_config
= get_all_config()
1092 g
['stuff'] = g
['stuff'].strip()
1095 for k
in all_config
:
1097 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1099 guide
= 'Detailed explanation can be found at ' + \
1100 color_func(c
['TWEET']['link'])(
1101 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1103 # Print specific config
1104 elif len(g
['stuff'].split()) == 1:
1105 if g
['stuff'] in all_config
:
1108 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1111 printNicely(red('No such config key.'))
1112 # Print specific config's default value
1113 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1114 key
= g
['stuff'].split()[0]
1116 value
= get_default_config(key
)
1117 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1119 except Exception as e
:
1121 # Delete specific config key in config file
1122 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1123 key
= g
['stuff'].split()[0]
1126 printNicely(green('Config key is dropped.'))
1127 except Exception as e
:
1129 # Set specific config
1130 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1131 key
= g
['stuff'].split()[0]
1132 value
= g
['stuff'].split()[-1]
1133 if key
== 'THEME' and not validate_theme(value
):
1134 printNicely(red('Invalid theme\'s value.'))
1137 set_config(key
, value
)
1138 # Apply theme immediately
1140 c
['THEME'] = reload_theme(value
, c
['THEME'])
1141 g
['decorated_name'] = lambda x
: color_func(
1142 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1144 printNicely(green('Updated successfully.'))
1145 except Exception as e
:
1148 printNicely(light_magenta('Sorry I can\'s understand.'))
1153 List and change theme
1157 for theme
in g
['themes']:
1158 line
= light_magenta(theme
)
1159 if c
['THEME'] == theme
:
1160 line
= ' ' * 2 + light_yellow('* ') + line
1162 line
= ' ' * 4 + line
1168 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1169 # Redefine decorated_name
1170 g
['decorated_name'] = lambda x
: color_func(
1171 c
['DECORATED_NAME'])(
1173 printNicely(green('Theme changed.'))
1175 printNicely(red('No such theme exists.'))
1178 def help_discover():
1183 # Discover the world
1185 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1186 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1187 'You can try ' + light_green('trend US') + ' or ' + \
1188 light_green('trend JP Tokyo') + '.\n'
1189 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1190 light_green('home 7') + ' will show 7 tweets.\n'
1191 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1192 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1193 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1194 magenta('@mdo') + '.\n'
1195 usage
+= s
* 2 + light_green('view @mdo') + \
1196 ' will show ' + magenta('@mdo') + '\'s home.\n'
1197 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1198 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1199 'Search can be performed with or without hashtag.\n'
1210 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1211 usage
+= s
* 2 + light_green('t oops ') + \
1212 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1214 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1215 light_yellow('[id=12]') + '.\n'
1217 light_green('quote 12 ') + ' will quote the tweet with ' + \
1218 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1219 'the quote will be canceled.\n'
1221 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1222 light_yellow('[id=12]') + '.\n'
1223 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1224 light_yellow('oops') + '" to tweet with ' + \
1225 light_yellow('[id=12]') + '.\n'
1227 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1228 light_yellow('[id=12]') + '.\n'
1230 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1231 light_yellow('[id=12]') + '.\n'
1233 light_green('del 12 ') + ' will delete tweet with ' + \
1234 light_yellow('[id=12]') + '.\n'
1235 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1236 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1237 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1238 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1242 def help_messages():
1249 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1250 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1251 light_green('inbox 7') + ' will show newest 7 messages.\n'
1252 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1253 light_green('sent 7') + ' will show newest 7 messages.\n'
1254 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1255 magenta('@dtvd88') + '.\n'
1256 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1257 light_yellow('[message_id=5]') + '.\n'
1261 def help_friends_and_followers():
1263 Friends and Followers
1266 # Follower and following
1268 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1270 light_green('ls fl') + \
1271 ' will list all followers (people who are following you).\n'
1273 light_green('ls fr') + \
1274 ' will list all friends (people who you are following).\n'
1275 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1276 magenta('@dtvd88') + '.\n'
1277 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1278 magenta('@dtvd88') + '.\n'
1279 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1280 magenta('@dtvd88') + '.\n'
1281 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1282 magenta('@dtvd88') + '.\n'
1283 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1284 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1285 magenta('@dtvd88') + '.\n'
1286 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1289 magenta('@dtvd88') + ' as a spam account.\n'
1300 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1301 usage
+= s
* 2 + light_green('list') + \
1302 ' will show all lists you are belong to.\n'
1303 usage
+= s
* 2 + light_green('list home') + \
1304 ' will show timeline of list. You will be asked for list\'s name.\n'
1305 usage
+= s
* 2 + light_green('list all_mem') + \
1306 ' will show list\'s all members.\n'
1307 usage
+= s
* 2 + light_green('list all_sub') + \
1308 ' will show list\'s all subscribers.\n'
1309 usage
+= s
* 2 + light_green('list add') + \
1310 ' will add specific person to a list owned by you.' + \
1311 ' You will be asked for list\'s name and person\'s name.\n'
1312 usage
+= s
* 2 + light_green('list rm') + \
1313 ' will remove specific person from a list owned by you.' + \
1314 ' You will be asked for list\'s name and person\'s name.\n'
1315 usage
+= s
* 2 + light_green('list sub') + \
1316 ' will subscribe you to a specific list.\n'
1317 usage
+= s
* 2 + light_green('list unsub') + \
1318 ' will unsubscribe you from a specific list.\n'
1319 usage
+= s
* 2 + light_green('list own') + \
1320 ' will show all list owned by you.\n'
1321 usage
+= s
* 2 + light_green('list new') + \
1322 ' will create a new list.\n'
1323 usage
+= s
* 2 + light_green('list update') + \
1324 ' will update a list owned by you.\n'
1325 usage
+= s
* 2 + light_green('list del') + \
1326 ' will delete a list owned by you.\n'
1337 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1338 usage
+= s
* 2 + light_green('switch public #AKB') + \
1339 ' will switch to public stream and follow "' + \
1340 light_yellow('AKB') + '" keyword.\n'
1341 usage
+= s
* 2 + light_green('switch mine') + \
1342 ' will switch to your personal stream.\n'
1343 usage
+= s
* 2 + light_green('switch mine -f ') + \
1344 ' will prompt to enter the filter.\n'
1345 usage
+= s
* 3 + light_yellow('Only nicks') + \
1346 ' filter will decide nicks will be INCLUDE ONLY.\n'
1347 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1348 ' filter will decide nicks will be EXCLUDE.\n'
1349 usage
+= s
* 2 + light_green('switch mine -d') + \
1350 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1359 h
, w
= os
.popen('stty size', 'r').read().split()
1362 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1363 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1364 usage
+= s
+ 'You are ' + \
1365 light_yellow('already') + ' on your personal stream.\n'
1366 usage
+= s
+ 'Any update from Twitter will show up ' + \
1367 light_yellow('immediately') + '.\n'
1368 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1369 # Twitter help section
1371 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1372 usage
+= s
* 2 + light_green('h discover') + \
1373 ' will show help for discover commands.\n'
1374 usage
+= s
* 2 + light_green('h tweets') + \
1375 ' will show help for tweets commands.\n'
1376 usage
+= s
* 2 + light_green('h messages') + \
1377 ' will show help for messages commands.\n'
1378 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1379 ' will show help for friends and followers commands.\n'
1380 usage
+= s
* 2 + light_green('h list') + \
1381 ' will show help for list commands.\n'
1382 usage
+= s
* 2 + light_green('h stream') + \
1383 ' will show help for stream commands.\n'
1386 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1387 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1388 'will be evaluate by Python interpreter.\n'
1389 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1390 ' for current month.\n'
1393 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1394 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1395 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1396 ' theme immediately.\n'
1397 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1399 light_green('config ASCII_ART') + ' will output current value of ' +\
1400 light_yellow('ASCII_ART') + ' config key.\n'
1402 light_green('config TREND_MAX default') + ' will output default value of ' + \
1403 light_yellow('TREND_MAX') + ' config key.\n'
1405 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1406 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1408 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1409 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1410 light_yellow('True') + '.\n'
1413 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1414 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1415 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1416 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1417 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1418 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1421 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1422 usage
+= s
+ 'Have fun and hang tight! \n'
1425 'discover': help_discover
,
1426 'tweets': help_tweets
,
1427 'messages': help_messages
,
1428 'friends_and_followers': help_friends_and_followers
,
1430 'stream': help_stream
,
1435 lambda: printNicely(red('No such command.'))
1443 Pause stream display
1446 printNicely(green('Stream is paused'))
1454 printNicely(green('Stream is running back now'))
1470 printNicely(green('See you next time :)'))
1478 Reset prefix of line
1481 if c
.get('USER_JSON_ERROR'):
1482 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1483 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1485 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1488 printNicely(str(eval(g
['cmd'])))
1536 # Handle function set
1584 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1589 Listen to user's input
1594 ['public', 'mine'], # switch
1609 ['image'], # show image
1611 ['fl', 'fr'], # list
1638 [key
for key
in dict(get_all_config())], # config
1639 g
['themes'], # theme
1644 'friends_and_followers',
1654 init_interactive_shell(d
)
1660 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1663 # Save cmd to compare with readline buffer
1664 g
['cmd'] = line
.strip()
1665 # Get short cmd to pass to handle function
1667 cmd
= line
.split()[0]
1671 # Lock the semaphore
1673 # Save cmd to global variable and call process
1674 g
['stuff'] = ' '.join(line
.split()[1:])
1675 # Process the command
1678 if cmd
in ['switch', 't', 'rt', 'rep']:
1682 # Release the semaphore lock
1685 printNicely(red('OMG something is wrong with Twitter right now.'))
1688 def stream(domain
, args
, name
='Rainbow Stream'):
1694 c
['USER_DOMAIN']: name
,
1695 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1696 c
['SITE_DOMAIN']: name
,
1699 ascii_art(art_dict
[domain
])
1700 # These arguments are optional:
1702 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1704 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1707 if args
.track_keywords
:
1708 query_args
['track'] = args
.track_keywords
1710 stream
= TwitterStream(
1715 if domain
== c
['USER_DOMAIN']:
1716 tweet_iter
= stream
.user(**query_args
)
1717 elif domain
== c
['SITE_DOMAIN']:
1718 tweet_iter
= stream
.site(**query_args
)
1720 if args
.track_keywords
:
1721 tweet_iter
= stream
.statuses
.filter(**query_args
)
1723 tweet_iter
= stream
.statuses
.sample()
1724 # Block new stream until other one exits
1725 StreamLock
.acquire()
1726 g
['stream_stop'] = False
1727 for tweet
in tweet_iter
:
1729 printNicely("-- None --")
1730 elif tweet
is Timeout
:
1731 if(g
['stream_stop']):
1732 StreamLock
.release()
1734 elif tweet
is HeartbeatTimeout
:
1735 printNicely("-- Heartbeat Timeout --")
1736 guide
= light_magenta("You can use ") + \
1737 light_green("switch") + \
1738 light_magenta(" command to return to your stream.\n")
1739 guide
+= light_magenta("Type ") + \
1740 light_green("h stream") + \
1741 light_magenta(" for more details.")
1743 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1745 elif tweet
is Hangup
:
1746 printNicely("-- Hangup --")
1747 elif tweet
.get('text'):
1750 keyword
=args
.track_keywords
,
1751 check_semaphore
=True,
1755 # Current readline buffer
1756 current_buffer
= readline
.get_line_buffer().strip()
1757 # There is an unexpected behaviour in MacOSX readline + Python 2:
1758 # after completely delete a word after typing it,
1759 # somehow readline buffer still contains
1760 # the 1st character of that word
1761 if current_buffer
and g
['cmd'] != current_buffer
:
1763 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1765 elif not c
['HIDE_PROMPT']:
1766 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1768 elif tweet
.get('direct_message'):
1769 print_message(tweet
['direct_message'], check_semaphore
=True)
1770 except TwitterHTTPError
:
1773 magenta("We have maximum connection problem with twitter'stream API right now :("))
1781 args
= parse_arguments()
1784 except TwitterHTTPError
:
1787 magenta("We have connection problem with twitter'stream API right now :("))
1788 printNicely(magenta("Let's try again later."))
1791 # Spawn stream thread
1792 th
= threading
.Thread(
1797 g
['original_name']))
1800 # Start listen process