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)
315 t
= Twitter(auth
=authen())
317 id = int(g
['stuff'].split()[0])
319 printNicely(red('Sorry I can\'t understand.'))
321 tid
= c
['tweet_dict'][id]
322 tweet
= t
.statuses
.show(id=tid
)
323 screen_name
= tweet
['user']['screen_name']
325 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
326 quote
= quote
.encode('utf8')
327 notice
= light_magenta('Compose mode ')
328 notice
+= light_yellow('(Enter nothing will cancel the quote)')
329 notice
+= light_magenta(':')
331 extra
= raw_input(quote
)
333 t
.statuses
.update(status
=quote
+ extra
)
335 printNicely(light_magenta('No text added.'))
342 t
= Twitter(auth
=authen())
345 id = int(g
['stuff'].split()[0])
347 printNicely(red('Sorry I can\'t understand.'))
349 tid
= c
['tweet_dict'][id]
350 # Get display num if exist
352 num
= int(g
['stuff'].split()[1])
354 num
= c
['RETWEETS_SHOW_NUM']
355 # Get result and display
356 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
358 printNicely(magenta('This tweet has no retweet.'))
360 for tweet
in reversed(rt_ary
):
369 t
= Twitter(auth
=authen())
371 id = int(g
['stuff'].split()[0])
373 printNicely(red('Sorry I can\'t understand.'))
375 tid
= c
['tweet_dict'][id]
376 t
.favorites
.create(_id
=tid
, include_entities
=False)
377 printNicely(green('Favorited.'))
378 draw(t
.statuses
.show(id=tid
))
386 t
= Twitter(auth
=authen())
388 id = int(g
['stuff'].split()[0])
390 printNicely(red('Sorry I can\'t understand.'))
392 tid
= c
['tweet_dict'][id]
393 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
394 status
= ' '.join(g
['stuff'].split()[1:])
395 status
= '@' + user
+ ' ' + unc(status
)
396 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
403 t
= Twitter(auth
=authen())
405 id = int(g
['stuff'].split()[0])
407 printNicely(red('Sorry I can\'t understand.'))
409 tid
= c
['tweet_dict'][id]
410 t
.statuses
.destroy(id=tid
)
411 printNicely(green('Okay it\'s gone.'))
418 t
= Twitter(auth
=authen())
420 id = int(g
['stuff'].split()[0])
422 printNicely(red('Sorry I can\'t understand.'))
424 tid
= c
['tweet_dict'][id]
425 t
.favorites
.destroy(_id
=tid
)
426 printNicely(green('Okay it\'s unfavorited.'))
427 draw(t
.statuses
.show(id=tid
))
435 t
= Twitter(auth
=authen())
436 g
['stuff'] = g
['stuff'].strip()
437 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
439 printNicely('Newest tweets:')
440 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
445 printNicely(magenta('I\'m afraid there is no result'))
450 Send a direct message
452 t
= Twitter(auth
=authen())
453 user
= g
['stuff'].split()[0]
454 if user
[0].startswith('@'):
456 content
= g
['stuff'].split()[1]
458 printNicely(red('Sorry I can\'t understand.'))
459 t
.direct_messages
.new(
460 screen_name
=user
[1:],
463 printNicely(green('Message sent.'))
465 printNicely(red('A name should begin with a \'@\''))
472 t
= Twitter(auth
=authen())
474 target
= g
['stuff'].split()[0]
475 if target
!= 'image':
477 id = int(g
['stuff'].split()[1])
478 tid
= c
['tweet_dict'][id]
479 tweet
= t
.statuses
.show(id=tid
)
480 media
= tweet
['entities']['media']
482 res
= requests
.get(m
['media_url'])
483 img
= Image
.open(BytesIO(res
.content
))
486 printNicely(red('Sorry I can\'t show this image.'))
493 t
= Twitter(auth
=authen())
495 if not g
['stuff'].isdigit():
497 tid
= c
['tweet_dict'][int(g
['stuff'])]
498 tweet
= t
.statuses
.show(id=tid
)
500 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
502 printNicely(light_magenta('No url here @.@!'))
504 for link
in link_ary
:
505 webbrowser
.open(link
)
507 printNicely(red('Sorry I can\'t open url in this tweet.'))
512 List friends for followers
514 t
= Twitter(auth
=authen())
517 name
= g
['stuff'].split()[1]
518 if name
.startswith('@'):
521 printNicely(red('A name should begin with a \'@\''))
522 raise Exception('Invalid name')
524 name
= g
['original_name']
525 # Get list followers or friends
527 target
= g
['stuff'].split()[0]
529 printNicely(red('Omg some syntax is wrong.'))
531 d
= {'fl': 'followers', 'fr': 'friends'}
535 while next_cursor
!= 0:
536 list = getattr(t
, d
[target
]).list(
540 include_entities
=False,
542 for u
in list['users']:
543 rel
[u
['name']] = '@' + u
['screen_name']
544 next_cursor
= list['next_cursor']
546 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
548 user
= ' ' + cycle_color(name
)
549 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
555 Inbox direct messages
557 t
= Twitter(auth
=authen())
558 num
= c
['MESSAGES_DISPLAY']
560 if g
['stuff'].isdigit():
563 # Max message per page is 20 so we have to loop
565 rel
= rel
+ t
.direct_messages(
568 include_entities
=False,
573 rel
= rel
+ t
.direct_messages(
576 include_entities
=False,
580 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
581 for m
in reversed(rel
):
590 t
= Twitter(auth
=authen())
591 num
= c
['MESSAGES_DISPLAY']
593 if g
['stuff'].isdigit():
594 num
= int(g
['stuff'])
596 # Max message per page is 20 so we have to loop
598 rel
= rel
+ t
.direct_messages
.sent(
601 include_entities
=False,
606 rel
= rel
+ t
.direct_messages
.sent(
609 include_entities
=False,
613 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
614 for m
in reversed(rel
):
623 t
= Twitter(auth
=authen())
625 id = int(g
['stuff'].split()[0])
627 printNicely(red('Sorry I can\'t understand.'))
628 mid
= c
['message_dict'][id]
629 t
.direct_messages
.destroy(id=mid
)
630 printNicely(green('Message deleted.'))
635 Show profile of a specific user
637 t
= Twitter(auth
=authen())
638 screen_name
= g
['stuff'].split()[0]
639 if screen_name
.startswith('@'):
642 screen_name
=screen_name
[1:],
643 include_entities
=False)
646 printNicely(red('Omg no user.'))
648 printNicely(red('A name should begin with a \'@\''))
655 t
= Twitter(auth
=authen())
656 screen_name
= g
['stuff'].split()[0]
657 if screen_name
.startswith('@'):
658 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
659 printNicely(green('You are following ' + screen_name
+ ' now!'))
661 printNicely(red('A name should begin with a \'@\''))
668 t
= Twitter(auth
=authen())
669 screen_name
= g
['stuff'].split()[0]
670 if screen_name
.startswith('@'):
671 t
.friendships
.destroy(
672 screen_name
=screen_name
[1:],
673 include_entities
=False)
674 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
676 printNicely(red('A name should begin with a \'@\''))
683 t
= Twitter(auth
=authen())
685 screen_name
= g
['stuff'].split()[0]
687 printNicely(red('A name should be specified. '))
689 if screen_name
.startswith('@'):
691 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
692 if isinstance(rel
, dict):
693 printNicely(green(screen_name
+ ' is muted.'))
694 c
['IGNORE_LIST'] += [unc(screen_name
)]
695 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
697 printNicely(red(rel
))
699 printNicely(red('Something is wrong, can not mute now :('))
701 printNicely(red('A name should begin with a \'@\''))
708 t
= Twitter(auth
=authen())
710 screen_name
= g
['stuff'].split()[0]
712 printNicely(red('A name should be specified. '))
714 if screen_name
.startswith('@'):
716 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
717 if isinstance(rel
, dict):
718 printNicely(green(screen_name
+ ' is unmuted.'))
719 c
['IGNORE_LIST'].remove(screen_name
)
721 printNicely(red(rel
))
723 printNicely(red('Maybe you are not muting this person ?'))
725 printNicely(red('A name should begin with a \'@\''))
732 # Get dict of muting users
733 md
= build_mute_dict(dict_data
=True)
734 printNicely('All: ' + str(len(md
)) + ' people.')
736 user
= ' ' + cycle_color(md
[name
])
737 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
739 # Update from Twitter
740 c
['IGNORE_LIST'] = [n
for n
in md
]
747 t
= Twitter(auth
=authen())
748 screen_name
= g
['stuff'].split()[0]
749 if screen_name
.startswith('@'):
751 screen_name
=screen_name
[1:],
752 include_entities
=False,
754 printNicely(green('You blocked ' + screen_name
+ '.'))
756 printNicely(red('A name should begin with a \'@\''))
763 t
= Twitter(auth
=authen())
764 screen_name
= g
['stuff'].split()[0]
765 if screen_name
.startswith('@'):
767 screen_name
=screen_name
[1:],
768 include_entities
=False,
770 printNicely(green('Unblock ' + screen_name
+ ' success!'))
772 printNicely(red('A name should begin with a \'@\''))
777 Report a user as a spam account
779 t
= Twitter(auth
=authen())
780 screen_name
= g
['stuff'].split()[0]
781 if screen_name
.startswith('@'):
783 screen_name
=screen_name
[1:])
784 printNicely(green('You reported ' + screen_name
+ '.'))
786 printNicely(red('Sorry I can\'t understand.'))
794 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
795 # Get list name and owner
797 owner
, slug
= list_name
.split('/')
798 if slug
.startswith('@'):
803 light_magenta('List name should follow "@owner/list_name" format.'))
804 raise Exception('Wrong list name')
811 rel
= t
.lists
.list(screen_name
=g
['original_name'])
815 printNicely(light_magenta('You belong to no lists :)'))
822 owner
, slug
= get_slug()
823 res
= t
.lists
.statuses(
825 owner_screen_name
=owner
,
827 include_entities
=False)
837 owner
, slug
= get_slug()
841 while next_cursor
!= 0:
844 owner_screen_name
=owner
,
846 include_entities
=False)
848 rel
[u
['name']] = '@' + u
['screen_name']
849 next_cursor
= m
['next_cursor']
850 printNicely('All: ' + str(len(rel
)) + ' members.')
852 user
= ' ' + cycle_color(name
)
853 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
857 def list_subscribers(t
):
861 owner
, slug
= get_slug()
865 while next_cursor
!= 0:
866 m
= t
.lists
.subscribers(
868 owner_screen_name
=owner
,
870 include_entities
=False)
872 rel
[u
['name']] = '@' + u
['screen_name']
873 next_cursor
= m
['next_cursor']
874 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
876 user
= ' ' + cycle_color(name
)
877 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
883 Add specific user to a list
885 owner
, slug
= get_slug()
887 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
888 if user_name
.startswith('@'):
889 user_name
= user_name
[1:]
891 t
.lists
.members
.create(
893 owner_screen_name
=owner
,
894 screen_name
=user_name
)
895 printNicely(green('Added.'))
897 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
902 Remove specific user from a list
904 owner
, slug
= get_slug()
906 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
907 if user_name
.startswith('@'):
908 user_name
= user_name
[1:]
910 t
.lists
.members
.destroy(
912 owner_screen_name
=owner
,
913 screen_name
=user_name
)
914 printNicely(green('Gone.'))
916 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
919 def list_subscribe(t
):
923 owner
, slug
= get_slug()
926 t
.lists
.subscribers
.create(
928 owner_screen_name
=owner
)
929 printNicely(green('Done.'))
932 light_magenta('I\'m sorry you can not subscribe to this list.'))
935 def list_unsubscribe(t
):
939 owner
, slug
= get_slug()
942 t
.lists
.subscribers
.destroy(
944 owner_screen_name
=owner
)
945 printNicely(green('Done.'))
948 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
957 while next_cursor
!= 0:
958 res
= t
.lists
.ownerships(
959 screen_name
=g
['original_name'],
962 next_cursor
= res
['next_cursor']
966 printNicely(light_magenta('You own no lists :)'))
973 name
= raw_input(light_magenta('New list\'s name: '))
974 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
975 description
= raw_input(light_magenta('New list\'s description: '))
980 description
=description
)
981 printNicely(green(name
+ ' list is created.'))
983 printNicely(red('Oops something is wrong with Twitter :('))
990 slug
= raw_input(light_magenta('Your list that you want to update: '))
991 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
992 mode
= raw_input(light_magenta('Update mode (public/private): '))
993 description
= raw_input(light_magenta('Update description: '))
997 slug
='-'.join(slug
.split()),
998 owner_screen_name
=g
['original_name'],
1001 description
=description
)
1005 owner_screen_name
=g
['original_name'],
1007 description
=description
)
1008 printNicely(green(slug
+ ' list is updated.'))
1010 printNicely(red('Oops something is wrong with Twitter :('))
1017 slug
= raw_input(light_magenta('Your list that you want to update: '))
1020 slug
='-'.join(slug
.split()),
1021 owner_screen_name
=g
['original_name'])
1022 printNicely(green(slug
+ ' list is deleted.'))
1024 printNicely(red('Oops something is wrong with Twitter :('))
1031 t
= Twitter(auth
=authen())
1032 # List all lists or base on action
1034 g
['list_action'] = g
['stuff'].split()[0]
1041 'all_mem': list_members
,
1042 'all_sub': list_subscribers
,
1045 'sub': list_subscribe
,
1046 'unsub': list_unsubscribe
,
1049 'update': list_update
,
1053 return action_ary
[g
['list_action']](t
)
1055 printNicely(red('Please try again.'))
1060 Unix's command `cal`
1063 rel
= os
.popen('cal').read().split('\n')
1066 show_calendar(month
, date
, rel
)
1071 Browse and change config
1073 all_config
= get_all_config()
1074 g
['stuff'] = g
['stuff'].strip()
1077 for k
in all_config
:
1079 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1081 guide
= 'Detailed explanation can be found at ' + \
1082 color_func(c
['TWEET']['link'])(
1083 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1085 # Print specific config
1086 elif len(g
['stuff'].split()) == 1:
1087 if g
['stuff'] in all_config
:
1090 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1093 printNicely(red('No such config key.'))
1094 # Print specific config's default value
1095 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1096 key
= g
['stuff'].split()[0]
1098 value
= get_default_config(key
)
1099 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1101 except Exception as e
:
1103 # Delete specific config key in config file
1104 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1105 key
= g
['stuff'].split()[0]
1108 printNicely(green('Config key is dropped.'))
1109 except Exception as e
:
1111 # Set specific config
1112 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1113 key
= g
['stuff'].split()[0]
1114 value
= g
['stuff'].split()[-1]
1115 if key
== 'THEME' and not validate_theme(value
):
1116 printNicely(red('Invalid theme\'s value.'))
1119 set_config(key
, value
)
1120 # Apply theme immediately
1122 c
['THEME'] = reload_theme(value
, c
['THEME'])
1123 g
['decorated_name'] = lambda x
: color_func(
1124 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1126 printNicely(green('Updated successfully.'))
1127 except Exception as e
:
1130 printNicely(light_magenta('Sorry I can\'s understand.'))
1135 List and change theme
1139 for theme
in g
['themes']:
1140 line
= light_magenta(theme
)
1141 if c
['THEME'] == theme
:
1142 line
= ' ' * 2 + light_yellow('* ') + line
1144 line
= ' ' * 4 + line
1150 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1151 # Redefine decorated_name
1152 g
['decorated_name'] = lambda x
: color_func(
1153 c
['DECORATED_NAME'])(
1155 printNicely(green('Theme changed.'))
1157 printNicely(red('No such theme exists.'))
1160 def help_discover():
1165 # Discover the world
1167 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1168 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1169 'You can try ' + light_green('trend US') + ' or ' + \
1170 light_green('trend JP Tokyo') + '.\n'
1171 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1172 light_green('home 7') + ' will show 7 tweets.\n'
1173 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1174 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1175 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1176 magenta('@mdo') + '.\n'
1177 usage
+= s
* 2 + light_green('view @mdo') + \
1178 ' will show ' + magenta('@mdo') + '\'s home.\n'
1179 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1180 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1181 'Search can be performed with or without hashtag.\n'
1192 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1193 usage
+= s
* 2 + light_green('t oops ') + \
1194 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1196 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1197 light_yellow('[id=12]') + '.\n'
1199 light_green('quote 12 ') + ' will quote the tweet with ' + \
1200 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1201 'the quote will be canceled.\n'
1203 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1204 light_yellow('[id=12]') + '.\n'
1205 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1206 light_yellow('oops') + '" to tweet with ' + \
1207 light_yellow('[id=12]') + '.\n'
1209 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1210 light_yellow('[id=12]') + '.\n'
1212 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1213 light_yellow('[id=12]') + '.\n'
1215 light_green('del 12 ') + ' will delete tweet with ' + \
1216 light_yellow('[id=12]') + '.\n'
1217 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1218 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1219 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1220 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1224 def help_messages():
1231 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1232 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1233 light_green('inbox 7') + ' will show newest 7 messages.\n'
1234 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1235 light_green('sent 7') + ' will show newest 7 messages.\n'
1236 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1237 magenta('@dtvd88') + '.\n'
1238 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1239 light_yellow('[message_id=5]') + '.\n'
1243 def help_friends_and_followers():
1245 Friends and Followers
1248 # Follower and following
1250 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1252 light_green('ls fl') + \
1253 ' will list all followers (people who are following you).\n'
1255 light_green('ls fr') + \
1256 ' will list all friends (people who you are following).\n'
1257 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1258 magenta('@dtvd88') + '.\n'
1259 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1260 magenta('@dtvd88') + '.\n'
1261 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1262 magenta('@dtvd88') + '.\n'
1263 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1264 magenta('@dtvd88') + '.\n'
1265 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1266 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1267 magenta('@dtvd88') + '.\n'
1268 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1269 magenta('@dtvd88') + '.\n'
1270 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1271 magenta('@dtvd88') + ' as a spam account.\n'
1282 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1283 usage
+= s
* 2 + light_green('list') + \
1284 ' will show all lists you are belong to.\n'
1285 usage
+= s
* 2 + light_green('list home') + \
1286 ' will show timeline of list. You will be asked for list\'s name.\n'
1287 usage
+= s
* 2 + light_green('list all_mem') + \
1288 ' will show list\'s all members.\n'
1289 usage
+= s
* 2 + light_green('list all_sub') + \
1290 ' will show list\'s all subscribers.\n'
1291 usage
+= s
* 2 + light_green('list add') + \
1292 ' will add specific person to a list owned by you.' + \
1293 ' You will be asked for list\'s name and person\'s name.\n'
1294 usage
+= s
* 2 + light_green('list rm') + \
1295 ' will remove specific person from a list owned by you.' + \
1296 ' You will be asked for list\'s name and person\'s name.\n'
1297 usage
+= s
* 2 + light_green('list sub') + \
1298 ' will subscribe you to a specific list.\n'
1299 usage
+= s
* 2 + light_green('list unsub') + \
1300 ' will unsubscribe you from a specific list.\n'
1301 usage
+= s
* 2 + light_green('list own') + \
1302 ' will show all list owned by you.\n'
1303 usage
+= s
* 2 + light_green('list new') + \
1304 ' will create a new list.\n'
1305 usage
+= s
* 2 + light_green('list update') + \
1306 ' will update a list owned by you.\n'
1307 usage
+= s
* 2 + light_green('list del') + \
1308 ' will delete a list owned by you.\n'
1319 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1320 usage
+= s
* 2 + light_green('switch public #AKB') + \
1321 ' will switch to public stream and follow "' + \
1322 light_yellow('AKB') + '" keyword.\n'
1323 usage
+= s
* 2 + light_green('switch mine') + \
1324 ' will switch to your personal stream.\n'
1325 usage
+= s
* 2 + light_green('switch mine -f ') + \
1326 ' will prompt to enter the filter.\n'
1327 usage
+= s
* 3 + light_yellow('Only nicks') + \
1328 ' filter will decide nicks will be INCLUDE ONLY.\n'
1329 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1330 ' filter will decide nicks will be EXCLUDE.\n'
1331 usage
+= s
* 2 + light_green('switch mine -d') + \
1332 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1341 h
, w
= os
.popen('stty size', 'r').read().split()
1344 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1345 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1346 usage
+= s
+ 'You are ' + \
1347 light_yellow('already') + ' on your personal stream.\n'
1348 usage
+= s
+ 'Any update from Twitter will show up ' + \
1349 light_yellow('immediately') + '.\n'
1350 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1351 # Twitter help section
1353 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1354 usage
+= s
* 2 + light_green('h discover') + \
1355 ' will show help for discover commands.\n'
1356 usage
+= s
* 2 + light_green('h tweets') + \
1357 ' will show help for tweets commands.\n'
1358 usage
+= s
* 2 + light_green('h messages') + \
1359 ' will show help for messages commands.\n'
1360 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1361 ' will show help for friends and followers commands.\n'
1362 usage
+= s
* 2 + light_green('h list') + \
1363 ' will show help for list commands.\n'
1364 usage
+= s
* 2 + light_green('h stream') + \
1365 ' will show help for stream commands.\n'
1368 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1369 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1370 'will be evaluate by Python interpreter.\n'
1371 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1372 ' for current month.\n'
1375 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1376 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1377 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1378 ' theme immediately.\n'
1379 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1381 light_green('config ASCII_ART') + ' will output current value of ' +\
1382 light_yellow('ASCII_ART') + ' config key.\n'
1384 light_green('config TREND_MAX default') + ' will output default value of ' + \
1385 light_yellow('TREND_MAX') + ' config key.\n'
1387 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1388 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1390 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1391 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1392 light_yellow('True') + '.\n'
1395 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1396 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1397 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1398 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1399 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1400 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1403 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1404 usage
+= s
+ 'Have fun and hang tight! \n'
1407 'discover': help_discover
,
1408 'tweets': help_tweets
,
1409 'messages': help_messages
,
1410 'friends_and_followers': help_friends_and_followers
,
1412 'stream': help_stream
,
1417 lambda: printNicely(red('No such command.'))
1425 Pause stream display
1428 printNicely(green('Stream is paused'))
1436 printNicely(green('Stream is running back now'))
1452 printNicely(green('See you next time :)'))
1460 Reset prefix of line
1463 if c
.get('USER_JSON_ERROR'):
1464 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1465 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1467 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1470 printNicely(str(eval(g
['cmd'])))
1518 # Handle function set
1566 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1571 Listen to user's input
1576 ['public', 'mine'], # switch
1591 ['image'], # show image
1593 ['fl', 'fr'], # list
1620 [key
for key
in dict(get_all_config())], # config
1621 g
['themes'], # theme
1626 'friends_and_followers',
1636 init_interactive_shell(d
)
1642 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1645 # Save cmd to compare with readline buffer
1646 g
['cmd'] = line
.strip()
1647 # Get short cmd to pass to handle function
1649 cmd
= line
.split()[0]
1653 # Lock the semaphore
1655 # Save cmd to global variable and call process
1656 g
['stuff'] = ' '.join(line
.split()[1:])
1657 # Process the command
1660 if cmd
in ['switch', 't', 'rt', 'rep']:
1664 # Release the semaphore lock
1667 printNicely(red('OMG something is wrong with Twitter right now.'))
1670 def stream(domain
, args
, name
='Rainbow Stream'):
1676 c
['USER_DOMAIN']: name
,
1677 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1678 c
['SITE_DOMAIN']: name
,
1681 ascii_art(art_dict
[domain
])
1682 # These arguments are optional:
1684 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1686 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1689 if args
.track_keywords
:
1690 query_args
['track'] = args
.track_keywords
1692 stream
= TwitterStream(
1697 if domain
== c
['USER_DOMAIN']:
1698 tweet_iter
= stream
.user(**query_args
)
1699 elif domain
== c
['SITE_DOMAIN']:
1700 tweet_iter
= stream
.site(**query_args
)
1702 if args
.track_keywords
:
1703 tweet_iter
= stream
.statuses
.filter(**query_args
)
1705 tweet_iter
= stream
.statuses
.sample()
1706 # Block new stream until other one exits
1707 StreamLock
.acquire()
1708 g
['stream_stop'] = False
1709 for tweet
in tweet_iter
:
1711 printNicely("-- None --")
1712 elif tweet
is Timeout
:
1713 if(g
['stream_stop']):
1714 StreamLock
.release()
1716 elif tweet
is HeartbeatTimeout
:
1717 printNicely("-- Heartbeat Timeout --")
1718 guide
= light_magenta("You can use ") + \
1719 light_green("switch") + \
1720 light_magenta(" command to return to your stream.\n")
1721 guide
+= light_magenta("Type ") + \
1722 light_green("h stream") + \
1723 light_magenta(" for more details.")
1725 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1727 elif tweet
is Hangup
:
1728 printNicely("-- Hangup --")
1729 elif tweet
.get('text'):
1732 keyword
=args
.track_keywords
,
1733 check_semaphore
=True,
1737 # Current readline buffer
1738 current_buffer
= readline
.get_line_buffer().strip()
1739 # There is an unexpected behaviour in MacOSX readline + Python 2:
1740 # after completely delete a word after typing it,
1741 # somehow readline buffer still contains
1742 # the 1st character of that word
1743 if current_buffer
and g
['cmd'] != current_buffer
:
1745 g
['decorated_name'](c
['PREFIX']) + unc(current_buffer
))
1747 elif not c
['HIDE_PROMPT']:
1748 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1750 elif tweet
.get('direct_message'):
1751 print_message(tweet
['direct_message'], check_semaphore
=True)
1752 except TwitterHTTPError
:
1755 magenta("We have maximum connection problem with twitter'stream API right now :("))
1763 args
= parse_arguments()
1766 except TwitterHTTPError
:
1769 magenta("We have connection problem with twitter'stream API right now :("))
1770 printNicely(magenta("Let's try again later."))
1773 # Spawn stream thread
1774 th
= threading
.Thread(
1779 g
['original_name']))
1782 # Start listen process