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 c
['original_name'] = g
['original_name'] = screen_name
[1:]
126 g
['full_name'] = name
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']
134 g
['message_threads'] = {}
139 # Init tweet dict and message dict
141 c
['message_dict'] = []
143 c
['IMAGE_ON_TERM'] = args
.image_on_term
144 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
146 c
['IGNORE_LIST'] += build_mute_dict()
153 t
= Twitter(auth
=authen())
154 # Get country and town
156 country
= g
['stuff'].split()[0]
160 town
= g
['stuff'].split()[1]
163 avail
= t
.trends
.available()
166 trends
= t
.trends
.place(_id
=1)[0]['trends']
169 for location
in avail
:
170 # Search for country and Town
172 if location
['countryCode'] == country \
173 and location
['placeType']['name'] == 'Town' \
174 and location
['name'] == town
:
175 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
177 # Search for country only
179 if location
['countryCode'] == country \
180 and location
['placeType']['name'] == 'Country':
181 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
189 t
= Twitter(auth
=authen())
190 num
= c
['HOME_TWEET_NUM']
191 if g
['stuff'].isdigit():
192 num
= int(g
['stuff'])
193 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
202 t
= Twitter(auth
=authen())
203 num
= c
['HOME_TWEET_NUM']
204 if g
['stuff'].isdigit():
205 num
= int(g
['stuff'])
206 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
213 Show profile of a specific user
215 t
= Twitter(auth
=authen())
216 screen_name
= g
['stuff'].split()[0]
217 if screen_name
.startswith('@'):
220 screen_name
=screen_name
[1:],
221 include_entities
=False)
224 printNicely(red('Omg no user.'))
226 printNicely(red('A name should begin with a \'@\''))
233 t
= Twitter(auth
=authen())
234 user
= g
['stuff'].split()[0]
237 num
= int(g
['stuff'].split()[1])
239 num
= c
['HOME_TWEET_NUM']
240 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
244 printNicely(red('A name should begin with a \'@\''))
251 t
= Twitter(auth
=authen())
253 query
= g
['stuff'].strip()
254 type = c
['SEARCH_TYPE']
255 if type not in ['mixed', 'recent', 'popular']:
257 max_record
= c
['SEARCH_MAX_RECORD']
258 count
= min(max_record
, 100)
260 rel
= t
.search
.tweets(
267 printNicely('Newest tweets:')
268 for i
in reversed(xrange(count
)):
269 draw(t
=rel
[i
], keyword
=query
)
272 printNicely(magenta('I\'m afraid there is no result'))
279 t
= Twitter(auth
=authen())
280 t
.statuses
.update(status
=g
['stuff'])
287 t
= Twitter(auth
=authen())
289 id = int(g
['stuff'].split()[0])
291 printNicely(red('Sorry I can\'t understand.'))
293 tid
= c
['tweet_dict'][id]
294 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
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 tweet
= t
.statuses
.show(id=tid
)
311 formater
= format_quote(tweet
)
315 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
316 comment
= raw_input(prefix
)
318 quote
= comment
.join(formater
.split('#comment'))
319 t
.statuses
.update(status
=quote
)
321 printNicely(light_magenta('No text added.'))
328 t
= Twitter(auth
=authen())
331 id = int(g
['stuff'].split()[0])
333 printNicely(red('Sorry I can\'t understand.'))
335 tid
= c
['tweet_dict'][id]
336 # Get display num if exist
338 num
= int(g
['stuff'].split()[1])
340 num
= c
['RETWEETS_SHOW_NUM']
341 # Get result and display
342 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
344 printNicely(magenta('This tweet has no retweet.'))
346 for tweet
in reversed(rt_ary
):
355 t
= Twitter(auth
=authen())
357 id = int(g
['stuff'].split()[0])
359 printNicely(red('Sorry I can\'t understand.'))
361 tid
= c
['tweet_dict'][id]
362 tweet
= t
.statuses
.show(id=tid
)
363 limit
= c
['CONVERSATION_MAX']
365 thread_ref
.append(tweet
)
366 prev_tid
= tweet
['in_reply_to_status_id']
367 while prev_tid
and limit
:
369 tweet
= t
.statuses
.show(id=prev_tid
)
370 prev_tid
= tweet
['in_reply_to_status_id']
371 thread_ref
.append(tweet
)
373 for tweet
in reversed(thread_ref
):
382 t
= Twitter(auth
=authen())
384 id = int(g
['stuff'].split()[0])
386 printNicely(red('Sorry I can\'t understand.'))
388 tid
= c
['tweet_dict'][id]
389 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
390 status
= ' '.join(g
['stuff'].split()[1:])
391 status
= '@' + user
+ ' ' + str2u(status
)
392 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
399 t
= Twitter(auth
=authen())
401 id = int(g
['stuff'].split()[0])
403 printNicely(red('Sorry I can\'t understand.'))
405 tid
= c
['tweet_dict'][id]
406 t
.favorites
.create(_id
=tid
, include_entities
=False)
407 printNicely(green('Favorited.'))
408 draw(t
.statuses
.show(id=tid
))
416 t
= Twitter(auth
=authen())
418 id = int(g
['stuff'].split()[0])
420 printNicely(red('Sorry I can\'t understand.'))
422 tid
= c
['tweet_dict'][id]
423 t
.favorites
.destroy(_id
=tid
)
424 printNicely(green('Okay it\'s unfavorited.'))
425 draw(t
.statuses
.show(id=tid
))
433 t
= Twitter(auth
=authen())
435 id = int(g
['stuff'].split()[0])
437 printNicely(red('Sorry I can\'t understand.'))
439 tid
= c
['tweet_dict'][id]
440 t
.statuses
.destroy(id=tid
)
441 printNicely(green('Okay it\'s gone.'))
448 t
= Twitter(auth
=authen())
450 target
= g
['stuff'].split()[0]
451 if target
!= 'image':
453 id = int(g
['stuff'].split()[1])
454 tid
= c
['tweet_dict'][id]
455 tweet
= t
.statuses
.show(id=tid
)
456 media
= tweet
['entities']['media']
458 res
= requests
.get(m
['media_url'])
459 img
= Image
.open(BytesIO(res
.content
))
462 printNicely(red('Sorry I can\'t show this image.'))
469 t
= Twitter(auth
=authen())
471 if not g
['stuff'].isdigit():
473 tid
= c
['tweet_dict'][int(g
['stuff'])]
474 tweet
= t
.statuses
.show(id=tid
)
475 link_prefix
= ('http://', 'https://')
476 link_ary
= [u
for u
in tweet
['text'].split()
477 if u
.startswith(link_prefix
)]
479 printNicely(light_magenta('No url here @.@!'))
481 for link
in link_ary
:
482 webbrowser
.open(link
)
484 printNicely(red('Sorry I can\'t open url in this tweet.'))
491 t
= Twitter(auth
=authen())
492 num
= c
['MESSAGES_DISPLAY']
493 if g
['stuff'].isdigit():
499 inbox
= inbox
+ t
.direct_messages(
502 include_entities
=False,
507 inbox
= inbox
+ t
.direct_messages(
510 include_entities
=False,
514 num
= c
['MESSAGES_DISPLAY']
515 if g
['stuff'].isdigit():
520 sent
= sent
+ t
.direct_messages
.sent(
523 include_entities
=False,
528 sent
= sent
+ t
.direct_messages
.sent(
531 include_entities
=False,
536 uniq_inbox
= list(set(
537 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
539 uniq_sent
= list(set(
540 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
542 for partner
in uniq_inbox
:
543 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
545 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
546 d
[partner
] = inbox_ary
+ sent_ary
547 for partner
in uniq_sent
:
550 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
551 g
['message_threads'] = print_threads(d
)
556 View a thread of message
559 thread_id
= int(g
['stuff'])
561 g
['message_threads'][thread_id
],
565 printNicely(red('No such thread.'))
570 Send a direct message
572 t
= Twitter(auth
=authen())
574 user
= g
['stuff'].split()[0]
575 if user
[0].startswith('@'):
576 content
= ' '.join(g
['stuff'].split()[1:])
577 t
.direct_messages
.new(
578 screen_name
=user
[1:],
581 printNicely(green('Message sent.'))
583 printNicely(red('A name should begin with a \'@\''))
585 printNicely(red('Sorry I can\'t understand.'))
592 t
= Twitter(auth
=authen())
594 id = int(g
['stuff'].split()[0])
596 printNicely(red('Sorry I can\'t understand.'))
597 mid
= c
['message_dict'][id]
598 t
.direct_messages
.destroy(id=mid
)
599 printNicely(green('Message deleted.'))
604 List friends for followers
606 t
= Twitter(auth
=authen())
609 name
= g
['stuff'].split()[1]
610 if name
.startswith('@'):
613 printNicely(red('A name should begin with a \'@\''))
614 raise Exception('Invalid name')
616 name
= g
['original_name']
617 # Get list followers or friends
619 target
= g
['stuff'].split()[0]
621 printNicely(red('Omg some syntax is wrong.'))
623 d
= {'fl': 'followers', 'fr': 'friends'}
627 while next_cursor
!= 0:
628 list = getattr(t
, d
[target
]).list(
632 include_entities
=False,
634 for u
in list['users']:
635 rel
[u
['name']] = '@' + u
['screen_name']
636 next_cursor
= list['next_cursor']
638 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
640 user
= ' ' + cycle_color(name
)
641 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
649 t
= Twitter(auth
=authen())
650 screen_name
= g
['stuff'].split()[0]
651 if screen_name
.startswith('@'):
652 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
653 printNicely(green('You are following ' + screen_name
+ ' now!'))
655 printNicely(red('A name should begin with a \'@\''))
662 t
= Twitter(auth
=authen())
663 screen_name
= g
['stuff'].split()[0]
664 if screen_name
.startswith('@'):
665 t
.friendships
.destroy(
666 screen_name
=screen_name
[1:],
667 include_entities
=False)
668 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
670 printNicely(red('A name should begin with a \'@\''))
677 t
= Twitter(auth
=authen())
679 screen_name
= g
['stuff'].split()[0]
681 printNicely(red('A name should be specified. '))
683 if screen_name
.startswith('@'):
685 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
686 if isinstance(rel
, dict):
687 printNicely(green(screen_name
+ ' is muted.'))
688 c
['IGNORE_LIST'] += [unc(screen_name
)]
689 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
691 printNicely(red(rel
))
693 printNicely(red('Something is wrong, can not mute now :('))
695 printNicely(red('A name should begin with a \'@\''))
702 t
= Twitter(auth
=authen())
704 screen_name
= g
['stuff'].split()[0]
706 printNicely(red('A name should be specified. '))
708 if screen_name
.startswith('@'):
710 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
711 if isinstance(rel
, dict):
712 printNicely(green(screen_name
+ ' is unmuted.'))
713 c
['IGNORE_LIST'].remove(screen_name
)
715 printNicely(red(rel
))
717 printNicely(red('Maybe you are not muting this person ?'))
719 printNicely(red('A name should begin with a \'@\''))
726 # Get dict of muting users
727 md
= build_mute_dict(dict_data
=True)
728 printNicely('All: ' + str(len(md
)) + ' people.')
730 user
= ' ' + cycle_color(md
[name
])
731 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
733 # Update from Twitter
734 c
['IGNORE_LIST'] = [n
for n
in md
]
741 t
= Twitter(auth
=authen())
742 screen_name
= g
['stuff'].split()[0]
743 if screen_name
.startswith('@'):
745 screen_name
=screen_name
[1:],
746 include_entities
=False,
748 printNicely(green('You blocked ' + screen_name
+ '.'))
750 printNicely(red('A name should begin with a \'@\''))
757 t
= Twitter(auth
=authen())
758 screen_name
= g
['stuff'].split()[0]
759 if screen_name
.startswith('@'):
761 screen_name
=screen_name
[1:],
762 include_entities
=False,
764 printNicely(green('Unblock ' + screen_name
+ ' success!'))
766 printNicely(red('A name should begin with a \'@\''))
771 Report a user as a spam account
773 t
= Twitter(auth
=authen())
774 screen_name
= g
['stuff'].split()[0]
775 if screen_name
.startswith('@'):
777 screen_name
=screen_name
[1:])
778 printNicely(green('You reported ' + screen_name
+ '.'))
780 printNicely(red('Sorry I can\'t understand.'))
788 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
789 # Get list name and owner
791 owner
, slug
= list_name
.split('/')
792 if slug
.startswith('@'):
797 light_magenta('List name should follow "@owner/list_name" format.'))
798 raise Exception('Wrong list name')
805 rel
= t
.lists
.list(screen_name
=g
['original_name'])
809 printNicely(light_magenta('You belong to no lists :)'))
816 owner
, slug
= get_slug()
817 res
= t
.lists
.statuses(
819 owner_screen_name
=owner
,
821 include_entities
=False)
831 owner
, slug
= get_slug()
835 while next_cursor
!= 0:
838 owner_screen_name
=owner
,
840 include_entities
=False)
842 rel
[u
['name']] = '@' + u
['screen_name']
843 next_cursor
= m
['next_cursor']
844 printNicely('All: ' + str(len(rel
)) + ' members.')
846 user
= ' ' + cycle_color(name
)
847 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
851 def list_subscribers(t
):
855 owner
, slug
= get_slug()
859 while next_cursor
!= 0:
860 m
= t
.lists
.subscribers(
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
)) + ' subscribers.')
870 user
= ' ' + cycle_color(name
)
871 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
877 Add specific user to a list
879 owner
, slug
= get_slug()
881 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
882 if user_name
.startswith('@'):
883 user_name
= user_name
[1:]
885 t
.lists
.members
.create(
887 owner_screen_name
=owner
,
888 screen_name
=user_name
)
889 printNicely(green('Added.'))
891 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
896 Remove specific user from a list
898 owner
, slug
= get_slug()
900 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
901 if user_name
.startswith('@'):
902 user_name
= user_name
[1:]
904 t
.lists
.members
.destroy(
906 owner_screen_name
=owner
,
907 screen_name
=user_name
)
908 printNicely(green('Gone.'))
910 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
913 def list_subscribe(t
):
917 owner
, slug
= get_slug()
920 t
.lists
.subscribers
.create(
922 owner_screen_name
=owner
)
923 printNicely(green('Done.'))
926 light_magenta('I\'m sorry you can not subscribe to this list.'))
929 def list_unsubscribe(t
):
933 owner
, slug
= get_slug()
936 t
.lists
.subscribers
.destroy(
938 owner_screen_name
=owner
)
939 printNicely(green('Done.'))
942 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
951 while next_cursor
!= 0:
952 res
= t
.lists
.ownerships(
953 screen_name
=g
['original_name'],
956 next_cursor
= res
['next_cursor']
960 printNicely(light_magenta('You own no lists :)'))
967 name
= raw_input(light_magenta('New list\'s name: '))
968 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
969 description
= raw_input(light_magenta('New list\'s description: '))
974 description
=description
)
975 printNicely(green(name
+ ' list is created.'))
977 printNicely(red('Oops something is wrong with Twitter :('))
984 slug
= raw_input(light_magenta('Your list that you want to update: '))
985 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
986 mode
= raw_input(light_magenta('Update mode (public/private): '))
987 description
= raw_input(light_magenta('Update description: '))
991 slug
='-'.join(slug
.split()),
992 owner_screen_name
=g
['original_name'],
995 description
=description
)
999 owner_screen_name
=g
['original_name'],
1001 description
=description
)
1002 printNicely(green(slug
+ ' list is updated.'))
1004 printNicely(red('Oops something is wrong with Twitter :('))
1011 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1014 slug
='-'.join(slug
.split()),
1015 owner_screen_name
=g
['original_name'])
1016 printNicely(green(slug
+ ' list is deleted.'))
1018 printNicely(red('Oops something is wrong with Twitter :('))
1025 t
= Twitter(auth
=authen())
1026 # List all lists or base on action
1028 g
['list_action'] = g
['stuff'].split()[0]
1035 'all_mem': list_members
,
1036 'all_sub': list_subscribers
,
1039 'sub': list_subscribe
,
1040 'unsub': list_unsubscribe
,
1043 'update': list_update
,
1047 return action_ary
[g
['list_action']](t
)
1049 printNicely(red('Please try again.'))
1057 target
= g
['stuff'].split()[0]
1059 args
= parse_arguments()
1061 if g
['stuff'].split()[-1] == '-f':
1062 guide
= 'To ignore an option, just hit Enter key.'
1063 printNicely(light_magenta(guide
))
1064 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1065 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1066 args
.filter = filter(None, only
.split(','))
1067 args
.ignore
= filter(None, ignore
.split(','))
1068 elif g
['stuff'].split()[-1] == '-d':
1069 args
.filter = c
['ONLY_LIST']
1070 args
.ignore
= c
['IGNORE_LIST']
1072 printNicely(red('Sorry, wrong format.'))
1075 if target
== 'public':
1076 keyword
= g
['stuff'].split()[1]
1077 if keyword
[0] == '#':
1078 keyword
= keyword
[1:]
1080 g
['stream_stop'] = True
1081 args
.track_keywords
= keyword
1083 th
= threading
.Thread(
1091 elif target
== 'mine':
1093 g
['stream_stop'] = True
1095 th
= threading
.Thread(
1100 g
['original_name']))
1105 printNicely(cyan('Only: ' + str(args
.filter)))
1107 printNicely(red('Ignore: ' + str(args
.ignore
)))
1110 printNicely(red('Sorry I can\'t understand.'))
1115 Unix's command `cal`
1118 rel
= os
.popen('cal').read().split('\n')
1121 show_calendar(month
, date
, rel
)
1126 List and change theme
1130 for theme
in g
['themes']:
1131 line
= light_magenta(theme
)
1132 if c
['THEME'] == theme
:
1133 line
= ' ' * 2 + light_yellow('* ') + line
1135 line
= ' ' * 4 + line
1141 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1142 # Redefine decorated_name
1143 g
['decorated_name'] = lambda x
: color_func(
1144 c
['DECORATED_NAME'])(
1146 printNicely(green('Theme changed.'))
1148 printNicely(red('No such theme exists.'))
1153 Browse and change config
1155 all_config
= get_all_config()
1156 g
['stuff'] = g
['stuff'].strip()
1159 for k
in all_config
:
1161 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1163 guide
= 'Detailed explanation can be found at ' + \
1164 color_func(c
['TWEET']['link'])(
1165 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1167 # Print specific config
1168 elif len(g
['stuff'].split()) == 1:
1169 if g
['stuff'] in all_config
:
1172 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1175 printNicely(red('No such config key.'))
1176 # Print specific config's default value
1177 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1178 key
= g
['stuff'].split()[0]
1180 value
= get_default_config(key
)
1181 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1183 except Exception as e
:
1185 # Delete specific config key in config file
1186 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1187 key
= g
['stuff'].split()[0]
1190 printNicely(green('Config key is dropped.'))
1191 except Exception as e
:
1193 # Set specific config
1194 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1195 key
= g
['stuff'].split()[0]
1196 value
= g
['stuff'].split()[-1]
1197 if key
== 'THEME' and not validate_theme(value
):
1198 printNicely(red('Invalid theme\'s value.'))
1201 set_config(key
, value
)
1202 # Apply theme immediately
1204 c
['THEME'] = reload_theme(value
, c
['THEME'])
1205 g
['decorated_name'] = lambda x
: color_func(
1206 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1208 printNicely(green('Updated successfully.'))
1209 except Exception as e
:
1212 printNicely(light_magenta('Sorry I can\'s understand.'))
1215 def help_discover():
1220 # Discover the world
1222 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1223 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1224 'You can try ' + light_green('trend US') + ' or ' + \
1225 light_green('trend JP Tokyo') + '.\n'
1226 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1227 light_green('home 7') + ' will show 7 tweets.\n'
1228 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1229 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1230 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1231 magenta('@mdo') + '.\n'
1232 usage
+= s
* 2 + light_green('view @mdo') + \
1233 ' will show ' + magenta('@mdo') + '\'s home.\n'
1234 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1235 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1236 'Search can be performed with or without hashtag.\n'
1247 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1248 usage
+= s
* 2 + light_green('t oops ') + \
1249 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1251 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1252 light_yellow('[id=12]') + '.\n'
1254 light_green('quote 12 ') + ' will quote the tweet with ' + \
1255 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1256 'the quote will be canceled.\n'
1258 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1259 light_yellow('[id=12]') + '.\n'
1260 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1261 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1262 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1263 light_yellow('oops') + '" to tweet with ' + \
1264 light_yellow('[id=12]') + '.\n'
1266 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1267 light_yellow('[id=12]') + '.\n'
1269 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1270 light_yellow('[id=12]') + '.\n'
1272 light_green('del 12 ') + ' will delete tweet with ' + \
1273 light_yellow('[id=12]') + '.\n'
1274 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1275 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1276 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1277 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1281 def help_messages():
1288 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1289 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1290 light_green('inbox 7') + ' will show newest 7 messages.\n'
1291 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1292 light_yellow('[thread_id=2]') + '.\n'
1293 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1294 magenta('@dtvd88') + '.\n'
1295 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1296 light_yellow('[message_id=5]') + '.\n'
1300 def help_friends_and_followers():
1302 Friends and Followers
1305 # Follower and following
1307 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1309 light_green('ls fl') + \
1310 ' will list all followers (people who are following you).\n'
1312 light_green('ls fr') + \
1313 ' will list all friends (people who you are following).\n'
1314 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1315 magenta('@dtvd88') + '.\n'
1316 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1317 magenta('@dtvd88') + '.\n'
1318 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1319 magenta('@dtvd88') + '.\n'
1320 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1321 magenta('@dtvd88') + '.\n'
1322 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1323 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1324 magenta('@dtvd88') + '.\n'
1325 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1326 magenta('@dtvd88') + '.\n'
1327 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1328 magenta('@dtvd88') + ' as a spam account.\n'
1339 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1340 usage
+= s
* 2 + light_green('list') + \
1341 ' will show all lists you are belong to.\n'
1342 usage
+= s
* 2 + light_green('list home') + \
1343 ' will show timeline of list. You will be asked for list\'s name.\n'
1344 usage
+= s
* 2 + light_green('list all_mem') + \
1345 ' will show list\'s all members.\n'
1346 usage
+= s
* 2 + light_green('list all_sub') + \
1347 ' will show list\'s all subscribers.\n'
1348 usage
+= s
* 2 + light_green('list add') + \
1349 ' will add specific person to a list owned by you.' + \
1350 ' You will be asked for list\'s name and person\'s name.\n'
1351 usage
+= s
* 2 + light_green('list rm') + \
1352 ' will remove specific person from a list owned by you.' + \
1353 ' You will be asked for list\'s name and person\'s name.\n'
1354 usage
+= s
* 2 + light_green('list sub') + \
1355 ' will subscribe you to a specific list.\n'
1356 usage
+= s
* 2 + light_green('list unsub') + \
1357 ' will unsubscribe you from a specific list.\n'
1358 usage
+= s
* 2 + light_green('list own') + \
1359 ' will show all list owned by you.\n'
1360 usage
+= s
* 2 + light_green('list new') + \
1361 ' will create a new list.\n'
1362 usage
+= s
* 2 + light_green('list update') + \
1363 ' will update a list owned by you.\n'
1364 usage
+= s
* 2 + light_green('list del') + \
1365 ' will delete a list owned by you.\n'
1376 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1377 usage
+= s
* 2 + light_green('switch public #AKB') + \
1378 ' will switch to public stream and follow "' + \
1379 light_yellow('AKB') + '" keyword.\n'
1380 usage
+= s
* 2 + light_green('switch mine') + \
1381 ' will switch to your personal stream.\n'
1382 usage
+= s
* 2 + light_green('switch mine -f ') + \
1383 ' will prompt to enter the filter.\n'
1384 usage
+= s
* 3 + light_yellow('Only nicks') + \
1385 ' filter will decide nicks will be INCLUDE ONLY.\n'
1386 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1387 ' filter will decide nicks will be EXCLUDE.\n'
1388 usage
+= s
* 2 + light_green('switch mine -d') + \
1389 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1398 h
, w
= os
.popen('stty size', 'r').read().split()
1401 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1402 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1403 usage
+= s
+ 'You are ' + \
1404 light_yellow('already') + ' on your personal stream.\n'
1405 usage
+= s
+ 'Any update from Twitter will show up ' + \
1406 light_yellow('immediately') + '.\n'
1407 usage
+= s
+ 'In addition, following commands are available right now:\n'
1408 # Twitter help section
1410 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1411 usage
+= s
* 2 + light_green('h discover') + \
1412 ' will show help for discover commands.\n'
1413 usage
+= s
* 2 + light_green('h tweets') + \
1414 ' will show help for tweets commands.\n'
1415 usage
+= s
* 2 + light_green('h messages') + \
1416 ' will show help for messages commands.\n'
1417 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1418 ' will show help for friends and followers commands.\n'
1419 usage
+= s
* 2 + light_green('h list') + \
1420 ' will show help for list commands.\n'
1421 usage
+= s
* 2 + light_green('h stream') + \
1422 ' will show help for stream commands.\n'
1425 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1426 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1427 'will be evaluate by Python interpreter.\n'
1428 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1429 ' for current month.\n'
1432 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1433 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1434 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1435 ' theme immediately.\n'
1436 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1438 light_green('config ASCII_ART') + ' will output current value of ' +\
1439 light_yellow('ASCII_ART') + ' config key.\n'
1441 light_green('config TREND_MAX default') + ' will output default value of ' + \
1442 light_yellow('TREND_MAX') + ' config key.\n'
1444 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1445 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1447 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1448 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1449 light_yellow('True') + '.\n'
1452 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1453 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1454 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1455 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1456 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1457 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1460 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1461 usage
+= s
+ 'Have fun and hang tight! \n'
1464 'discover': help_discover
,
1465 'tweets': help_tweets
,
1466 'messages': help_messages
,
1467 'friends_and_followers': help_friends_and_followers
,
1469 'stream': help_stream
,
1474 lambda: printNicely(red('No such command.'))
1482 Pause stream display
1485 printNicely(green('Stream is paused'))
1493 printNicely(green('Stream is running back now'))
1509 printNicely(green('See you next time :)'))
1517 Reset prefix of line
1520 if c
.get('USER_JSON_ERROR'):
1521 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1522 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1524 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1527 printNicely(str(eval(g
['cmd'])))
1576 # Handle function set
1625 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1630 Listen to user's input
1635 ['public', 'mine'], # switch
1651 ['image'], # show image
1653 ['fl', 'fr'], # list
1655 [i
for i
in g
['message_threads']], # sent
1680 [key
for key
in dict(get_all_config())], # config
1681 g
['themes'], # theme
1686 'friends_and_followers',
1696 init_interactive_shell(d
)
1703 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1706 # Save cmd to compare with readline buffer
1707 g
['cmd'] = line
.strip()
1708 # Get short cmd to pass to handle function
1710 cmd
= line
.split()[0]
1713 # Lock the semaphore
1715 # Save cmd to global variable and call process
1716 g
['stuff'] = ' '.join(line
.split()[1:])
1717 # Process the command
1720 if cmd
in ['switch', 't', 'rt', 'rep']:
1724 # Release the semaphore lock
1729 printNicely(red('OMG something is wrong with Twitter right now.'))
1732 def stream(domain
, args
, name
='Rainbow Stream'):
1738 c
['USER_DOMAIN']: name
,
1739 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1740 c
['SITE_DOMAIN']: name
,
1743 ascii_art(art_dict
[domain
])
1744 # These arguments are optional:
1746 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1748 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1751 if args
.track_keywords
:
1752 query_args
['track'] = args
.track_keywords
1754 stream
= TwitterStream(
1759 if domain
== c
['USER_DOMAIN']:
1760 tweet_iter
= stream
.user(**query_args
)
1761 elif domain
== c
['SITE_DOMAIN']:
1762 tweet_iter
= stream
.site(**query_args
)
1764 if args
.track_keywords
:
1765 tweet_iter
= stream
.statuses
.filter(**query_args
)
1767 tweet_iter
= stream
.statuses
.sample()
1768 # Block new stream until other one exits
1769 StreamLock
.acquire()
1770 g
['stream_stop'] = False
1771 for tweet
in tweet_iter
:
1773 printNicely("-- None --")
1774 elif tweet
is Timeout
:
1775 if(g
['stream_stop']):
1776 StreamLock
.release()
1778 elif tweet
is HeartbeatTimeout
:
1779 printNicely("-- Heartbeat Timeout --")
1780 guide
= light_magenta("You can use ") + \
1781 light_green("switch") + \
1782 light_magenta(" command to return to your stream.\n")
1783 guide
+= light_magenta("Type ") + \
1784 light_green("h stream") + \
1785 light_magenta(" for more details.")
1787 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1789 StreamLock
.release()
1791 elif tweet
is Hangup
:
1792 printNicely("-- Hangup --")
1793 elif tweet
.get('text'):
1794 # Check the semaphore pause and lock (stream process only)
1802 keyword
=args
.track_keywords
,
1807 # Current readline buffer
1808 current_buffer
= readline
.get_line_buffer().strip()
1809 # There is an unexpected behaviour in MacOSX readline + Python 2:
1810 # after completely delete a word after typing it,
1811 # somehow readline buffer still contains
1812 # the 1st character of that word
1813 if current_buffer
and g
['cmd'] != current_buffer
:
1815 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1817 elif not c
['HIDE_PROMPT']:
1818 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1820 elif tweet
.get('direct_message'):
1821 # Check the semaphore pause and lock (stream process only)
1826 print_message(tweet
['direct_message'])
1827 except TwitterHTTPError
:
1830 magenta("We have maximum connection problem with twitter'stream API right now :("))
1838 args
= parse_arguments()
1841 except TwitterHTTPError
:
1844 magenta("We have connection problem with twitter'stream API right now :("))
1845 printNicely(magenta("Let's try again later."))
1848 # Spawn stream thread
1849 th
= threading
.Thread(
1854 g
['original_name']))
1857 # Start listen process