11 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
12 from twitter
.api
import *
13 from twitter
.oauth
import OAuth
, read_token_file
14 from twitter
.oauth_dance
import oauth_dance
15 from twitter
.util
import printNicely
20 from .consumer
import *
21 from .interactive
import *
22 from .c_image
import *
23 from .py3patch
import *
29 StreamLock
= threading
.Lock()
32 def parse_arguments():
36 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
40 help='Timeout for the stream (seconds).')
44 help='Search the stream for specific text.')
48 help='Filter specific screen_name.')
52 help='Ignore specific screen_name.')
57 help='Display all image on terminal.')
58 return parser
.parse_args()
63 Authenticate with Twitter OAuth
65 # When using rainbow stream you must authorize.
66 twitter_credential
= os
.environ
.get(
70 '')) + os
.sep
+ '.rainbow_oauth'
71 if not os
.path
.exists(twitter_credential
):
72 oauth_dance("Rainbow Stream",
76 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
84 def build_mute_dict(dict_data
=False):
88 t
= Twitter(auth
=authen())
94 while next_cursor
!= 0:
95 list = t
.mutes
.users
.list(
96 screen_name
=g
['original_name'],
99 include_entities
=False,
101 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
102 name_list
+= [u
['name'] for u
in list['users']]
103 next_cursor
= list['next_cursor']
104 # Return dict or list
106 return dict(zip(screen_name_list
, name_list
))
108 return screen_name_list
116 ctrl_c_handler
= lambda signum
, frame
: quit()
117 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
119 t
= Twitter(auth
=authen())
120 credential
= t
.account
.verify_credentials()
121 screen_name
= '@' + credential
['screen_name']
122 name
= credential
['name']
123 if not get_config('PREFIX'):
124 set_config('PREFIX', screen_name
)
125 g
['PREFIX'] = u2str(c
['PREFIX'])
126 c
['original_name'] = g
['original_name'] = screen_name
[1:]
127 g
['full_name'] = name
128 g
['decorated_name'] = lambda x
: color_func(
129 c
['DECORATED_NAME'])('[' + x
+ ']: ')
131 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
132 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
135 g
['message_threads'] = {}
142 # Init tweet dict and message dict
144 c
['message_dict'] = []
146 c
['IMAGE_ON_TERM'] = args
.image_on_term
147 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
149 c
['IGNORE_LIST'] += build_mute_dict()
156 t
= Twitter(auth
=authen())
157 # Get country and town
159 country
= g
['stuff'].split()[0]
163 town
= g
['stuff'].split()[1]
166 avail
= t
.trends
.available()
169 trends
= t
.trends
.place(_id
=1)[0]['trends']
172 for location
in avail
:
173 # Search for country and Town
175 if location
['countryCode'] == country \
176 and location
['placeType']['name'] == 'Town' \
177 and location
['name'] == town
:
178 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
180 # Search for country only
182 if location
['countryCode'] == country \
183 and location
['placeType']['name'] == 'Country':
184 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
192 t
= Twitter(auth
=authen())
193 num
= c
['HOME_TWEET_NUM']
194 if g
['stuff'].isdigit():
195 num
= int(g
['stuff'])
196 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
206 for e
in g
['events']:
210 printNicely(magenta('Nothing at this time.'))
217 t
= Twitter(auth
=authen())
218 num
= c
['HOME_TWEET_NUM']
219 if g
['stuff'].isdigit():
220 num
= int(g
['stuff'])
221 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
228 Show profile of a specific user
230 t
= Twitter(auth
=authen())
231 screen_name
= g
['stuff'].split()[0]
232 if screen_name
.startswith('@'):
235 screen_name
=screen_name
[1:],
236 include_entities
=False)
239 printNicely(red('Omg no user.'))
241 printNicely(red('A name should begin with a \'@\''))
248 t
= Twitter(auth
=authen())
249 user
= g
['stuff'].split()[0]
252 num
= int(g
['stuff'].split()[1])
254 num
= c
['HOME_TWEET_NUM']
255 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
259 printNicely(red('A name should begin with a \'@\''))
266 t
= Twitter(auth
=authen())
268 query
= g
['stuff'].strip()
269 type = c
['SEARCH_TYPE']
270 if type not in ['mixed', 'recent', 'popular']:
272 max_record
= c
['SEARCH_MAX_RECORD']
273 count
= min(max_record
, 100)
275 rel
= t
.search
.tweets(
282 printNicely('Newest tweets:')
283 for i
in reversed(xrange(count
)):
284 draw(t
=rel
[i
], keyword
=query
)
287 printNicely(magenta('I\'m afraid there is no result'))
294 t
= Twitter(auth
=authen())
295 t
.statuses
.update(status
=g
['stuff'])
302 t
= Twitter(auth
=authen())
304 id = int(g
['stuff'].split()[0])
306 printNicely(red('Sorry I can\'t understand.'))
308 tid
= c
['tweet_dict'][id]
309 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
317 t
= Twitter(auth
=authen())
319 id = int(g
['stuff'].split()[0])
321 printNicely(red('Sorry I can\'t understand.'))
323 tid
= c
['tweet_dict'][id]
324 tweet
= t
.statuses
.show(id=tid
)
326 formater
= format_quote(tweet
)
330 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
331 comment
= raw_input(prefix
)
333 quote
= comment
.join(formater
.split('#comment'))
334 t
.statuses
.update(status
=quote
)
336 printNicely(light_magenta('No text added.'))
343 t
= Twitter(auth
=authen())
346 id = int(g
['stuff'].split()[0])
348 printNicely(red('Sorry I can\'t understand.'))
350 tid
= c
['tweet_dict'][id]
351 # Get display num if exist
353 num
= int(g
['stuff'].split()[1])
355 num
= c
['RETWEETS_SHOW_NUM']
356 # Get result and display
357 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
359 printNicely(magenta('This tweet has no retweet.'))
361 for tweet
in reversed(rt_ary
):
370 t
= Twitter(auth
=authen())
372 id = int(g
['stuff'].split()[0])
374 printNicely(red('Sorry I can\'t understand.'))
376 tid
= c
['tweet_dict'][id]
377 tweet
= t
.statuses
.show(id=tid
)
378 limit
= c
['CONVERSATION_MAX']
380 thread_ref
.append(tweet
)
381 prev_tid
= tweet
['in_reply_to_status_id']
382 while prev_tid
and limit
:
384 tweet
= t
.statuses
.show(id=prev_tid
)
385 prev_tid
= tweet
['in_reply_to_status_id']
386 thread_ref
.append(tweet
)
388 for tweet
in reversed(thread_ref
):
397 t
= Twitter(auth
=authen())
399 id = int(g
['stuff'].split()[0])
401 printNicely(red('Sorry I can\'t understand.'))
403 tid
= c
['tweet_dict'][id]
404 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
405 status
= ' '.join(g
['stuff'].split()[1:])
406 status
= '@' + user
+ ' ' + str2u(status
)
407 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
414 t
= Twitter(auth
=authen())
416 id = int(g
['stuff'].split()[0])
418 printNicely(red('Sorry I can\'t understand.'))
420 tid
= c
['tweet_dict'][id]
421 t
.favorites
.create(_id
=tid
, include_entities
=False)
422 printNicely(green('Favorited.'))
423 draw(t
.statuses
.show(id=tid
))
431 t
= Twitter(auth
=authen())
433 id = int(g
['stuff'].split()[0])
435 printNicely(red('Sorry I can\'t understand.'))
437 tid
= c
['tweet_dict'][id]
438 t
.favorites
.destroy(_id
=tid
)
439 printNicely(green('Okay it\'s unfavorited.'))
440 draw(t
.statuses
.show(id=tid
))
448 t
= Twitter(auth
=authen())
450 id = int(g
['stuff'].split()[0])
452 printNicely(red('Sorry I can\'t understand.'))
454 tid
= c
['tweet_dict'][id]
455 t
.statuses
.destroy(id=tid
)
456 printNicely(green('Okay it\'s gone.'))
463 t
= Twitter(auth
=authen())
465 target
= g
['stuff'].split()[0]
466 if target
!= 'image':
468 id = int(g
['stuff'].split()[1])
469 tid
= c
['tweet_dict'][id]
470 tweet
= t
.statuses
.show(id=tid
)
471 media
= tweet
['entities']['media']
473 res
= requests
.get(m
['media_url'])
474 img
= Image
.open(BytesIO(res
.content
))
477 printNicely(red('Sorry I can\'t show this image.'))
484 t
= Twitter(auth
=authen())
486 if not g
['stuff'].isdigit():
488 tid
= c
['tweet_dict'][int(g
['stuff'])]
489 tweet
= t
.statuses
.show(id=tid
)
490 link_prefix
= ('http://', 'https://')
491 link_ary
= [u
for u
in tweet
['text'].split()
492 if u
.startswith(link_prefix
)]
494 printNicely(light_magenta('No url here @.@!'))
496 for link
in link_ary
:
497 webbrowser
.open(link
)
499 printNicely(red('Sorry I can\'t open url in this tweet.'))
506 t
= Twitter(auth
=authen())
507 num
= c
['MESSAGES_DISPLAY']
508 if g
['stuff'].isdigit():
514 inbox
= inbox
+ t
.direct_messages(
517 include_entities
=False,
522 inbox
= inbox
+ t
.direct_messages(
525 include_entities
=False,
529 num
= c
['MESSAGES_DISPLAY']
530 if g
['stuff'].isdigit():
535 sent
= sent
+ t
.direct_messages
.sent(
538 include_entities
=False,
543 sent
= sent
+ t
.direct_messages
.sent(
546 include_entities
=False,
551 uniq_inbox
= list(set(
552 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
554 uniq_sent
= list(set(
555 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
557 for partner
in uniq_inbox
:
558 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
560 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
561 d
[partner
] = inbox_ary
+ sent_ary
562 for partner
in uniq_sent
:
565 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
566 g
['message_threads'] = print_threads(d
)
571 View a thread of message
574 thread_id
= int(g
['stuff'])
576 g
['message_threads'][thread_id
],
580 printNicely(red('No such thread.'))
585 Send a direct message
587 t
= Twitter(auth
=authen())
589 user
= g
['stuff'].split()[0]
590 if user
[0].startswith('@'):
591 content
= ' '.join(g
['stuff'].split()[1:])
592 t
.direct_messages
.new(
593 screen_name
=user
[1:],
596 printNicely(green('Message sent.'))
598 printNicely(red('A name should begin with a \'@\''))
600 printNicely(red('Sorry I can\'t understand.'))
607 t
= Twitter(auth
=authen())
609 id = int(g
['stuff'].split()[0])
611 printNicely(red('Sorry I can\'t understand.'))
612 mid
= c
['message_dict'][id]
613 t
.direct_messages
.destroy(id=mid
)
614 printNicely(green('Message deleted.'))
619 List friends for followers
621 t
= Twitter(auth
=authen())
624 name
= g
['stuff'].split()[1]
625 if name
.startswith('@'):
628 printNicely(red('A name should begin with a \'@\''))
629 raise Exception('Invalid name')
631 name
= g
['original_name']
632 # Get list followers or friends
634 target
= g
['stuff'].split()[0]
636 printNicely(red('Omg some syntax is wrong.'))
638 d
= {'fl': 'followers', 'fr': 'friends'}
642 while next_cursor
!= 0:
643 list = getattr(t
, d
[target
]).list(
647 include_entities
=False,
649 for u
in list['users']:
650 rel
[u
['name']] = '@' + u
['screen_name']
651 next_cursor
= list['next_cursor']
653 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
655 user
= ' ' + cycle_color(name
)
656 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
664 t
= Twitter(auth
=authen())
665 screen_name
= g
['stuff'].split()[0]
666 if screen_name
.startswith('@'):
667 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
668 printNicely(green('You are following ' + screen_name
+ ' now!'))
670 printNicely(red('A name should begin with a \'@\''))
677 t
= Twitter(auth
=authen())
678 screen_name
= g
['stuff'].split()[0]
679 if screen_name
.startswith('@'):
680 t
.friendships
.destroy(
681 screen_name
=screen_name
[1:],
682 include_entities
=False)
683 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
685 printNicely(red('A name should begin with a \'@\''))
692 t
= Twitter(auth
=authen())
694 screen_name
= g
['stuff'].split()[0]
696 printNicely(red('A name should be specified. '))
698 if screen_name
.startswith('@'):
700 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
701 if isinstance(rel
, dict):
702 printNicely(green(screen_name
+ ' is muted.'))
703 c
['IGNORE_LIST'] += [unc(screen_name
)]
704 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
706 printNicely(red(rel
))
708 printNicely(red('Something is wrong, can not mute now :('))
710 printNicely(red('A name should begin with a \'@\''))
717 t
= Twitter(auth
=authen())
719 screen_name
= g
['stuff'].split()[0]
721 printNicely(red('A name should be specified. '))
723 if screen_name
.startswith('@'):
725 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
726 if isinstance(rel
, dict):
727 printNicely(green(screen_name
+ ' is unmuted.'))
728 c
['IGNORE_LIST'].remove(screen_name
)
730 printNicely(red(rel
))
732 printNicely(red('Maybe you are not muting this person ?'))
734 printNicely(red('A name should begin with a \'@\''))
741 # Get dict of muting users
742 md
= build_mute_dict(dict_data
=True)
743 printNicely('All: ' + str(len(md
)) + ' people.')
745 user
= ' ' + cycle_color(md
[name
])
746 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
748 # Update from Twitter
749 c
['IGNORE_LIST'] = [n
for n
in md
]
756 t
= Twitter(auth
=authen())
757 screen_name
= g
['stuff'].split()[0]
758 if screen_name
.startswith('@'):
760 screen_name
=screen_name
[1:],
761 include_entities
=False,
763 printNicely(green('You blocked ' + screen_name
+ '.'))
765 printNicely(red('A name should begin with a \'@\''))
772 t
= Twitter(auth
=authen())
773 screen_name
= g
['stuff'].split()[0]
774 if screen_name
.startswith('@'):
776 screen_name
=screen_name
[1:],
777 include_entities
=False,
779 printNicely(green('Unblock ' + screen_name
+ ' success!'))
781 printNicely(red('A name should begin with a \'@\''))
786 Report a user as a spam account
788 t
= Twitter(auth
=authen())
789 screen_name
= g
['stuff'].split()[0]
790 if screen_name
.startswith('@'):
792 screen_name
=screen_name
[1:])
793 printNicely(green('You reported ' + screen_name
+ '.'))
795 printNicely(red('Sorry I can\'t understand.'))
803 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
804 # Get list name and owner
806 owner
, slug
= list_name
.split('/')
807 if slug
.startswith('@'):
812 light_magenta('List name should follow "@owner/list_name" format.'))
813 raise Exception('Wrong list name')
820 rel
= t
.lists
.list(screen_name
=g
['original_name'])
824 printNicely(light_magenta('You belong to no lists :)'))
831 owner
, slug
= get_slug()
832 res
= t
.lists
.statuses(
834 owner_screen_name
=owner
,
836 include_entities
=False)
846 owner
, slug
= get_slug()
850 while next_cursor
!= 0:
853 owner_screen_name
=owner
,
855 include_entities
=False)
857 rel
[u
['name']] = '@' + u
['screen_name']
858 next_cursor
= m
['next_cursor']
859 printNicely('All: ' + str(len(rel
)) + ' members.')
861 user
= ' ' + cycle_color(name
)
862 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
866 def list_subscribers(t
):
870 owner
, slug
= get_slug()
874 while next_cursor
!= 0:
875 m
= t
.lists
.subscribers(
877 owner_screen_name
=owner
,
879 include_entities
=False)
881 rel
[u
['name']] = '@' + u
['screen_name']
882 next_cursor
= m
['next_cursor']
883 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
885 user
= ' ' + cycle_color(name
)
886 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
892 Add specific user to a list
894 owner
, slug
= get_slug()
896 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
897 if user_name
.startswith('@'):
898 user_name
= user_name
[1:]
900 t
.lists
.members
.create(
902 owner_screen_name
=owner
,
903 screen_name
=user_name
)
904 printNicely(green('Added.'))
906 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
911 Remove specific user from a list
913 owner
, slug
= get_slug()
915 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
916 if user_name
.startswith('@'):
917 user_name
= user_name
[1:]
919 t
.lists
.members
.destroy(
921 owner_screen_name
=owner
,
922 screen_name
=user_name
)
923 printNicely(green('Gone.'))
925 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
928 def list_subscribe(t
):
932 owner
, slug
= get_slug()
935 t
.lists
.subscribers
.create(
937 owner_screen_name
=owner
)
938 printNicely(green('Done.'))
941 light_magenta('I\'m sorry you can not subscribe to this list.'))
944 def list_unsubscribe(t
):
948 owner
, slug
= get_slug()
951 t
.lists
.subscribers
.destroy(
953 owner_screen_name
=owner
)
954 printNicely(green('Done.'))
957 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
966 while next_cursor
!= 0:
967 res
= t
.lists
.ownerships(
968 screen_name
=g
['original_name'],
971 next_cursor
= res
['next_cursor']
975 printNicely(light_magenta('You own no lists :)'))
982 name
= raw_input(light_magenta('New list\'s name: '))
983 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
984 description
= raw_input(light_magenta('New list\'s description: '))
989 description
=description
)
990 printNicely(green(name
+ ' list is created.'))
992 printNicely(red('Oops something is wrong with Twitter :('))
999 slug
= raw_input(light_magenta('Your list that you want to update: '))
1000 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1001 mode
= raw_input(light_magenta('Update mode (public/private): '))
1002 description
= raw_input(light_magenta('Update description: '))
1006 slug
='-'.join(slug
.split()),
1007 owner_screen_name
=g
['original_name'],
1010 description
=description
)
1014 owner_screen_name
=g
['original_name'],
1016 description
=description
)
1017 printNicely(green(slug
+ ' list is updated.'))
1019 printNicely(red('Oops something is wrong with Twitter :('))
1026 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1029 slug
='-'.join(slug
.split()),
1030 owner_screen_name
=g
['original_name'])
1031 printNicely(green(slug
+ ' list is deleted.'))
1033 printNicely(red('Oops something is wrong with Twitter :('))
1040 t
= Twitter(auth
=authen())
1041 # List all lists or base on action
1043 g
['list_action'] = g
['stuff'].split()[0]
1050 'all_mem': list_members
,
1051 'all_sub': list_subscribers
,
1054 'sub': list_subscribe
,
1055 'unsub': list_unsubscribe
,
1058 'update': list_update
,
1062 return action_ary
[g
['list_action']](t
)
1064 printNicely(red('Please try again.'))
1072 target
= g
['stuff'].split()[0]
1074 args
= parse_arguments()
1076 if g
['stuff'].split()[-1] == '-f':
1077 guide
= 'To ignore an option, just hit Enter key.'
1078 printNicely(light_magenta(guide
))
1079 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1080 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1081 args
.filter = filter(None, only
.split(','))
1082 args
.ignore
= filter(None, ignore
.split(','))
1083 elif g
['stuff'].split()[-1] == '-d':
1084 args
.filter = c
['ONLY_LIST']
1085 args
.ignore
= c
['IGNORE_LIST']
1087 printNicely(red('Sorry, wrong format.'))
1090 if target
== 'public':
1091 keyword
= g
['stuff'].split()[1]
1092 if keyword
[0] == '#':
1093 keyword
= keyword
[1:]
1095 g
['stream_stop'] = True
1096 args
.track_keywords
= keyword
1098 th
= threading
.Thread(
1106 elif target
== 'mine':
1108 g
['stream_stop'] = True
1110 th
= threading
.Thread(
1115 g
['original_name']))
1120 printNicely(cyan('Only: ' + str(args
.filter)))
1122 printNicely(red('Ignore: ' + str(args
.ignore
)))
1125 printNicely(red('Sorry I can\'t understand.'))
1130 Unix's command `cal`
1133 rel
= os
.popen('cal').read().split('\n')
1136 show_calendar(month
, date
, rel
)
1141 List and change theme
1145 for theme
in g
['themes']:
1146 line
= light_magenta(theme
)
1147 if c
['THEME'] == theme
:
1148 line
= ' ' * 2 + light_yellow('* ') + line
1150 line
= ' ' * 4 + line
1156 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1157 # Redefine decorated_name
1158 g
['decorated_name'] = lambda x
: color_func(
1159 c
['DECORATED_NAME'])(
1161 printNicely(green('Theme changed.'))
1163 printNicely(red('No such theme exists.'))
1168 Browse and change config
1170 all_config
= get_all_config()
1171 g
['stuff'] = g
['stuff'].strip()
1174 for k
in all_config
:
1176 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1178 guide
= 'Detailed explanation can be found at ' + \
1179 color_func(c
['TWEET']['link'])(
1180 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1182 # Print specific config
1183 elif len(g
['stuff'].split()) == 1:
1184 if g
['stuff'] in all_config
:
1187 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1190 printNicely(red('No such config key.'))
1191 # Print specific config's default value
1192 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1193 key
= g
['stuff'].split()[0]
1195 value
= get_default_config(key
)
1196 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1198 except Exception as e
:
1200 # Delete specific config key in config file
1201 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1202 key
= g
['stuff'].split()[0]
1205 printNicely(green('Config key is dropped.'))
1206 except Exception as e
:
1208 # Set specific config
1209 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1210 key
= g
['stuff'].split()[0]
1211 value
= g
['stuff'].split()[-1]
1212 if key
== 'THEME' and not validate_theme(value
):
1213 printNicely(red('Invalid theme\'s value.'))
1216 set_config(key
, value
)
1217 # Apply theme immediately
1219 c
['THEME'] = reload_theme(value
, c
['THEME'])
1220 g
['decorated_name'] = lambda x
: color_func(
1221 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1223 printNicely(green('Updated successfully.'))
1224 except Exception as e
:
1227 printNicely(light_magenta('Sorry I can\'s understand.'))
1230 def help_discover():
1235 # Discover the world
1237 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1238 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1239 'You can try ' + light_green('trend US') + ' or ' + \
1240 light_green('trend JP Tokyo') + '.\n'
1241 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1242 light_green('home 7') + ' will show 7 tweets.\n'
1244 light_green('notification') + ' will show your recent notification.\n'
1245 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1246 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1247 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1248 magenta('@mdo') + '.\n'
1249 usage
+= s
* 2 + light_green('view @mdo') + \
1250 ' will show ' + magenta('@mdo') + '\'s home.\n'
1251 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1252 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1253 'Search can be performed with or without hashtag.\n'
1264 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1265 usage
+= s
* 2 + light_green('t oops ') + \
1266 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1268 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1269 light_yellow('[id=12]') + '.\n'
1271 light_green('quote 12 ') + ' will quote the tweet with ' + \
1272 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1273 'the quote will be canceled.\n'
1275 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1276 light_yellow('[id=12]') + '.\n'
1277 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1278 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1279 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1280 light_yellow('oops') + '" to tweet with ' + \
1281 light_yellow('[id=12]') + '.\n'
1283 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1284 light_yellow('[id=12]') + '.\n'
1286 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1287 light_yellow('[id=12]') + '.\n'
1289 light_green('del 12 ') + ' will delete tweet with ' + \
1290 light_yellow('[id=12]') + '.\n'
1291 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1292 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1293 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1294 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1298 def help_messages():
1305 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1306 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1307 light_green('inbox 7') + ' will show newest 7 messages.\n'
1308 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1309 light_yellow('[thread_id=2]') + '.\n'
1310 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1311 magenta('@dtvd88') + '.\n'
1312 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1313 light_yellow('[message_id=5]') + '.\n'
1317 def help_friends_and_followers():
1319 Friends and Followers
1322 # Follower and following
1324 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1326 light_green('ls fl') + \
1327 ' will list all followers (people who are following you).\n'
1329 light_green('ls fr') + \
1330 ' will list all friends (people who you are following).\n'
1331 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1332 magenta('@dtvd88') + '.\n'
1333 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1334 magenta('@dtvd88') + '.\n'
1335 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1336 magenta('@dtvd88') + '.\n'
1337 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1338 magenta('@dtvd88') + '.\n'
1339 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1340 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1341 magenta('@dtvd88') + '.\n'
1342 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1343 magenta('@dtvd88') + '.\n'
1344 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1345 magenta('@dtvd88') + ' as a spam account.\n'
1356 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1357 usage
+= s
* 2 + light_green('list') + \
1358 ' will show all lists you are belong to.\n'
1359 usage
+= s
* 2 + light_green('list home') + \
1360 ' will show timeline of list. You will be asked for list\'s name.\n'
1361 usage
+= s
* 2 + light_green('list all_mem') + \
1362 ' will show list\'s all members.\n'
1363 usage
+= s
* 2 + light_green('list all_sub') + \
1364 ' will show list\'s all subscribers.\n'
1365 usage
+= s
* 2 + light_green('list add') + \
1366 ' will add specific person to a list owned by you.' + \
1367 ' You will be asked for list\'s name and person\'s name.\n'
1368 usage
+= s
* 2 + light_green('list rm') + \
1369 ' will remove specific person from a list owned by you.' + \
1370 ' You will be asked for list\'s name and person\'s name.\n'
1371 usage
+= s
* 2 + light_green('list sub') + \
1372 ' will subscribe you to a specific list.\n'
1373 usage
+= s
* 2 + light_green('list unsub') + \
1374 ' will unsubscribe you from a specific list.\n'
1375 usage
+= s
* 2 + light_green('list own') + \
1376 ' will show all list owned by you.\n'
1377 usage
+= s
* 2 + light_green('list new') + \
1378 ' will create a new list.\n'
1379 usage
+= s
* 2 + light_green('list update') + \
1380 ' will update a list owned by you.\n'
1381 usage
+= s
* 2 + light_green('list del') + \
1382 ' will delete a list owned by you.\n'
1393 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1394 usage
+= s
* 2 + light_green('switch public #AKB') + \
1395 ' will switch to public stream and follow "' + \
1396 light_yellow('AKB') + '" keyword.\n'
1397 usage
+= s
* 2 + light_green('switch mine') + \
1398 ' will switch to your personal stream.\n'
1399 usage
+= s
* 2 + light_green('switch mine -f ') + \
1400 ' will prompt to enter the filter.\n'
1401 usage
+= s
* 3 + light_yellow('Only nicks') + \
1402 ' filter will decide nicks will be INCLUDE ONLY.\n'
1403 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1404 ' filter will decide nicks will be EXCLUDE.\n'
1405 usage
+= s
* 2 + light_green('switch mine -d') + \
1406 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1415 h
, w
= os
.popen('stty size', 'r').read().split()
1418 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1419 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1420 usage
+= s
+ 'You are ' + \
1421 light_yellow('already') + ' on your personal stream.\n'
1422 usage
+= s
+ 'Any update from Twitter will show up ' + \
1423 light_yellow('immediately') + '.\n'
1424 usage
+= s
+ 'In addition, following commands are available right now:\n'
1425 # Twitter help section
1427 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1428 usage
+= s
* 2 + light_green('h discover') + \
1429 ' will show help for discover commands.\n'
1430 usage
+= s
* 2 + light_green('h tweets') + \
1431 ' will show help for tweets commands.\n'
1432 usage
+= s
* 2 + light_green('h messages') + \
1433 ' will show help for messages commands.\n'
1434 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1435 ' will show help for friends and followers commands.\n'
1436 usage
+= s
* 2 + light_green('h list') + \
1437 ' will show help for list commands.\n'
1438 usage
+= s
* 2 + light_green('h stream') + \
1439 ' will show help for stream commands.\n'
1442 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1443 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1444 'will be evaluate by Python interpreter.\n'
1445 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1446 ' for current month.\n'
1449 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1450 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1451 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1452 ' theme immediately.\n'
1453 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1455 light_green('config ASCII_ART') + ' will output current value of ' +\
1456 light_yellow('ASCII_ART') + ' config key.\n'
1458 light_green('config TREND_MAX default') + ' will output default value of ' + \
1459 light_yellow('TREND_MAX') + ' config key.\n'
1461 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1462 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1464 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1465 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1466 light_yellow('True') + '.\n'
1469 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1470 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1471 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1472 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1473 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1474 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1477 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1478 usage
+= s
+ 'Have fun and hang tight! \n'
1481 'discover': help_discover
,
1482 'tweets': help_tweets
,
1483 'messages': help_messages
,
1484 'friends_and_followers': help_friends_and_followers
,
1486 'stream': help_stream
,
1491 lambda: printNicely(red('No such command.'))
1499 Pause stream display
1502 printNicely(green('Stream is paused'))
1510 printNicely(green('Stream is running back now'))
1526 printNicely(green('See you next time :)'))
1534 Reset prefix of line
1537 if c
.get('USER_JSON_ERROR'):
1538 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1539 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1541 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1544 printNicely(str(eval(g
['cmd'])))
1594 # Handle function set
1644 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1649 Listen to user's input
1654 ['public', 'mine'], # switch
1671 ['image'], # show image
1673 ['fl', 'fr'], # list
1675 [i
for i
in g
['message_threads']], # sent
1700 [key
for key
in dict(get_all_config())], # config
1701 g
['themes'], # theme
1706 'friends_and_followers',
1716 init_interactive_shell(d
)
1723 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1726 # Save cmd to compare with readline buffer
1727 g
['cmd'] = line
.strip()
1728 # Get short cmd to pass to handle function
1730 cmd
= line
.split()[0]
1733 # Lock the semaphore
1735 # Save cmd to global variable and call process
1736 g
['stuff'] = ' '.join(line
.split()[1:])
1737 # Process the command
1740 if cmd
in ['switch', 't', 'rt', 'rep']:
1744 # Release the semaphore lock
1749 printNicely(red('OMG something is wrong with Twitter right now.'))
1752 def stream(domain
, args
, name
='Rainbow Stream'):
1758 c
['USER_DOMAIN']: name
,
1759 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1760 c
['SITE_DOMAIN']: name
,
1763 ascii_art(art_dict
[domain
])
1764 # These arguments are optional:
1766 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1768 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1771 if args
.track_keywords
:
1772 query_args
['track'] = args
.track_keywords
1774 stream
= TwitterStream(
1779 if domain
== c
['USER_DOMAIN']:
1780 tweet_iter
= stream
.user(**query_args
)
1781 elif domain
== c
['SITE_DOMAIN']:
1782 tweet_iter
= stream
.site(**query_args
)
1784 if args
.track_keywords
:
1785 tweet_iter
= stream
.statuses
.filter(**query_args
)
1787 tweet_iter
= stream
.statuses
.sample()
1788 # Block new stream until other one exits
1789 StreamLock
.acquire()
1790 g
['stream_stop'] = False
1791 for tweet
in tweet_iter
:
1793 printNicely("-- None --")
1794 elif tweet
is Timeout
:
1795 if(g
['stream_stop']):
1796 StreamLock
.release()
1798 elif tweet
is HeartbeatTimeout
:
1799 printNicely("-- Heartbeat Timeout --")
1800 guide
= light_magenta("You can use ") + \
1801 light_green("switch") + \
1802 light_magenta(" command to return to your stream.\n")
1803 guide
+= light_magenta("Type ") + \
1804 light_green("h stream") + \
1805 light_magenta(" for more details.")
1807 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1809 StreamLock
.release()
1811 elif tweet
is Hangup
:
1812 printNicely("-- Hangup --")
1813 elif tweet
.get('text'):
1814 # Check the semaphore pause and lock (stream process only)
1822 keyword
=args
.track_keywords
,
1827 # Current readline buffer
1828 current_buffer
= readline
.get_line_buffer().strip()
1829 # There is an unexpected behaviour in MacOSX readline + Python 2:
1830 # after completely delete a word after typing it,
1831 # somehow readline buffer still contains
1832 # the 1st character of that word
1833 if current_buffer
and g
['cmd'] != current_buffer
:
1835 g
['decorated_name'](g
['PREFIX']) + str2u(current_buffer
))
1837 elif not c
['HIDE_PROMPT']:
1838 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1840 elif tweet
.get('direct_message'):
1841 # Check the semaphore pause and lock (stream process only)
1846 print_message(tweet
['direct_message'])
1847 elif tweet
.get('event'):
1848 g
['events'].append(tweet
)
1850 except TwitterHTTPError
:
1853 magenta("We have maximum connection problem with twitter'stream API right now :("))
1861 args
= parse_arguments()
1864 except TwitterHTTPError
:
1867 magenta("We have connection problem with twitter'stream API right now :("))
1868 printNicely(magenta("Let's try again later."))
1871 # Spawn stream thread
1872 th
= threading
.Thread(
1877 g
['original_name']))
1880 # Start listen process