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 # Init tweet dict and message dict
142 c
['message_dict'] = []
144 c
['IMAGE_ON_TERM'] = args
.image_on_term
145 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
147 c
['IGNORE_LIST'] += build_mute_dict()
154 t
= Twitter(auth
=authen())
155 # Get country and town
157 country
= g
['stuff'].split()[0]
161 town
= g
['stuff'].split()[1]
164 avail
= t
.trends
.available()
167 trends
= t
.trends
.place(_id
=1)[0]['trends']
170 for location
in avail
:
171 # Search for country and Town
173 if location
['countryCode'] == country \
174 and location
['placeType']['name'] == 'Town' \
175 and location
['name'] == town
:
176 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
178 # Search for country only
180 if location
['countryCode'] == country \
181 and location
['placeType']['name'] == 'Country':
182 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
190 t
= Twitter(auth
=authen())
191 num
= c
['HOME_TWEET_NUM']
192 if g
['stuff'].isdigit():
193 num
= int(g
['stuff'])
194 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
203 t
= Twitter(auth
=authen())
204 num
= c
['HOME_TWEET_NUM']
205 if g
['stuff'].isdigit():
206 num
= int(g
['stuff'])
207 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
214 Show profile of a specific user
216 t
= Twitter(auth
=authen())
217 screen_name
= g
['stuff'].split()[0]
218 if screen_name
.startswith('@'):
221 screen_name
=screen_name
[1:],
222 include_entities
=False)
225 printNicely(red('Omg no user.'))
227 printNicely(red('A name should begin with a \'@\''))
234 t
= Twitter(auth
=authen())
235 user
= g
['stuff'].split()[0]
238 num
= int(g
['stuff'].split()[1])
240 num
= c
['HOME_TWEET_NUM']
241 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
245 printNicely(red('A name should begin with a \'@\''))
252 t
= Twitter(auth
=authen())
254 query
= g
['stuff'].strip()
255 type = c
['SEARCH_TYPE']
256 if type not in ['mixed', 'recent', 'popular']:
258 max_record
= c
['SEARCH_MAX_RECORD']
259 count
= min(max_record
, 100)
261 rel
= t
.search
.tweets(
268 printNicely('Newest tweets:')
269 for i
in reversed(xrange(count
)):
270 draw(t
=rel
[i
], keyword
=query
)
273 printNicely(magenta('I\'m afraid there is no result'))
280 t
= Twitter(auth
=authen())
281 t
.statuses
.update(status
=g
['stuff'])
288 t
= Twitter(auth
=authen())
290 id = int(g
['stuff'].split()[0])
292 printNicely(red('Sorry I can\'t understand.'))
294 tid
= c
['tweet_dict'][id]
295 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
303 t
= Twitter(auth
=authen())
305 id = int(g
['stuff'].split()[0])
307 printNicely(red('Sorry I can\'t understand.'))
309 tid
= c
['tweet_dict'][id]
310 tweet
= t
.statuses
.show(id=tid
)
312 formater
= format_quote(tweet
)
316 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
317 comment
= raw_input(prefix
)
319 quote
= comment
.join(formater
.split('#comment'))
320 t
.statuses
.update(status
=quote
)
322 printNicely(light_magenta('No text added.'))
329 t
= Twitter(auth
=authen())
332 id = int(g
['stuff'].split()[0])
334 printNicely(red('Sorry I can\'t understand.'))
336 tid
= c
['tweet_dict'][id]
337 # Get display num if exist
339 num
= int(g
['stuff'].split()[1])
341 num
= c
['RETWEETS_SHOW_NUM']
342 # Get result and display
343 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
345 printNicely(magenta('This tweet has no retweet.'))
347 for tweet
in reversed(rt_ary
):
356 t
= Twitter(auth
=authen())
358 id = int(g
['stuff'].split()[0])
360 printNicely(red('Sorry I can\'t understand.'))
362 tid
= c
['tweet_dict'][id]
363 tweet
= t
.statuses
.show(id=tid
)
364 limit
= c
['CONVERSATION_MAX']
366 thread_ref
.append(tweet
)
367 prev_tid
= tweet
['in_reply_to_status_id']
368 while prev_tid
and limit
:
370 tweet
= t
.statuses
.show(id=prev_tid
)
371 prev_tid
= tweet
['in_reply_to_status_id']
372 thread_ref
.append(tweet
)
374 for tweet
in reversed(thread_ref
):
383 t
= Twitter(auth
=authen())
385 id = int(g
['stuff'].split()[0])
387 printNicely(red('Sorry I can\'t understand.'))
389 tid
= c
['tweet_dict'][id]
390 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
391 status
= ' '.join(g
['stuff'].split()[1:])
392 status
= '@' + user
+ ' ' + str2u(status
)
393 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
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 t
.favorites
.create(_id
=tid
, include_entities
=False)
408 printNicely(green('Favorited.'))
409 draw(t
.statuses
.show(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
.destroy(_id
=tid
)
425 printNicely(green('Okay it\'s unfavorited.'))
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
.statuses
.destroy(id=tid
)
442 printNicely(green('Okay it\'s gone.'))
449 t
= Twitter(auth
=authen())
451 target
= g
['stuff'].split()[0]
452 if target
!= 'image':
454 id = int(g
['stuff'].split()[1])
455 tid
= c
['tweet_dict'][id]
456 tweet
= t
.statuses
.show(id=tid
)
457 media
= tweet
['entities']['media']
459 res
= requests
.get(m
['media_url'])
460 img
= Image
.open(BytesIO(res
.content
))
463 printNicely(red('Sorry I can\'t show this image.'))
470 t
= Twitter(auth
=authen())
472 if not g
['stuff'].isdigit():
474 tid
= c
['tweet_dict'][int(g
['stuff'])]
475 tweet
= t
.statuses
.show(id=tid
)
476 link_prefix
= ('http://', 'https://')
477 link_ary
= [u
for u
in tweet
['text'].split()
478 if u
.startswith(link_prefix
)]
480 printNicely(light_magenta('No url here @.@!'))
482 for link
in link_ary
:
483 webbrowser
.open(link
)
485 printNicely(red('Sorry I can\'t open url in this tweet.'))
492 t
= Twitter(auth
=authen())
493 num
= c
['MESSAGES_DISPLAY']
494 if g
['stuff'].isdigit():
500 inbox
= inbox
+ t
.direct_messages(
503 include_entities
=False,
508 inbox
= inbox
+ t
.direct_messages(
511 include_entities
=False,
515 num
= c
['MESSAGES_DISPLAY']
516 if g
['stuff'].isdigit():
521 sent
= sent
+ t
.direct_messages
.sent(
524 include_entities
=False,
529 sent
= sent
+ t
.direct_messages
.sent(
532 include_entities
=False,
537 uniq_inbox
= list(set(
538 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
540 uniq_sent
= list(set(
541 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
543 for partner
in uniq_inbox
:
544 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
546 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
547 d
[partner
] = inbox_ary
+ sent_ary
548 for partner
in uniq_sent
:
551 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
552 g
['message_threads'] = print_threads(d
)
557 View a thread of message
560 thread_id
= int(g
['stuff'])
562 g
['message_threads'][thread_id
],
566 printNicely(red('No such thread.'))
571 Send a direct message
573 t
= Twitter(auth
=authen())
575 user
= g
['stuff'].split()[0]
576 if user
[0].startswith('@'):
577 content
= ' '.join(g
['stuff'].split()[1:])
578 t
.direct_messages
.new(
579 screen_name
=user
[1:],
582 printNicely(green('Message sent.'))
584 printNicely(red('A name should begin with a \'@\''))
586 printNicely(red('Sorry I can\'t understand.'))
593 t
= Twitter(auth
=authen())
595 id = int(g
['stuff'].split()[0])
597 printNicely(red('Sorry I can\'t understand.'))
598 mid
= c
['message_dict'][id]
599 t
.direct_messages
.destroy(id=mid
)
600 printNicely(green('Message deleted.'))
605 List friends for followers
607 t
= Twitter(auth
=authen())
610 name
= g
['stuff'].split()[1]
611 if name
.startswith('@'):
614 printNicely(red('A name should begin with a \'@\''))
615 raise Exception('Invalid name')
617 name
= g
['original_name']
618 # Get list followers or friends
620 target
= g
['stuff'].split()[0]
622 printNicely(red('Omg some syntax is wrong.'))
624 d
= {'fl': 'followers', 'fr': 'friends'}
628 while next_cursor
!= 0:
629 list = getattr(t
, d
[target
]).list(
633 include_entities
=False,
635 for u
in list['users']:
636 rel
[u
['name']] = '@' + u
['screen_name']
637 next_cursor
= list['next_cursor']
639 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
641 user
= ' ' + cycle_color(name
)
642 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
650 t
= Twitter(auth
=authen())
651 screen_name
= g
['stuff'].split()[0]
652 if screen_name
.startswith('@'):
653 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
654 printNicely(green('You are following ' + screen_name
+ ' now!'))
656 printNicely(red('A name should begin with a \'@\''))
663 t
= Twitter(auth
=authen())
664 screen_name
= g
['stuff'].split()[0]
665 if screen_name
.startswith('@'):
666 t
.friendships
.destroy(
667 screen_name
=screen_name
[1:],
668 include_entities
=False)
669 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
671 printNicely(red('A name should begin with a \'@\''))
678 t
= Twitter(auth
=authen())
680 screen_name
= g
['stuff'].split()[0]
682 printNicely(red('A name should be specified. '))
684 if screen_name
.startswith('@'):
686 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
687 if isinstance(rel
, dict):
688 printNicely(green(screen_name
+ ' is muted.'))
689 c
['IGNORE_LIST'] += [unc(screen_name
)]
690 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
692 printNicely(red(rel
))
694 printNicely(red('Something is wrong, can not mute now :('))
696 printNicely(red('A name should begin with a \'@\''))
703 t
= Twitter(auth
=authen())
705 screen_name
= g
['stuff'].split()[0]
707 printNicely(red('A name should be specified. '))
709 if screen_name
.startswith('@'):
711 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
712 if isinstance(rel
, dict):
713 printNicely(green(screen_name
+ ' is unmuted.'))
714 c
['IGNORE_LIST'].remove(screen_name
)
716 printNicely(red(rel
))
718 printNicely(red('Maybe you are not muting this person ?'))
720 printNicely(red('A name should begin with a \'@\''))
727 # Get dict of muting users
728 md
= build_mute_dict(dict_data
=True)
729 printNicely('All: ' + str(len(md
)) + ' people.')
731 user
= ' ' + cycle_color(md
[name
])
732 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
734 # Update from Twitter
735 c
['IGNORE_LIST'] = [n
for n
in md
]
742 t
= Twitter(auth
=authen())
743 screen_name
= g
['stuff'].split()[0]
744 if screen_name
.startswith('@'):
746 screen_name
=screen_name
[1:],
747 include_entities
=False,
749 printNicely(green('You blocked ' + screen_name
+ '.'))
751 printNicely(red('A name should begin with a \'@\''))
758 t
= Twitter(auth
=authen())
759 screen_name
= g
['stuff'].split()[0]
760 if screen_name
.startswith('@'):
762 screen_name
=screen_name
[1:],
763 include_entities
=False,
765 printNicely(green('Unblock ' + screen_name
+ ' success!'))
767 printNicely(red('A name should begin with a \'@\''))
772 Report a user as a spam account
774 t
= Twitter(auth
=authen())
775 screen_name
= g
['stuff'].split()[0]
776 if screen_name
.startswith('@'):
778 screen_name
=screen_name
[1:])
779 printNicely(green('You reported ' + screen_name
+ '.'))
781 printNicely(red('Sorry I can\'t understand.'))
789 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
790 # Get list name and owner
792 owner
, slug
= list_name
.split('/')
793 if slug
.startswith('@'):
798 light_magenta('List name should follow "@owner/list_name" format.'))
799 raise Exception('Wrong list name')
806 rel
= t
.lists
.list(screen_name
=g
['original_name'])
810 printNicely(light_magenta('You belong to no lists :)'))
817 owner
, slug
= get_slug()
818 res
= t
.lists
.statuses(
820 owner_screen_name
=owner
,
822 include_entities
=False)
832 owner
, slug
= get_slug()
836 while next_cursor
!= 0:
839 owner_screen_name
=owner
,
841 include_entities
=False)
843 rel
[u
['name']] = '@' + u
['screen_name']
844 next_cursor
= m
['next_cursor']
845 printNicely('All: ' + str(len(rel
)) + ' members.')
847 user
= ' ' + cycle_color(name
)
848 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
852 def list_subscribers(t
):
856 owner
, slug
= get_slug()
860 while next_cursor
!= 0:
861 m
= t
.lists
.subscribers(
863 owner_screen_name
=owner
,
865 include_entities
=False)
867 rel
[u
['name']] = '@' + u
['screen_name']
868 next_cursor
= m
['next_cursor']
869 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
871 user
= ' ' + cycle_color(name
)
872 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
878 Add specific user to a list
880 owner
, slug
= get_slug()
882 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
883 if user_name
.startswith('@'):
884 user_name
= user_name
[1:]
886 t
.lists
.members
.create(
888 owner_screen_name
=owner
,
889 screen_name
=user_name
)
890 printNicely(green('Added.'))
892 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
897 Remove specific user from a list
899 owner
, slug
= get_slug()
901 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
902 if user_name
.startswith('@'):
903 user_name
= user_name
[1:]
905 t
.lists
.members
.destroy(
907 owner_screen_name
=owner
,
908 screen_name
=user_name
)
909 printNicely(green('Gone.'))
911 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
914 def list_subscribe(t
):
918 owner
, slug
= get_slug()
921 t
.lists
.subscribers
.create(
923 owner_screen_name
=owner
)
924 printNicely(green('Done.'))
927 light_magenta('I\'m sorry you can not subscribe to this list.'))
930 def list_unsubscribe(t
):
934 owner
, slug
= get_slug()
937 t
.lists
.subscribers
.destroy(
939 owner_screen_name
=owner
)
940 printNicely(green('Done.'))
943 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
952 while next_cursor
!= 0:
953 res
= t
.lists
.ownerships(
954 screen_name
=g
['original_name'],
957 next_cursor
= res
['next_cursor']
961 printNicely(light_magenta('You own no lists :)'))
968 name
= raw_input(light_magenta('New list\'s name: '))
969 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
970 description
= raw_input(light_magenta('New list\'s description: '))
975 description
=description
)
976 printNicely(green(name
+ ' list is created.'))
978 printNicely(red('Oops something is wrong with Twitter :('))
985 slug
= raw_input(light_magenta('Your list that you want to update: '))
986 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
987 mode
= raw_input(light_magenta('Update mode (public/private): '))
988 description
= raw_input(light_magenta('Update description: '))
992 slug
='-'.join(slug
.split()),
993 owner_screen_name
=g
['original_name'],
996 description
=description
)
1000 owner_screen_name
=g
['original_name'],
1002 description
=description
)
1003 printNicely(green(slug
+ ' list is updated.'))
1005 printNicely(red('Oops something is wrong with Twitter :('))
1012 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1015 slug
='-'.join(slug
.split()),
1016 owner_screen_name
=g
['original_name'])
1017 printNicely(green(slug
+ ' list is deleted.'))
1019 printNicely(red('Oops something is wrong with Twitter :('))
1026 t
= Twitter(auth
=authen())
1027 # List all lists or base on action
1029 g
['list_action'] = g
['stuff'].split()[0]
1036 'all_mem': list_members
,
1037 'all_sub': list_subscribers
,
1040 'sub': list_subscribe
,
1041 'unsub': list_unsubscribe
,
1044 'update': list_update
,
1048 return action_ary
[g
['list_action']](t
)
1050 printNicely(red('Please try again.'))
1058 target
= g
['stuff'].split()[0]
1060 args
= parse_arguments()
1062 if g
['stuff'].split()[-1] == '-f':
1063 guide
= 'To ignore an option, just hit Enter key.'
1064 printNicely(light_magenta(guide
))
1065 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1066 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1067 args
.filter = filter(None, only
.split(','))
1068 args
.ignore
= filter(None, ignore
.split(','))
1069 elif g
['stuff'].split()[-1] == '-d':
1070 args
.filter = c
['ONLY_LIST']
1071 args
.ignore
= c
['IGNORE_LIST']
1073 printNicely(red('Sorry, wrong format.'))
1076 if target
== 'public':
1077 keyword
= g
['stuff'].split()[1]
1078 if keyword
[0] == '#':
1079 keyword
= keyword
[1:]
1081 g
['stream_stop'] = True
1082 args
.track_keywords
= keyword
1084 th
= threading
.Thread(
1092 elif target
== 'mine':
1094 g
['stream_stop'] = True
1096 th
= threading
.Thread(
1101 g
['original_name']))
1106 printNicely(cyan('Only: ' + str(args
.filter)))
1108 printNicely(red('Ignore: ' + str(args
.ignore
)))
1111 printNicely(red('Sorry I can\'t understand.'))
1116 Unix's command `cal`
1119 rel
= os
.popen('cal').read().split('\n')
1122 show_calendar(month
, date
, rel
)
1127 List and change theme
1131 for theme
in g
['themes']:
1132 line
= light_magenta(theme
)
1133 if c
['THEME'] == theme
:
1134 line
= ' ' * 2 + light_yellow('* ') + line
1136 line
= ' ' * 4 + line
1142 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1143 # Redefine decorated_name
1144 g
['decorated_name'] = lambda x
: color_func(
1145 c
['DECORATED_NAME'])(
1147 printNicely(green('Theme changed.'))
1149 printNicely(red('No such theme exists.'))
1154 Browse and change config
1156 all_config
= get_all_config()
1157 g
['stuff'] = g
['stuff'].strip()
1160 for k
in all_config
:
1162 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1164 guide
= 'Detailed explanation can be found at ' + \
1165 color_func(c
['TWEET']['link'])(
1166 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1168 # Print specific config
1169 elif len(g
['stuff'].split()) == 1:
1170 if g
['stuff'] in all_config
:
1173 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1176 printNicely(red('No such config key.'))
1177 # Print specific config's default value
1178 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1179 key
= g
['stuff'].split()[0]
1181 value
= get_default_config(key
)
1182 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1184 except Exception as e
:
1186 # Delete specific config key in config file
1187 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1188 key
= g
['stuff'].split()[0]
1191 printNicely(green('Config key is dropped.'))
1192 except Exception as e
:
1194 # Set specific config
1195 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1196 key
= g
['stuff'].split()[0]
1197 value
= g
['stuff'].split()[-1]
1198 if key
== 'THEME' and not validate_theme(value
):
1199 printNicely(red('Invalid theme\'s value.'))
1202 set_config(key
, value
)
1203 # Apply theme immediately
1205 c
['THEME'] = reload_theme(value
, c
['THEME'])
1206 g
['decorated_name'] = lambda x
: color_func(
1207 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1209 printNicely(green('Updated successfully.'))
1210 except Exception as e
:
1213 printNicely(light_magenta('Sorry I can\'s understand.'))
1216 def help_discover():
1221 # Discover the world
1223 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1224 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1225 'You can try ' + light_green('trend US') + ' or ' + \
1226 light_green('trend JP Tokyo') + '.\n'
1227 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1228 light_green('home 7') + ' will show 7 tweets.\n'
1229 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1230 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1231 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1232 magenta('@mdo') + '.\n'
1233 usage
+= s
* 2 + light_green('view @mdo') + \
1234 ' will show ' + magenta('@mdo') + '\'s home.\n'
1235 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1236 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1237 'Search can be performed with or without hashtag.\n'
1248 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1249 usage
+= s
* 2 + light_green('t oops ') + \
1250 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1252 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1253 light_yellow('[id=12]') + '.\n'
1255 light_green('quote 12 ') + ' will quote the tweet with ' + \
1256 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1257 'the quote will be canceled.\n'
1259 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1260 light_yellow('[id=12]') + '.\n'
1261 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1262 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1263 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1264 light_yellow('oops') + '" to tweet with ' + \
1265 light_yellow('[id=12]') + '.\n'
1267 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1268 light_yellow('[id=12]') + '.\n'
1270 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1271 light_yellow('[id=12]') + '.\n'
1273 light_green('del 12 ') + ' will delete tweet with ' + \
1274 light_yellow('[id=12]') + '.\n'
1275 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1276 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1277 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1278 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1282 def help_messages():
1289 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1290 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1291 light_green('inbox 7') + ' will show newest 7 messages.\n'
1292 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1293 light_yellow('[thread_id=2]') + '.\n'
1294 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1295 magenta('@dtvd88') + '.\n'
1296 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1297 light_yellow('[message_id=5]') + '.\n'
1301 def help_friends_and_followers():
1303 Friends and Followers
1306 # Follower and following
1308 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1310 light_green('ls fl') + \
1311 ' will list all followers (people who are following you).\n'
1313 light_green('ls fr') + \
1314 ' will list all friends (people who you are following).\n'
1315 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1316 magenta('@dtvd88') + '.\n'
1317 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1318 magenta('@dtvd88') + '.\n'
1319 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1320 magenta('@dtvd88') + '.\n'
1321 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1322 magenta('@dtvd88') + '.\n'
1323 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1324 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1325 magenta('@dtvd88') + '.\n'
1326 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1327 magenta('@dtvd88') + '.\n'
1328 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1329 magenta('@dtvd88') + ' as a spam account.\n'
1340 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1341 usage
+= s
* 2 + light_green('list') + \
1342 ' will show all lists you are belong to.\n'
1343 usage
+= s
* 2 + light_green('list home') + \
1344 ' will show timeline of list. You will be asked for list\'s name.\n'
1345 usage
+= s
* 2 + light_green('list all_mem') + \
1346 ' will show list\'s all members.\n'
1347 usage
+= s
* 2 + light_green('list all_sub') + \
1348 ' will show list\'s all subscribers.\n'
1349 usage
+= s
* 2 + light_green('list add') + \
1350 ' will add specific person to a list owned by you.' + \
1351 ' You will be asked for list\'s name and person\'s name.\n'
1352 usage
+= s
* 2 + light_green('list rm') + \
1353 ' will remove specific person from a list owned by you.' + \
1354 ' You will be asked for list\'s name and person\'s name.\n'
1355 usage
+= s
* 2 + light_green('list sub') + \
1356 ' will subscribe you to a specific list.\n'
1357 usage
+= s
* 2 + light_green('list unsub') + \
1358 ' will unsubscribe you from a specific list.\n'
1359 usage
+= s
* 2 + light_green('list own') + \
1360 ' will show all list owned by you.\n'
1361 usage
+= s
* 2 + light_green('list new') + \
1362 ' will create a new list.\n'
1363 usage
+= s
* 2 + light_green('list update') + \
1364 ' will update a list owned by you.\n'
1365 usage
+= s
* 2 + light_green('list del') + \
1366 ' will delete a list owned by you.\n'
1377 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1378 usage
+= s
* 2 + light_green('switch public #AKB') + \
1379 ' will switch to public stream and follow "' + \
1380 light_yellow('AKB') + '" keyword.\n'
1381 usage
+= s
* 2 + light_green('switch mine') + \
1382 ' will switch to your personal stream.\n'
1383 usage
+= s
* 2 + light_green('switch mine -f ') + \
1384 ' will prompt to enter the filter.\n'
1385 usage
+= s
* 3 + light_yellow('Only nicks') + \
1386 ' filter will decide nicks will be INCLUDE ONLY.\n'
1387 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1388 ' filter will decide nicks will be EXCLUDE.\n'
1389 usage
+= s
* 2 + light_green('switch mine -d') + \
1390 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1399 h
, w
= os
.popen('stty size', 'r').read().split()
1402 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1403 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1404 usage
+= s
+ 'You are ' + \
1405 light_yellow('already') + ' on your personal stream.\n'
1406 usage
+= s
+ 'Any update from Twitter will show up ' + \
1407 light_yellow('immediately') + '.\n'
1408 usage
+= s
+ 'In addition, following commands are available right now:\n'
1409 # Twitter help section
1411 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1412 usage
+= s
* 2 + light_green('h discover') + \
1413 ' will show help for discover commands.\n'
1414 usage
+= s
* 2 + light_green('h tweets') + \
1415 ' will show help for tweets commands.\n'
1416 usage
+= s
* 2 + light_green('h messages') + \
1417 ' will show help for messages commands.\n'
1418 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1419 ' will show help for friends and followers commands.\n'
1420 usage
+= s
* 2 + light_green('h list') + \
1421 ' will show help for list commands.\n'
1422 usage
+= s
* 2 + light_green('h stream') + \
1423 ' will show help for stream commands.\n'
1426 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1427 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1428 'will be evaluate by Python interpreter.\n'
1429 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1430 ' for current month.\n'
1433 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1434 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1435 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1436 ' theme immediately.\n'
1437 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1439 light_green('config ASCII_ART') + ' will output current value of ' +\
1440 light_yellow('ASCII_ART') + ' config key.\n'
1442 light_green('config TREND_MAX default') + ' will output default value of ' + \
1443 light_yellow('TREND_MAX') + ' config key.\n'
1445 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1446 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1448 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1449 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1450 light_yellow('True') + '.\n'
1453 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1454 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1455 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1456 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1457 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1458 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1461 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1462 usage
+= s
+ 'Have fun and hang tight! \n'
1465 'discover': help_discover
,
1466 'tweets': help_tweets
,
1467 'messages': help_messages
,
1468 'friends_and_followers': help_friends_and_followers
,
1470 'stream': help_stream
,
1475 lambda: printNicely(red('No such command.'))
1483 Pause stream display
1486 printNicely(green('Stream is paused'))
1494 printNicely(green('Stream is running back now'))
1510 printNicely(green('See you next time :)'))
1518 Reset prefix of line
1521 if c
.get('USER_JSON_ERROR'):
1522 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1523 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1525 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1528 printNicely(str(eval(g
['cmd'])))
1577 # Handle function set
1626 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1631 Listen to user's input
1636 ['public', 'mine'], # switch
1652 ['image'], # show image
1654 ['fl', 'fr'], # list
1656 [i
for i
in g
['message_threads']], # sent
1681 [key
for key
in dict(get_all_config())], # config
1682 g
['themes'], # theme
1687 'friends_and_followers',
1697 init_interactive_shell(d
)
1704 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1707 # Save cmd to compare with readline buffer
1708 g
['cmd'] = line
.strip()
1709 # Get short cmd to pass to handle function
1711 cmd
= line
.split()[0]
1714 # Lock the semaphore
1716 # Save cmd to global variable and call process
1717 g
['stuff'] = ' '.join(line
.split()[1:])
1718 # Process the command
1721 if cmd
in ['switch', 't', 'rt', 'rep']:
1725 # Release the semaphore lock
1730 printNicely(red('OMG something is wrong with Twitter right now.'))
1733 def stream(domain
, args
, name
='Rainbow Stream'):
1739 c
['USER_DOMAIN']: name
,
1740 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1741 c
['SITE_DOMAIN']: name
,
1744 ascii_art(art_dict
[domain
])
1745 # These arguments are optional:
1747 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1749 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1752 if args
.track_keywords
:
1753 query_args
['track'] = args
.track_keywords
1755 stream
= TwitterStream(
1760 if domain
== c
['USER_DOMAIN']:
1761 tweet_iter
= stream
.user(**query_args
)
1762 elif domain
== c
['SITE_DOMAIN']:
1763 tweet_iter
= stream
.site(**query_args
)
1765 if args
.track_keywords
:
1766 tweet_iter
= stream
.statuses
.filter(**query_args
)
1768 tweet_iter
= stream
.statuses
.sample()
1769 # Block new stream until other one exits
1770 StreamLock
.acquire()
1771 g
['stream_stop'] = False
1772 for tweet
in tweet_iter
:
1774 printNicely("-- None --")
1775 elif tweet
is Timeout
:
1776 if(g
['stream_stop']):
1777 StreamLock
.release()
1779 elif tweet
is HeartbeatTimeout
:
1780 printNicely("-- Heartbeat Timeout --")
1781 guide
= light_magenta("You can use ") + \
1782 light_green("switch") + \
1783 light_magenta(" command to return to your stream.\n")
1784 guide
+= light_magenta("Type ") + \
1785 light_green("h stream") + \
1786 light_magenta(" for more details.")
1788 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1790 StreamLock
.release()
1792 elif tweet
is Hangup
:
1793 printNicely("-- Hangup --")
1794 elif tweet
.get('text'):
1795 # Check the semaphore pause and lock (stream process only)
1803 keyword
=args
.track_keywords
,
1808 # Current readline buffer
1809 current_buffer
= readline
.get_line_buffer().strip()
1810 # There is an unexpected behaviour in MacOSX readline + Python 2:
1811 # after completely delete a word after typing it,
1812 # somehow readline buffer still contains
1813 # the 1st character of that word
1814 if current_buffer
and g
['cmd'] != current_buffer
:
1816 g
['decorated_name'](g
['PREFIX']) + str2u(current_buffer
))
1818 elif not c
['HIDE_PROMPT']:
1819 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1821 elif tweet
.get('direct_message'):
1822 # Check the semaphore pause and lock (stream process only)
1827 print_message(tweet
['direct_message'])
1828 except TwitterHTTPError
:
1831 magenta("We have maximum connection problem with twitter'stream API right now :("))
1839 args
= parse_arguments()
1842 except TwitterHTTPError
:
1845 magenta("We have connection problem with twitter'stream API right now :("))
1846 printNicely(magenta("Let's try again later."))
1849 # Spawn stream thread
1850 th
= threading
.Thread(
1855 g
['original_name']))
1858 # Start listen process