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'] = {}
140 # Retweet of mine events
144 # Init tweet dict and message dict
146 c
['message_dict'] = []
148 c
['IMAGE_ON_TERM'] = args
.image_on_term
149 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
151 c
['IGNORE_LIST'] += build_mute_dict()
158 t
= Twitter(auth
=authen())
159 # Get country and town
161 country
= g
['stuff'].split()[0]
165 town
= g
['stuff'].split()[1]
168 avail
= t
.trends
.available()
171 trends
= t
.trends
.place(_id
=1)[0]['trends']
174 for location
in avail
:
175 # Search for country and Town
177 if location
['countryCode'] == country \
178 and location
['placeType']['name'] == 'Town' \
179 and location
['name'] == town
:
180 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
182 # Search for country only
184 if location
['countryCode'] == country \
185 and location
['placeType']['name'] == 'Country':
186 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
194 t
= Twitter(auth
=authen())
195 num
= c
['HOME_TWEET_NUM']
196 if g
['stuff'].isdigit():
197 num
= int(g
['stuff'])
198 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
207 g
['events'] = g
['events'] + c
['events']
209 for e
in g
['events']:
213 printNicely(magenta('Nothing at this time.'))
220 t
= Twitter(auth
=authen())
221 num
= c
['HOME_TWEET_NUM']
222 if g
['stuff'].isdigit():
223 num
= int(g
['stuff'])
224 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
231 Show profile of a specific user
233 t
= Twitter(auth
=authen())
234 screen_name
= g
['stuff'].split()[0]
235 if screen_name
.startswith('@'):
238 screen_name
=screen_name
[1:],
239 include_entities
=False)
242 printNicely(red('Omg no user.'))
244 printNicely(red('A name should begin with a \'@\''))
251 t
= Twitter(auth
=authen())
252 user
= g
['stuff'].split()[0]
255 num
= int(g
['stuff'].split()[1])
257 num
= c
['HOME_TWEET_NUM']
258 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
262 printNicely(red('A name should begin with a \'@\''))
269 t
= Twitter(auth
=authen())
271 query
= g
['stuff'].strip()
272 type = c
['SEARCH_TYPE']
273 if type not in ['mixed', 'recent', 'popular']:
275 max_record
= c
['SEARCH_MAX_RECORD']
276 count
= min(max_record
, 100)
278 rel
= t
.search
.tweets(
285 printNicely('Newest tweets:')
286 for i
in reversed(xrange(count
)):
287 draw(t
=rel
[i
], keyword
=query
)
290 printNicely(magenta('I\'m afraid there is no result'))
297 t
= Twitter(auth
=authen())
298 t
.statuses
.update(status
=g
['stuff'])
305 t
= Twitter(auth
=authen())
307 id = int(g
['stuff'].split()[0])
309 printNicely(red('Sorry I can\'t understand.'))
311 tid
= c
['tweet_dict'][id]
312 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
320 t
= Twitter(auth
=authen())
322 id = int(g
['stuff'].split()[0])
324 printNicely(red('Sorry I can\'t understand.'))
326 tid
= c
['tweet_dict'][id]
327 tweet
= t
.statuses
.show(id=tid
)
329 formater
= format_quote(tweet
)
333 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
334 comment
= raw_input(prefix
)
336 quote
= comment
.join(formater
.split('#comment'))
337 t
.statuses
.update(status
=quote
)
339 printNicely(light_magenta('No text added.'))
346 t
= Twitter(auth
=authen())
349 id = int(g
['stuff'].split()[0])
351 printNicely(red('Sorry I can\'t understand.'))
353 tid
= c
['tweet_dict'][id]
354 # Get display num if exist
356 num
= int(g
['stuff'].split()[1])
358 num
= c
['RETWEETS_SHOW_NUM']
359 # Get result and display
360 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
362 printNicely(magenta('This tweet has no retweet.'))
364 for tweet
in reversed(rt_ary
):
373 t
= Twitter(auth
=authen())
375 id = int(g
['stuff'].split()[0])
377 printNicely(red('Sorry I can\'t understand.'))
379 tid
= c
['tweet_dict'][id]
380 tweet
= t
.statuses
.show(id=tid
)
381 limit
= c
['CONVERSATION_MAX']
383 thread_ref
.append(tweet
)
384 prev_tid
= tweet
['in_reply_to_status_id']
385 while prev_tid
and limit
:
387 tweet
= t
.statuses
.show(id=prev_tid
)
388 prev_tid
= tweet
['in_reply_to_status_id']
389 thread_ref
.append(tweet
)
391 for tweet
in reversed(thread_ref
):
400 t
= Twitter(auth
=authen())
402 id = int(g
['stuff'].split()[0])
404 printNicely(red('Sorry I can\'t understand.'))
406 tid
= c
['tweet_dict'][id]
407 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
408 status
= ' '.join(g
['stuff'].split()[1:])
409 status
= '@' + user
+ ' ' + str2u(status
)
410 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
417 t
= Twitter(auth
=authen())
419 id = int(g
['stuff'].split()[0])
421 printNicely(red('Sorry I can\'t understand.'))
423 tid
= c
['tweet_dict'][id]
424 t
.favorites
.create(_id
=tid
, include_entities
=False)
425 printNicely(green('Favorited.'))
426 draw(t
.statuses
.show(id=tid
))
434 t
= Twitter(auth
=authen())
436 id = int(g
['stuff'].split()[0])
438 printNicely(red('Sorry I can\'t understand.'))
440 tid
= c
['tweet_dict'][id]
441 t
.favorites
.destroy(_id
=tid
)
442 printNicely(green('Okay it\'s unfavorited.'))
443 draw(t
.statuses
.show(id=tid
))
451 t
= Twitter(auth
=authen())
453 id = int(g
['stuff'].split()[0])
455 printNicely(red('Sorry I can\'t understand.'))
457 tid
= c
['tweet_dict'][id]
458 t
.statuses
.destroy(id=tid
)
459 printNicely(green('Okay it\'s gone.'))
466 t
= Twitter(auth
=authen())
468 target
= g
['stuff'].split()[0]
469 if target
!= 'image':
471 id = int(g
['stuff'].split()[1])
472 tid
= c
['tweet_dict'][id]
473 tweet
= t
.statuses
.show(id=tid
)
474 media
= tweet
['entities']['media']
476 res
= requests
.get(m
['media_url'])
477 img
= Image
.open(BytesIO(res
.content
))
480 printNicely(red('Sorry I can\'t show this image.'))
487 t
= Twitter(auth
=authen())
489 if not g
['stuff'].isdigit():
491 tid
= c
['tweet_dict'][int(g
['stuff'])]
492 tweet
= t
.statuses
.show(id=tid
)
493 link_prefix
= ('http://', 'https://')
494 link_ary
= [u
for u
in tweet
['text'].split()
495 if u
.startswith(link_prefix
)]
497 printNicely(light_magenta('No url here @.@!'))
499 for link
in link_ary
:
500 webbrowser
.open(link
)
502 printNicely(red('Sorry I can\'t open url in this tweet.'))
509 t
= Twitter(auth
=authen())
510 num
= c
['MESSAGES_DISPLAY']
511 if g
['stuff'].isdigit():
517 inbox
= inbox
+ t
.direct_messages(
520 include_entities
=False,
525 inbox
= inbox
+ t
.direct_messages(
528 include_entities
=False,
532 num
= c
['MESSAGES_DISPLAY']
533 if g
['stuff'].isdigit():
538 sent
= sent
+ t
.direct_messages
.sent(
541 include_entities
=False,
546 sent
= sent
+ t
.direct_messages
.sent(
549 include_entities
=False,
554 uniq_inbox
= list(set(
555 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
557 uniq_sent
= list(set(
558 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
560 for partner
in uniq_inbox
:
561 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
563 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
564 d
[partner
] = inbox_ary
+ sent_ary
565 for partner
in uniq_sent
:
568 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
569 g
['message_threads'] = print_threads(d
)
574 View a thread of message
577 thread_id
= int(g
['stuff'])
579 g
['message_threads'][thread_id
],
583 printNicely(red('No such thread.'))
588 Send a direct message
590 t
= Twitter(auth
=authen())
592 user
= g
['stuff'].split()[0]
593 if user
[0].startswith('@'):
594 content
= ' '.join(g
['stuff'].split()[1:])
595 t
.direct_messages
.new(
596 screen_name
=user
[1:],
599 printNicely(green('Message sent.'))
601 printNicely(red('A name should begin with a \'@\''))
603 printNicely(red('Sorry I can\'t understand.'))
610 t
= Twitter(auth
=authen())
612 id = int(g
['stuff'].split()[0])
614 printNicely(red('Sorry I can\'t understand.'))
615 mid
= c
['message_dict'][id]
616 t
.direct_messages
.destroy(id=mid
)
617 printNicely(green('Message deleted.'))
622 List friends for followers
624 t
= Twitter(auth
=authen())
627 name
= g
['stuff'].split()[1]
628 if name
.startswith('@'):
631 printNicely(red('A name should begin with a \'@\''))
632 raise Exception('Invalid name')
634 name
= g
['original_name']
635 # Get list followers or friends
637 target
= g
['stuff'].split()[0]
639 printNicely(red('Omg some syntax is wrong.'))
641 d
= {'fl': 'followers', 'fr': 'friends'}
645 while next_cursor
!= 0:
646 list = getattr(t
, d
[target
]).list(
650 include_entities
=False,
652 for u
in list['users']:
653 rel
[u
['name']] = '@' + u
['screen_name']
654 next_cursor
= list['next_cursor']
656 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
658 user
= ' ' + cycle_color(name
)
659 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
667 t
= Twitter(auth
=authen())
668 screen_name
= g
['stuff'].split()[0]
669 if screen_name
.startswith('@'):
670 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
671 printNicely(green('You are following ' + screen_name
+ ' now!'))
673 printNicely(red('A name should begin with a \'@\''))
680 t
= Twitter(auth
=authen())
681 screen_name
= g
['stuff'].split()[0]
682 if screen_name
.startswith('@'):
683 t
.friendships
.destroy(
684 screen_name
=screen_name
[1:],
685 include_entities
=False)
686 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
688 printNicely(red('A name should begin with a \'@\''))
695 t
= Twitter(auth
=authen())
697 screen_name
= g
['stuff'].split()[0]
699 printNicely(red('A name should be specified. '))
701 if screen_name
.startswith('@'):
703 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
704 if isinstance(rel
, dict):
705 printNicely(green(screen_name
+ ' is muted.'))
706 c
['IGNORE_LIST'] += [unc(screen_name
)]
707 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
709 printNicely(red(rel
))
711 printNicely(red('Something is wrong, can not mute now :('))
713 printNicely(red('A name should begin with a \'@\''))
720 t
= Twitter(auth
=authen())
722 screen_name
= g
['stuff'].split()[0]
724 printNicely(red('A name should be specified. '))
726 if screen_name
.startswith('@'):
728 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
729 if isinstance(rel
, dict):
730 printNicely(green(screen_name
+ ' is unmuted.'))
731 c
['IGNORE_LIST'].remove(screen_name
)
733 printNicely(red(rel
))
735 printNicely(red('Maybe you are not muting this person ?'))
737 printNicely(red('A name should begin with a \'@\''))
744 # Get dict of muting users
745 md
= build_mute_dict(dict_data
=True)
746 printNicely('All: ' + str(len(md
)) + ' people.')
748 user
= ' ' + cycle_color(md
[name
])
749 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
751 # Update from Twitter
752 c
['IGNORE_LIST'] = [n
for n
in md
]
759 t
= Twitter(auth
=authen())
760 screen_name
= g
['stuff'].split()[0]
761 if screen_name
.startswith('@'):
763 screen_name
=screen_name
[1:],
764 include_entities
=False,
766 printNicely(green('You blocked ' + screen_name
+ '.'))
768 printNicely(red('A name should begin with a \'@\''))
775 t
= Twitter(auth
=authen())
776 screen_name
= g
['stuff'].split()[0]
777 if screen_name
.startswith('@'):
779 screen_name
=screen_name
[1:],
780 include_entities
=False,
782 printNicely(green('Unblock ' + screen_name
+ ' success!'))
784 printNicely(red('A name should begin with a \'@\''))
789 Report a user as a spam account
791 t
= Twitter(auth
=authen())
792 screen_name
= g
['stuff'].split()[0]
793 if screen_name
.startswith('@'):
795 screen_name
=screen_name
[1:])
796 printNicely(green('You reported ' + screen_name
+ '.'))
798 printNicely(red('Sorry I can\'t understand.'))
806 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
807 # Get list name and owner
809 owner
, slug
= list_name
.split('/')
810 if slug
.startswith('@'):
815 light_magenta('List name should follow "@owner/list_name" format.'))
816 raise Exception('Wrong list name')
823 rel
= t
.lists
.list(screen_name
=g
['original_name'])
827 printNicely(light_magenta('You belong to no lists :)'))
834 owner
, slug
= get_slug()
835 res
= t
.lists
.statuses(
837 owner_screen_name
=owner
,
839 include_entities
=False)
849 owner
, slug
= get_slug()
853 while next_cursor
!= 0:
856 owner_screen_name
=owner
,
858 include_entities
=False)
860 rel
[u
['name']] = '@' + u
['screen_name']
861 next_cursor
= m
['next_cursor']
862 printNicely('All: ' + str(len(rel
)) + ' members.')
864 user
= ' ' + cycle_color(name
)
865 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
869 def list_subscribers(t
):
873 owner
, slug
= get_slug()
877 while next_cursor
!= 0:
878 m
= t
.lists
.subscribers(
880 owner_screen_name
=owner
,
882 include_entities
=False)
884 rel
[u
['name']] = '@' + u
['screen_name']
885 next_cursor
= m
['next_cursor']
886 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
888 user
= ' ' + cycle_color(name
)
889 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
895 Add specific user to a list
897 owner
, slug
= get_slug()
899 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
900 if user_name
.startswith('@'):
901 user_name
= user_name
[1:]
903 t
.lists
.members
.create(
905 owner_screen_name
=owner
,
906 screen_name
=user_name
)
907 printNicely(green('Added.'))
909 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
914 Remove specific user from a list
916 owner
, slug
= get_slug()
918 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
919 if user_name
.startswith('@'):
920 user_name
= user_name
[1:]
922 t
.lists
.members
.destroy(
924 owner_screen_name
=owner
,
925 screen_name
=user_name
)
926 printNicely(green('Gone.'))
928 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
931 def list_subscribe(t
):
935 owner
, slug
= get_slug()
938 t
.lists
.subscribers
.create(
940 owner_screen_name
=owner
)
941 printNicely(green('Done.'))
944 light_magenta('I\'m sorry you can not subscribe to this list.'))
947 def list_unsubscribe(t
):
951 owner
, slug
= get_slug()
954 t
.lists
.subscribers
.destroy(
956 owner_screen_name
=owner
)
957 printNicely(green('Done.'))
960 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
969 while next_cursor
!= 0:
970 res
= t
.lists
.ownerships(
971 screen_name
=g
['original_name'],
974 next_cursor
= res
['next_cursor']
978 printNicely(light_magenta('You own no lists :)'))
985 name
= raw_input(light_magenta('New list\'s name: '))
986 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
987 description
= raw_input(light_magenta('New list\'s description: '))
992 description
=description
)
993 printNicely(green(name
+ ' list is created.'))
995 printNicely(red('Oops something is wrong with Twitter :('))
1002 slug
= raw_input(light_magenta('Your list that you want to update: '))
1003 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1004 mode
= raw_input(light_magenta('Update mode (public/private): '))
1005 description
= raw_input(light_magenta('Update description: '))
1009 slug
='-'.join(slug
.split()),
1010 owner_screen_name
=g
['original_name'],
1013 description
=description
)
1017 owner_screen_name
=g
['original_name'],
1019 description
=description
)
1020 printNicely(green(slug
+ ' list is updated.'))
1022 printNicely(red('Oops something is wrong with Twitter :('))
1029 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1032 slug
='-'.join(slug
.split()),
1033 owner_screen_name
=g
['original_name'])
1034 printNicely(green(slug
+ ' list is deleted.'))
1036 printNicely(red('Oops something is wrong with Twitter :('))
1043 t
= Twitter(auth
=authen())
1044 # List all lists or base on action
1046 g
['list_action'] = g
['stuff'].split()[0]
1053 'all_mem': list_members
,
1054 'all_sub': list_subscribers
,
1057 'sub': list_subscribe
,
1058 'unsub': list_unsubscribe
,
1061 'update': list_update
,
1065 return action_ary
[g
['list_action']](t
)
1067 printNicely(red('Please try again.'))
1075 target
= g
['stuff'].split()[0]
1077 args
= parse_arguments()
1079 if g
['stuff'].split()[-1] == '-f':
1080 guide
= 'To ignore an option, just hit Enter key.'
1081 printNicely(light_magenta(guide
))
1082 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1083 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1084 args
.filter = filter(None, only
.split(','))
1085 args
.ignore
= filter(None, ignore
.split(','))
1086 elif g
['stuff'].split()[-1] == '-d':
1087 args
.filter = c
['ONLY_LIST']
1088 args
.ignore
= c
['IGNORE_LIST']
1090 printNicely(red('Sorry, wrong format.'))
1093 if target
== 'public':
1094 keyword
= g
['stuff'].split()[1]
1095 if keyword
[0] == '#':
1096 keyword
= keyword
[1:]
1098 g
['stream_stop'] = True
1099 args
.track_keywords
= keyword
1101 th
= threading
.Thread(
1109 elif target
== 'mine':
1111 g
['stream_stop'] = True
1113 th
= threading
.Thread(
1118 g
['original_name']))
1123 printNicely(cyan('Only: ' + str(args
.filter)))
1125 printNicely(red('Ignore: ' + str(args
.ignore
)))
1128 printNicely(red('Sorry I can\'t understand.'))
1133 Unix's command `cal`
1136 rel
= os
.popen('cal').read().split('\n')
1139 show_calendar(month
, date
, rel
)
1144 List and change theme
1148 for theme
in g
['themes']:
1149 line
= light_magenta(theme
)
1150 if c
['THEME'] == theme
:
1151 line
= ' ' * 2 + light_yellow('* ') + line
1153 line
= ' ' * 4 + line
1159 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1160 # Redefine decorated_name
1161 g
['decorated_name'] = lambda x
: color_func(
1162 c
['DECORATED_NAME'])(
1164 printNicely(green('Theme changed.'))
1166 printNicely(red('No such theme exists.'))
1171 Browse and change config
1173 all_config
= get_all_config()
1174 g
['stuff'] = g
['stuff'].strip()
1177 for k
in all_config
:
1179 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1181 guide
= 'Detailed explanation can be found at ' + \
1182 color_func(c
['TWEET']['link'])(
1183 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1185 # Print specific config
1186 elif len(g
['stuff'].split()) == 1:
1187 if g
['stuff'] in all_config
:
1190 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1193 printNicely(red('No such config key.'))
1194 # Print specific config's default value
1195 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1196 key
= g
['stuff'].split()[0]
1198 value
= get_default_config(key
)
1199 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1201 except Exception as e
:
1203 # Delete specific config key in config file
1204 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1205 key
= g
['stuff'].split()[0]
1208 printNicely(green('Config key is dropped.'))
1209 except Exception as e
:
1211 # Set specific config
1212 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1213 key
= g
['stuff'].split()[0]
1214 value
= g
['stuff'].split()[-1]
1215 if key
== 'THEME' and not validate_theme(value
):
1216 printNicely(red('Invalid theme\'s value.'))
1219 set_config(key
, value
)
1220 # Apply theme immediately
1222 c
['THEME'] = reload_theme(value
, c
['THEME'])
1223 g
['decorated_name'] = lambda x
: color_func(
1224 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1226 printNicely(green('Updated successfully.'))
1227 except Exception as e
:
1230 printNicely(light_magenta('Sorry I can\'s understand.'))
1233 def help_discover():
1238 # Discover the world
1240 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1241 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1242 'You can try ' + light_green('trend US') + ' or ' + \
1243 light_green('trend JP Tokyo') + '.\n'
1244 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1245 light_green('home 7') + ' will show 7 tweets.\n'
1247 light_green('notification') + ' will show your recent notification.\n'
1248 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1249 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1250 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1251 magenta('@mdo') + '.\n'
1252 usage
+= s
* 2 + light_green('view @mdo') + \
1253 ' will show ' + magenta('@mdo') + '\'s home.\n'
1254 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1255 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1256 'Search can be performed with or without hashtag.\n'
1267 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1268 usage
+= s
* 2 + light_green('t oops ') + \
1269 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1271 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1272 light_yellow('[id=12]') + '.\n'
1274 light_green('quote 12 ') + ' will quote the tweet with ' + \
1275 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1276 'the quote will be canceled.\n'
1278 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1279 light_yellow('[id=12]') + '.\n'
1280 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1281 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1282 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1283 light_yellow('oops') + '" to tweet with ' + \
1284 light_yellow('[id=12]') + '.\n'
1286 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1287 light_yellow('[id=12]') + '.\n'
1289 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1290 light_yellow('[id=12]') + '.\n'
1292 light_green('del 12 ') + ' will delete tweet with ' + \
1293 light_yellow('[id=12]') + '.\n'
1294 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1295 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1296 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1297 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1301 def help_messages():
1308 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1309 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1310 light_green('inbox 7') + ' will show newest 7 messages.\n'
1311 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1312 light_yellow('[thread_id=2]') + '.\n'
1313 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1314 magenta('@dtvd88') + '.\n'
1315 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1316 light_yellow('[message_id=5]') + '.\n'
1320 def help_friends_and_followers():
1322 Friends and Followers
1325 # Follower and following
1327 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1329 light_green('ls fl') + \
1330 ' will list all followers (people who are following you).\n'
1332 light_green('ls fr') + \
1333 ' will list all friends (people who you are following).\n'
1334 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1335 magenta('@dtvd88') + '.\n'
1336 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1337 magenta('@dtvd88') + '.\n'
1338 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1339 magenta('@dtvd88') + '.\n'
1340 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1341 magenta('@dtvd88') + '.\n'
1342 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1343 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1344 magenta('@dtvd88') + '.\n'
1345 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1346 magenta('@dtvd88') + '.\n'
1347 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1348 magenta('@dtvd88') + ' as a spam account.\n'
1359 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1360 usage
+= s
* 2 + light_green('list') + \
1361 ' will show all lists you are belong to.\n'
1362 usage
+= s
* 2 + light_green('list home') + \
1363 ' will show timeline of list. You will be asked for list\'s name.\n'
1364 usage
+= s
* 2 + light_green('list all_mem') + \
1365 ' will show list\'s all members.\n'
1366 usage
+= s
* 2 + light_green('list all_sub') + \
1367 ' will show list\'s all subscribers.\n'
1368 usage
+= s
* 2 + light_green('list add') + \
1369 ' will add specific person to 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 rm') + \
1372 ' will remove specific person from a list owned by you.' + \
1373 ' You will be asked for list\'s name and person\'s name.\n'
1374 usage
+= s
* 2 + light_green('list sub') + \
1375 ' will subscribe you to a specific list.\n'
1376 usage
+= s
* 2 + light_green('list unsub') + \
1377 ' will unsubscribe you from a specific list.\n'
1378 usage
+= s
* 2 + light_green('list own') + \
1379 ' will show all list owned by you.\n'
1380 usage
+= s
* 2 + light_green('list new') + \
1381 ' will create a new list.\n'
1382 usage
+= s
* 2 + light_green('list update') + \
1383 ' will update a list owned by you.\n'
1384 usage
+= s
* 2 + light_green('list del') + \
1385 ' will delete a list owned by you.\n'
1396 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1397 usage
+= s
* 2 + light_green('switch public #AKB') + \
1398 ' will switch to public stream and follow "' + \
1399 light_yellow('AKB') + '" keyword.\n'
1400 usage
+= s
* 2 + light_green('switch mine') + \
1401 ' will switch to your personal stream.\n'
1402 usage
+= s
* 2 + light_green('switch mine -f ') + \
1403 ' will prompt to enter the filter.\n'
1404 usage
+= s
* 3 + light_yellow('Only nicks') + \
1405 ' filter will decide nicks will be INCLUDE ONLY.\n'
1406 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1407 ' filter will decide nicks will be EXCLUDE.\n'
1408 usage
+= s
* 2 + light_green('switch mine -d') + \
1409 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1418 h
, w
= os
.popen('stty size', 'r').read().split()
1421 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1422 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1423 usage
+= s
+ 'You are ' + \
1424 light_yellow('already') + ' on your personal stream.\n'
1425 usage
+= s
+ 'Any update from Twitter will show up ' + \
1426 light_yellow('immediately') + '.\n'
1427 usage
+= s
+ 'In addition, following commands are available right now:\n'
1428 # Twitter help section
1430 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1431 usage
+= s
* 2 + light_green('h discover') + \
1432 ' will show help for discover commands.\n'
1433 usage
+= s
* 2 + light_green('h tweets') + \
1434 ' will show help for tweets commands.\n'
1435 usage
+= s
* 2 + light_green('h messages') + \
1436 ' will show help for messages commands.\n'
1437 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1438 ' will show help for friends and followers commands.\n'
1439 usage
+= s
* 2 + light_green('h list') + \
1440 ' will show help for list commands.\n'
1441 usage
+= s
* 2 + light_green('h stream') + \
1442 ' will show help for stream commands.\n'
1445 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1446 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1447 'will be evaluate by Python interpreter.\n'
1448 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1449 ' for current month.\n'
1452 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1453 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1454 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1455 ' theme immediately.\n'
1456 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1458 light_green('config ASCII_ART') + ' will output current value of ' +\
1459 light_yellow('ASCII_ART') + ' config key.\n'
1461 light_green('config TREND_MAX default') + ' will output default value of ' + \
1462 light_yellow('TREND_MAX') + ' config key.\n'
1464 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1465 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1467 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1468 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1469 light_yellow('True') + '.\n'
1472 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1473 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1474 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1475 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1476 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1477 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1480 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1481 usage
+= s
+ 'Have fun and hang tight! \n'
1484 'discover': help_discover
,
1485 'tweets': help_tweets
,
1486 'messages': help_messages
,
1487 'friends_and_followers': help_friends_and_followers
,
1489 'stream': help_stream
,
1494 lambda: printNicely(red('No such command.'))
1502 Pause stream display
1505 printNicely(green('Stream is paused'))
1513 printNicely(green('Stream is running back now'))
1529 printNicely(green('See you next time :)'))
1537 Reset prefix of line
1540 if c
.get('USER_JSON_ERROR'):
1541 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1542 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1544 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1547 printNicely(str(eval(g
['cmd'])))
1597 # Handle function set
1647 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1652 Listen to user's input
1657 ['public', 'mine'], # switch
1674 ['image'], # show image
1676 ['fl', 'fr'], # list
1678 [i
for i
in g
['message_threads']], # sent
1703 [key
for key
in dict(get_all_config())], # config
1704 g
['themes'], # theme
1709 'friends_and_followers',
1719 init_interactive_shell(d
)
1726 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1729 # Save cmd to compare with readline buffer
1730 g
['cmd'] = line
.strip()
1731 # Get short cmd to pass to handle function
1733 cmd
= line
.split()[0]
1736 # Lock the semaphore
1738 # Save cmd to global variable and call process
1739 g
['stuff'] = ' '.join(line
.split()[1:])
1740 # Process the command
1743 if cmd
in ['switch', 't', 'rt', 'rep']:
1747 # Release the semaphore lock
1752 printNicely(red('OMG something is wrong with Twitter right now.'))
1755 def stream(domain
, args
, name
='Rainbow Stream'):
1761 c
['USER_DOMAIN']: name
,
1762 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1763 c
['SITE_DOMAIN']: name
,
1766 ascii_art(art_dict
[domain
])
1767 # These arguments are optional:
1769 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1771 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1774 if args
.track_keywords
:
1775 query_args
['track'] = args
.track_keywords
1777 stream
= TwitterStream(
1782 if domain
== c
['USER_DOMAIN']:
1783 tweet_iter
= stream
.user(**query_args
)
1784 elif domain
== c
['SITE_DOMAIN']:
1785 tweet_iter
= stream
.site(**query_args
)
1787 if args
.track_keywords
:
1788 tweet_iter
= stream
.statuses
.filter(**query_args
)
1790 tweet_iter
= stream
.statuses
.sample()
1791 # Block new stream until other one exits
1792 StreamLock
.acquire()
1793 g
['stream_stop'] = False
1794 for tweet
in tweet_iter
:
1796 printNicely("-- None --")
1797 elif tweet
is Timeout
:
1798 if(g
['stream_stop']):
1799 StreamLock
.release()
1801 elif tweet
is HeartbeatTimeout
:
1802 printNicely("-- Heartbeat Timeout --")
1803 guide
= light_magenta("You can use ") + \
1804 light_green("switch") + \
1805 light_magenta(" command to return to your stream.\n")
1806 guide
+= light_magenta("Type ") + \
1807 light_green("h stream") + \
1808 light_magenta(" for more details.")
1810 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1812 StreamLock
.release()
1814 elif tweet
is Hangup
:
1815 printNicely("-- Hangup --")
1816 elif tweet
.get('text'):
1817 # Check the semaphore pause and lock (stream process only)
1825 keyword
=args
.track_keywords
,
1830 # Current readline buffer
1831 current_buffer
= readline
.get_line_buffer().strip()
1832 # There is an unexpected behaviour in MacOSX readline + Python 2:
1833 # after completely delete a word after typing it,
1834 # somehow readline buffer still contains
1835 # the 1st character of that word
1836 if current_buffer
and g
['cmd'] != current_buffer
:
1838 g
['decorated_name'](g
['PREFIX']) + str2u(current_buffer
))
1840 elif not c
['HIDE_PROMPT']:
1841 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1843 elif tweet
.get('direct_message'):
1844 # Check the semaphore pause and lock (stream process only)
1849 print_message(tweet
['direct_message'])
1850 elif tweet
.get('event'):
1851 g
['events'].append(tweet
)
1853 except TwitterHTTPError
:
1856 magenta("We have maximum connection problem with twitter'stream API right now :("))
1864 args
= parse_arguments()
1867 except TwitterHTTPError
:
1870 magenta("We have connection problem with twitter'stream API right now :("))
1871 printNicely(magenta("Let's try again later."))
1874 # Spawn stream thread
1875 th
= threading
.Thread(
1880 g
['original_name']))
1883 # Start listen process