12 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
13 from twitter
.api
import *
14 from twitter
.oauth
import OAuth
, read_token_file
15 from twitter
.oauth_dance
import oauth_dance
16 from twitter
.util
import printNicely
21 from .consumer
import *
22 from .interactive
import *
23 from .c_image
import *
24 from .py3patch
import *
31 StreamLock
= threading
.Lock()
34 def parse_arguments():
38 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
42 help='Timeout for the stream (seconds).')
46 help='Search the stream for specific text.')
50 help='Filter specific screen_name.')
54 help='Ignore specific screen_name.')
59 help='Run in debug mode.')
64 help='Display all image on terminal.')
65 return parser
.parse_args()
70 Authenticate with Twitter OAuth
72 # When using rainbow stream you must authorize.
73 twitter_credential
= os
.environ
.get(
77 '')) + os
.sep
+ '.rainbow_oauth'
78 if not os
.path
.exists(twitter_credential
):
79 oauth_dance("Rainbow Stream",
83 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
91 def build_mute_dict(dict_data
=False):
95 t
= Twitter(auth
=authen())
101 while next_cursor
!= 0:
102 list = t
.mutes
.users
.list(
103 screen_name
=g
['original_name'],
106 include_entities
=False,
108 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
109 name_list
+= [u
['name'] for u
in list['users']]
110 next_cursor
= list['next_cursor']
111 # Return dict or list
113 return dict(zip(screen_name_list
, name_list
))
115 return screen_name_list
120 Save traceback when run in debug mode
123 g
['traceback'].append(traceback
.format_exc())
131 ctrl_c_handler
= lambda signum
, frame
: quit()
132 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
134 t
= Twitter(auth
=authen())
135 credential
= t
.account
.verify_credentials()
136 screen_name
= '@' + credential
['screen_name']
137 name
= credential
['name']
138 if not get_config('PREFIX'):
139 set_config('PREFIX', screen_name
)
140 c
['PREFIX'] = emojize(c
['PREFIX'])
141 g
['PREFIX'] = u2str(c
['PREFIX'])
142 c
['original_name'] = g
['original_name'] = screen_name
[1:]
143 g
['full_name'] = name
144 g
['decorated_name'] = lambda x
: color_func(
145 c
['DECORATED_NAME'])('[' + x
+ ']: ')
147 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
148 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
151 g
['message_threads'] = {}
157 g
['debug'] = args
.debug
159 # Retweet of mine events
163 # Init tweet dict and message dict
165 c
['message_dict'] = []
167 c
['IMAGE_ON_TERM'] = args
.image_on_term
168 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
170 c
['IGNORE_LIST'] += build_mute_dict()
177 t
= Twitter(auth
=authen())
178 # Get country and town
180 country
= g
['stuff'].split()[0]
184 town
= g
['stuff'].split()[1]
187 avail
= t
.trends
.available()
190 trends
= t
.trends
.place(_id
=1)[0]['trends']
193 for location
in avail
:
194 # Search for country and Town
196 if location
['countryCode'] == country \
197 and location
['placeType']['name'] == 'Town' \
198 and location
['name'] == town
:
199 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
201 # Search for country only
203 if location
['countryCode'] == country \
204 and location
['placeType']['name'] == 'Country':
205 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
213 t
= Twitter(auth
=authen())
214 num
= c
['HOME_TWEET_NUM']
215 if g
['stuff'].isdigit():
216 num
= int(g
['stuff'])
217 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
226 g
['events'] = g
['events'] + c
['events']
228 for e
in g
['events']:
232 printNicely(magenta('Nothing at this time.'))
239 t
= Twitter(auth
=authen())
240 num
= c
['HOME_TWEET_NUM']
241 if g
['stuff'].isdigit():
242 num
= int(g
['stuff'])
243 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
250 Show profile of a specific user
252 t
= Twitter(auth
=authen())
253 screen_name
= g
['stuff'].split()[0]
254 if screen_name
.startswith('@'):
257 screen_name
=screen_name
[1:],
258 include_entities
=False)
262 printNicely(red('No user.'))
264 printNicely(red('A name should begin with a \'@\''))
271 t
= Twitter(auth
=authen())
272 user
= g
['stuff'].split()[0]
275 num
= int(g
['stuff'].split()[1])
277 num
= c
['HOME_TWEET_NUM']
278 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
282 printNicely(red('A name should begin with a \'@\''))
289 t
= Twitter(auth
=authen())
291 query
= g
['stuff'].strip()
292 type = c
['SEARCH_TYPE']
293 if type not in ['mixed', 'recent', 'popular']:
295 max_record
= c
['SEARCH_MAX_RECORD']
296 count
= min(max_record
, 100)
298 rel
= t
.search
.tweets(
305 printNicely('Newest tweets:')
306 for i
in reversed(xrange(count
)):
307 draw(t
=rel
[i
], keyword
=query
)
310 printNicely(magenta('I\'m afraid there is no result'))
317 t
= Twitter(auth
=authen())
318 t
.statuses
.update(status
=g
['stuff'])
325 t
= Twitter(auth
=authen())
327 id = int(g
['stuff'].split()[0])
329 printNicely(red('Sorry I can\'t understand.'))
331 tid
= c
['tweet_dict'][id]
332 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
340 t
= Twitter(auth
=authen())
342 id = int(g
['stuff'].split()[0])
344 printNicely(red('Sorry I can\'t understand.'))
346 tid
= c
['tweet_dict'][id]
347 tweet
= t
.statuses
.show(id=tid
)
349 formater
= format_quote(tweet
)
353 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
354 comment
= raw_input(prefix
)
356 quote
= comment
.join(formater
.split('#comment'))
357 t
.statuses
.update(status
=quote
)
359 printNicely(light_magenta('No text added.'))
366 t
= Twitter(auth
=authen())
369 id = int(g
['stuff'].split()[0])
371 printNicely(red('Sorry I can\'t understand.'))
373 tid
= c
['tweet_dict'][id]
374 # Get display num if exist
376 num
= int(g
['stuff'].split()[1])
378 num
= c
['RETWEETS_SHOW_NUM']
379 # Get result and display
380 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
382 printNicely(magenta('This tweet has no retweet.'))
384 for tweet
in reversed(rt_ary
):
393 t
= Twitter(auth
=authen())
395 id = int(g
['stuff'].split()[0])
397 printNicely(red('Sorry I can\'t understand.'))
399 tid
= c
['tweet_dict'][id]
400 tweet
= t
.statuses
.show(id=tid
)
401 limit
= c
['CONVERSATION_MAX']
403 thread_ref
.append(tweet
)
404 prev_tid
= tweet
['in_reply_to_status_id']
405 while prev_tid
and limit
:
407 tweet
= t
.statuses
.show(id=prev_tid
)
408 prev_tid
= tweet
['in_reply_to_status_id']
409 thread_ref
.append(tweet
)
411 for tweet
in reversed(thread_ref
):
420 t
= Twitter(auth
=authen())
422 id = int(g
['stuff'].split()[0])
424 printNicely(red('Sorry I can\'t understand.'))
426 tid
= c
['tweet_dict'][id]
427 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
428 status
= ' '.join(g
['stuff'].split()[1:])
429 status
= '@' + user
+ ' ' + str2u(status
)
430 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
437 t
= Twitter(auth
=authen())
439 id = int(g
['stuff'].split()[0])
441 printNicely(red('Sorry I can\'t understand.'))
443 tid
= c
['tweet_dict'][id]
444 t
.favorites
.create(_id
=tid
, include_entities
=False)
445 printNicely(green('Favorited.'))
446 draw(t
.statuses
.show(id=tid
))
454 t
= Twitter(auth
=authen())
456 id = int(g
['stuff'].split()[0])
458 printNicely(red('Sorry I can\'t understand.'))
460 tid
= c
['tweet_dict'][id]
461 t
.favorites
.destroy(_id
=tid
)
462 printNicely(green('Okay it\'s unfavorited.'))
463 draw(t
.statuses
.show(id=tid
))
471 t
= Twitter(auth
=authen())
473 id = int(g
['stuff'].split()[0])
475 printNicely(red('Sorry I can\'t understand.'))
477 tid
= c
['tweet_dict'][id]
478 t
.statuses
.destroy(id=tid
)
479 printNicely(green('Okay it\'s gone.'))
486 t
= Twitter(auth
=authen())
488 target
= g
['stuff'].split()[0]
489 if target
!= 'image':
491 id = int(g
['stuff'].split()[1])
492 tid
= c
['tweet_dict'][id]
493 tweet
= t
.statuses
.show(id=tid
)
494 media
= tweet
['entities']['media']
496 res
= requests
.get(m
['media_url'])
497 img
= Image
.open(BytesIO(res
.content
))
501 printNicely(red('Sorry I can\'t show this image.'))
508 t
= Twitter(auth
=authen())
510 if not g
['stuff'].isdigit():
512 tid
= c
['tweet_dict'][int(g
['stuff'])]
513 tweet
= t
.statuses
.show(id=tid
)
514 link_prefix
= ('http://', 'https://')
515 link_ary
= [u
for u
in tweet
['text'].split()
516 if u
.startswith(link_prefix
)]
518 printNicely(light_magenta('No url here @.@!'))
520 for link
in link_ary
:
521 webbrowser
.open(link
)
524 printNicely(red('Sorry I can\'t open url in this tweet.'))
531 t
= Twitter(auth
=authen())
532 num
= c
['MESSAGES_DISPLAY']
533 if g
['stuff'].isdigit():
539 inbox
= inbox
+ t
.direct_messages(
542 include_entities
=False,
547 inbox
= inbox
+ t
.direct_messages(
550 include_entities
=False,
554 num
= c
['MESSAGES_DISPLAY']
555 if g
['stuff'].isdigit():
560 sent
= sent
+ t
.direct_messages
.sent(
563 include_entities
=False,
568 sent
= sent
+ t
.direct_messages
.sent(
571 include_entities
=False,
576 uniq_inbox
= list(set(
577 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
579 uniq_sent
= list(set(
580 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
582 for partner
in uniq_inbox
:
583 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
585 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
586 d
[partner
] = inbox_ary
+ sent_ary
587 for partner
in uniq_sent
:
590 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
591 g
['message_threads'] = print_threads(d
)
596 View a thread of message
599 thread_id
= int(g
['stuff'])
601 g
['message_threads'][thread_id
],
606 printNicely(red('No such thread.'))
611 Send a direct message
613 t
= Twitter(auth
=authen())
615 user
= g
['stuff'].split()[0]
616 if user
[0].startswith('@'):
617 content
= ' '.join(g
['stuff'].split()[1:])
618 t
.direct_messages
.new(
619 screen_name
=user
[1:],
622 printNicely(green('Message sent.'))
624 printNicely(red('A name should begin with a \'@\''))
627 printNicely(red('Sorry I can\'t understand.'))
634 t
= Twitter(auth
=authen())
636 id = int(g
['stuff'].split()[0])
638 printNicely(red('Sorry I can\'t understand.'))
639 mid
= c
['message_dict'][id]
640 t
.direct_messages
.destroy(id=mid
)
641 printNicely(green('Message deleted.'))
646 List friends for followers
648 t
= Twitter(auth
=authen())
651 name
= g
['stuff'].split()[1]
652 if name
.startswith('@'):
655 printNicely(red('A name should begin with a \'@\''))
656 raise Exception('Invalid name')
658 name
= g
['original_name']
659 # Get list followers or friends
661 target
= g
['stuff'].split()[0]
663 printNicely(red('Omg some syntax is wrong.'))
665 d
= {'fl': 'followers', 'fr': 'friends'}
669 while next_cursor
!= 0:
670 list = getattr(t
, d
[target
]).list(
674 include_entities
=False,
676 for u
in list['users']:
677 rel
[u
['name']] = '@' + u
['screen_name']
678 next_cursor
= list['next_cursor']
680 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
682 user
= ' ' + cycle_color(name
)
683 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
691 t
= Twitter(auth
=authen())
692 screen_name
= g
['stuff'].split()[0]
693 if screen_name
.startswith('@'):
694 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
695 printNicely(green('You are following ' + screen_name
+ ' now!'))
697 printNicely(red('A name should begin with a \'@\''))
704 t
= Twitter(auth
=authen())
705 screen_name
= g
['stuff'].split()[0]
706 if screen_name
.startswith('@'):
707 t
.friendships
.destroy(
708 screen_name
=screen_name
[1:],
709 include_entities
=False)
710 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
712 printNicely(red('A name should begin with a \'@\''))
719 t
= Twitter(auth
=authen())
721 screen_name
= g
['stuff'].split()[0]
723 printNicely(red('A name should be specified. '))
725 if screen_name
.startswith('@'):
727 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
728 if isinstance(rel
, dict):
729 printNicely(green(screen_name
+ ' is muted.'))
730 c
['IGNORE_LIST'] += [unc(screen_name
)]
731 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
733 printNicely(red(rel
))
736 printNicely(red('Something is wrong, can not mute now :('))
738 printNicely(red('A name should begin with a \'@\''))
745 t
= Twitter(auth
=authen())
747 screen_name
= g
['stuff'].split()[0]
749 printNicely(red('A name should be specified. '))
751 if screen_name
.startswith('@'):
753 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
754 if isinstance(rel
, dict):
755 printNicely(green(screen_name
+ ' is unmuted.'))
756 c
['IGNORE_LIST'].remove(screen_name
)
758 printNicely(red(rel
))
760 printNicely(red('Maybe you are not muting this person ?'))
762 printNicely(red('A name should begin with a \'@\''))
769 # Get dict of muting users
770 md
= build_mute_dict(dict_data
=True)
771 printNicely('All: ' + str(len(md
)) + ' people.')
773 user
= ' ' + cycle_color(md
[name
])
774 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
776 # Update from Twitter
777 c
['IGNORE_LIST'] = [n
for n
in md
]
784 t
= Twitter(auth
=authen())
785 screen_name
= g
['stuff'].split()[0]
786 if screen_name
.startswith('@'):
788 screen_name
=screen_name
[1:],
789 include_entities
=False,
791 printNicely(green('You blocked ' + screen_name
+ '.'))
793 printNicely(red('A name should begin with a \'@\''))
800 t
= Twitter(auth
=authen())
801 screen_name
= g
['stuff'].split()[0]
802 if screen_name
.startswith('@'):
804 screen_name
=screen_name
[1:],
805 include_entities
=False,
807 printNicely(green('Unblock ' + screen_name
+ ' success!'))
809 printNicely(red('A name should begin with a \'@\''))
814 Report a user as a spam account
816 t
= Twitter(auth
=authen())
817 screen_name
= g
['stuff'].split()[0]
818 if screen_name
.startswith('@'):
820 screen_name
=screen_name
[1:])
821 printNicely(green('You reported ' + screen_name
+ '.'))
823 printNicely(red('Sorry I can\'t understand.'))
831 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
832 # Get list name and owner
834 owner
, slug
= list_name
.split('/')
835 if slug
.startswith('@'):
840 light_magenta('List name should follow "@owner/list_name" format.'))
841 raise Exception('Wrong list name')
848 rel
= t
.lists
.list(screen_name
=g
['original_name'])
852 printNicely(light_magenta('You belong to no lists :)'))
859 owner
, slug
= get_slug()
860 res
= t
.lists
.statuses(
862 owner_screen_name
=owner
,
864 include_entities
=False)
874 owner
, slug
= get_slug()
878 while next_cursor
!= 0:
881 owner_screen_name
=owner
,
883 include_entities
=False)
885 rel
[u
['name']] = '@' + u
['screen_name']
886 next_cursor
= m
['next_cursor']
887 printNicely('All: ' + str(len(rel
)) + ' members.')
889 user
= ' ' + cycle_color(name
)
890 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
894 def list_subscribers(t
):
898 owner
, slug
= get_slug()
902 while next_cursor
!= 0:
903 m
= t
.lists
.subscribers(
905 owner_screen_name
=owner
,
907 include_entities
=False)
909 rel
[u
['name']] = '@' + u
['screen_name']
910 next_cursor
= m
['next_cursor']
911 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
913 user
= ' ' + cycle_color(name
)
914 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
920 Add specific user to a list
922 owner
, slug
= get_slug()
924 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
925 if user_name
.startswith('@'):
926 user_name
= user_name
[1:]
928 t
.lists
.members
.create(
930 owner_screen_name
=owner
,
931 screen_name
=user_name
)
932 printNicely(green('Added.'))
935 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
940 Remove specific user from a list
942 owner
, slug
= get_slug()
944 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
945 if user_name
.startswith('@'):
946 user_name
= user_name
[1:]
948 t
.lists
.members
.destroy(
950 owner_screen_name
=owner
,
951 screen_name
=user_name
)
952 printNicely(green('Gone.'))
955 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
958 def list_subscribe(t
):
962 owner
, slug
= get_slug()
965 t
.lists
.subscribers
.create(
967 owner_screen_name
=owner
)
968 printNicely(green('Done.'))
972 light_magenta('I\'m sorry you can not subscribe to this list.'))
975 def list_unsubscribe(t
):
979 owner
, slug
= get_slug()
982 t
.lists
.subscribers
.destroy(
984 owner_screen_name
=owner
)
985 printNicely(green('Done.'))
989 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
998 while next_cursor
!= 0:
999 res
= t
.lists
.ownerships(
1000 screen_name
=g
['original_name'],
1003 next_cursor
= res
['next_cursor']
1007 printNicely(light_magenta('You own no lists :)'))
1014 name
= raw_input(light_magenta('New list\'s name: '))
1015 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1016 description
= raw_input(light_magenta('New list\'s description: '))
1021 description
=description
)
1022 printNicely(green(name
+ ' list is created.'))
1025 printNicely(red('Oops something is wrong with Twitter :('))
1032 slug
= raw_input(light_magenta('Your list that you want to update: '))
1033 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1034 mode
= raw_input(light_magenta('Update mode (public/private): '))
1035 description
= raw_input(light_magenta('Update description: '))
1039 slug
='-'.join(slug
.split()),
1040 owner_screen_name
=g
['original_name'],
1043 description
=description
)
1047 owner_screen_name
=g
['original_name'],
1049 description
=description
)
1050 printNicely(green(slug
+ ' list is updated.'))
1053 printNicely(red('Oops something is wrong with Twitter :('))
1060 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1063 slug
='-'.join(slug
.split()),
1064 owner_screen_name
=g
['original_name'])
1065 printNicely(green(slug
+ ' list is deleted.'))
1068 printNicely(red('Oops something is wrong with Twitter :('))
1075 t
= Twitter(auth
=authen())
1076 # List all lists or base on action
1078 g
['list_action'] = g
['stuff'].split()[0]
1085 'all_mem': list_members
,
1086 'all_sub': list_subscribers
,
1089 'sub': list_subscribe
,
1090 'unsub': list_unsubscribe
,
1093 'update': list_update
,
1097 return action_ary
[g
['list_action']](t
)
1099 printNicely(red('Please try again.'))
1107 target
= g
['stuff'].split()[0]
1109 args
= parse_arguments()
1111 if g
['stuff'].split()[-1] == '-f':
1112 guide
= 'To ignore an option, just hit Enter key.'
1113 printNicely(light_magenta(guide
))
1114 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1115 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1116 args
.filter = filter(None, only
.split(','))
1117 args
.ignore
= filter(None, ignore
.split(','))
1118 elif g
['stuff'].split()[-1] == '-d':
1119 args
.filter = c
['ONLY_LIST']
1120 args
.ignore
= c
['IGNORE_LIST']
1122 printNicely(red('Sorry, wrong format.'))
1125 if target
== 'public':
1126 keyword
= g
['stuff'].split()[1]
1127 if keyword
[0] == '#':
1128 keyword
= keyword
[1:]
1130 g
['stream_stop'] = True
1131 args
.track_keywords
= keyword
1133 th
= threading
.Thread(
1141 elif target
== 'mine':
1143 g
['stream_stop'] = True
1145 th
= threading
.Thread(
1150 g
['original_name']))
1155 printNicely(cyan('Only: ' + str(args
.filter)))
1157 printNicely(red('Ignore: ' + str(args
.ignore
)))
1160 printNicely(red('Sorry I can\'t understand.'))
1165 Unix's command `cal`
1168 rel
= os
.popen('cal').read().split('\n')
1171 show_calendar(month
, date
, rel
)
1176 List and change theme
1180 for theme
in g
['themes']:
1181 line
= light_magenta(theme
)
1182 if c
['THEME'] == theme
:
1183 line
= ' ' * 2 + light_yellow('* ') + line
1185 line
= ' ' * 4 + line
1191 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1192 # Redefine decorated_name
1193 g
['decorated_name'] = lambda x
: color_func(
1194 c
['DECORATED_NAME'])(
1196 printNicely(green('Theme changed.'))
1198 printNicely(red('No such theme exists.'))
1203 Browse and change config
1205 all_config
= get_all_config()
1206 g
['stuff'] = g
['stuff'].strip()
1209 for k
in all_config
:
1211 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1213 guide
= 'Detailed explanation can be found at ' + \
1214 color_func(c
['TWEET']['link'])(
1215 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1217 # Print specific config
1218 elif len(g
['stuff'].split()) == 1:
1219 if g
['stuff'] in all_config
:
1222 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1225 printNicely(red('No such config key.'))
1226 # Print specific config's default value
1227 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1228 key
= g
['stuff'].split()[0]
1230 value
= get_default_config(key
)
1231 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1233 except Exception as e
:
1235 # Delete specific config key in config file
1236 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1237 key
= g
['stuff'].split()[0]
1240 printNicely(green('Config key is dropped.'))
1241 except Exception as e
:
1243 # Set specific config
1244 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1245 key
= g
['stuff'].split()[0]
1246 value
= g
['stuff'].split()[-1]
1247 if key
== 'THEME' and not validate_theme(value
):
1248 printNicely(red('Invalid theme\'s value.'))
1251 set_config(key
, value
)
1252 # Apply theme immediately
1254 c
['THEME'] = reload_theme(value
, c
['THEME'])
1255 g
['decorated_name'] = lambda x
: color_func(
1256 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1258 printNicely(green('Updated successfully.'))
1259 except Exception as e
:
1262 printNicely(light_magenta('Sorry I can\'s understand.'))
1265 def help_discover():
1270 # Discover the world
1272 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1273 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1274 'You can try ' + light_green('trend US') + ' or ' + \
1275 light_green('trend JP Tokyo') + '.\n'
1276 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1277 light_green('home 7') + ' will show 7 tweets.\n'
1279 light_green('notification') + ' will show your recent notification.\n'
1280 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1281 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1282 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1283 magenta('@mdo') + '.\n'
1284 usage
+= s
* 2 + light_green('view @mdo') + \
1285 ' will show ' + magenta('@mdo') + '\'s home.\n'
1286 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1287 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1288 'Search can be performed with or without hashtag.\n'
1299 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1300 usage
+= s
* 2 + light_green('t oops ') + \
1301 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1303 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1304 light_yellow('[id=12]') + '.\n'
1306 light_green('quote 12 ') + ' will quote the tweet with ' + \
1307 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1308 'the quote will be canceled.\n'
1310 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1311 light_yellow('[id=12]') + '.\n'
1312 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1313 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1314 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1315 light_yellow('oops') + '" to tweet with ' + \
1316 light_yellow('[id=12]') + '.\n'
1318 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1319 light_yellow('[id=12]') + '.\n'
1321 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1322 light_yellow('[id=12]') + '.\n'
1324 light_green('del 12 ') + ' will delete tweet with ' + \
1325 light_yellow('[id=12]') + '.\n'
1326 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1327 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1328 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1329 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1333 def help_messages():
1340 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1341 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1342 light_green('inbox 7') + ' will show newest 7 messages.\n'
1343 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1344 light_yellow('[thread_id=2]') + '.\n'
1345 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1346 magenta('@dtvd88') + '.\n'
1347 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1348 light_yellow('[message_id=5]') + '.\n'
1352 def help_friends_and_followers():
1354 Friends and Followers
1357 # Follower and following
1359 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1361 light_green('ls fl') + \
1362 ' will list all followers (people who are following you).\n'
1364 light_green('ls fr') + \
1365 ' will list all friends (people who you are following).\n'
1366 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1367 magenta('@dtvd88') + '.\n'
1368 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1369 magenta('@dtvd88') + '.\n'
1370 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1371 magenta('@dtvd88') + '.\n'
1372 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1373 magenta('@dtvd88') + '.\n'
1374 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1375 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1376 magenta('@dtvd88') + '.\n'
1377 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1378 magenta('@dtvd88') + '.\n'
1379 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1380 magenta('@dtvd88') + ' as a spam account.\n'
1391 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1392 usage
+= s
* 2 + light_green('list') + \
1393 ' will show all lists you are belong to.\n'
1394 usage
+= s
* 2 + light_green('list home') + \
1395 ' will show timeline of list. You will be asked for list\'s name.\n'
1396 usage
+= s
* 2 + light_green('list all_mem') + \
1397 ' will show list\'s all members.\n'
1398 usage
+= s
* 2 + light_green('list all_sub') + \
1399 ' will show list\'s all subscribers.\n'
1400 usage
+= s
* 2 + light_green('list add') + \
1401 ' will add specific person to a list owned by you.' + \
1402 ' You will be asked for list\'s name and person\'s name.\n'
1403 usage
+= s
* 2 + light_green('list rm') + \
1404 ' will remove specific person from a list owned by you.' + \
1405 ' You will be asked for list\'s name and person\'s name.\n'
1406 usage
+= s
* 2 + light_green('list sub') + \
1407 ' will subscribe you to a specific list.\n'
1408 usage
+= s
* 2 + light_green('list unsub') + \
1409 ' will unsubscribe you from a specific list.\n'
1410 usage
+= s
* 2 + light_green('list own') + \
1411 ' will show all list owned by you.\n'
1412 usage
+= s
* 2 + light_green('list new') + \
1413 ' will create a new list.\n'
1414 usage
+= s
* 2 + light_green('list update') + \
1415 ' will update a list owned by you.\n'
1416 usage
+= s
* 2 + light_green('list del') + \
1417 ' will delete a list owned by you.\n'
1428 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1429 usage
+= s
* 2 + light_green('switch public #AKB') + \
1430 ' will switch to public stream and follow "' + \
1431 light_yellow('AKB') + '" keyword.\n'
1432 usage
+= s
* 2 + light_green('switch mine') + \
1433 ' will switch to your personal stream.\n'
1434 usage
+= s
* 2 + light_green('switch mine -f ') + \
1435 ' will prompt to enter the filter.\n'
1436 usage
+= s
* 3 + light_yellow('Only nicks') + \
1437 ' filter will decide nicks will be INCLUDE ONLY.\n'
1438 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1439 ' filter will decide nicks will be EXCLUDE.\n'
1440 usage
+= s
* 2 + light_green('switch mine -d') + \
1441 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1450 h
, w
= os
.popen('stty size', 'r').read().split()
1453 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1454 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1455 usage
+= s
+ 'You are ' + \
1456 light_yellow('already') + ' on your personal stream.\n'
1457 usage
+= s
+ 'Any update from Twitter will show up ' + \
1458 light_yellow('immediately') + '.\n'
1459 usage
+= s
+ 'In addition, following commands are available right now:\n'
1460 # Twitter help section
1462 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1463 usage
+= s
* 2 + light_green('h discover') + \
1464 ' will show help for discover commands.\n'
1465 usage
+= s
* 2 + light_green('h tweets') + \
1466 ' will show help for tweets commands.\n'
1467 usage
+= s
* 2 + light_green('h messages') + \
1468 ' will show help for messages commands.\n'
1469 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1470 ' will show help for friends and followers commands.\n'
1471 usage
+= s
* 2 + light_green('h list') + \
1472 ' will show help for list commands.\n'
1473 usage
+= s
* 2 + light_green('h stream') + \
1474 ' will show help for stream commands.\n'
1477 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1478 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1479 'will be evaluate by Python interpreter.\n'
1480 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1481 ' for current month.\n'
1484 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1485 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1486 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1487 ' theme immediately.\n'
1488 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1490 light_green('config ASCII_ART') + ' will output current value of ' +\
1491 light_yellow('ASCII_ART') + ' config key.\n'
1493 light_green('config TREND_MAX default') + ' will output default value of ' + \
1494 light_yellow('TREND_MAX') + ' config key.\n'
1496 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1497 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1499 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1500 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1501 light_yellow('True') + '.\n'
1504 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1505 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1506 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1507 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1508 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1509 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1512 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1513 usage
+= s
+ 'Have fun and hang tight! \n'
1516 'discover': help_discover
,
1517 'tweets': help_tweets
,
1518 'messages': help_messages
,
1519 'friends_and_followers': help_friends_and_followers
,
1521 'stream': help_stream
,
1526 lambda: printNicely(red('No such command.'))
1534 Pause stream display
1537 printNicely(green('Stream is paused'))
1545 printNicely(green('Stream is running back now'))
1561 printNicely(green('See you next time :)'))
1569 Reset prefix of line
1572 if c
.get('USER_JSON_ERROR'):
1573 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1574 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1576 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1579 printNicely(str(eval(g
['cmd'])))
1629 # Handle function set
1679 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1684 Listen to user's input
1689 ['public', 'mine'], # switch
1706 ['image'], # show image
1708 ['fl', 'fr'], # list
1710 [i
for i
in g
['message_threads']], # sent
1735 [key
for key
in dict(get_all_config())], # config
1736 g
['themes'], # theme
1741 'friends_and_followers',
1751 init_interactive_shell(d
)
1758 # Only use PREFIX as a string with raw_input
1759 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1762 # Save cmd to compare with readline buffer
1763 g
['cmd'] = line
.strip()
1764 # Get short cmd to pass to handle function
1766 cmd
= line
.split()[0]
1769 # Lock the semaphore
1771 # Save cmd to global variable and call process
1772 g
['stuff'] = ' '.join(line
.split()[1:])
1773 # Process the command
1776 if cmd
in ['switch', 't', 'rt', 'rep']:
1780 # Release the semaphore lock
1786 printNicely(red('OMG something is wrong with Twitter right now.'))
1789 def stream(domain
, args
, name
='Rainbow Stream'):
1795 c
['USER_DOMAIN']: name
,
1796 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1797 c
['SITE_DOMAIN']: name
,
1800 ascii_art(art_dict
[domain
])
1801 # These arguments are optional:
1803 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1805 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1808 if args
.track_keywords
:
1809 query_args
['track'] = args
.track_keywords
1811 stream
= TwitterStream(
1816 if domain
== c
['USER_DOMAIN']:
1817 tweet_iter
= stream
.user(**query_args
)
1818 elif domain
== c
['SITE_DOMAIN']:
1819 tweet_iter
= stream
.site(**query_args
)
1821 if args
.track_keywords
:
1822 tweet_iter
= stream
.statuses
.filter(**query_args
)
1824 tweet_iter
= stream
.statuses
.sample()
1825 # Block new stream until other one exits
1826 StreamLock
.acquire()
1827 g
['stream_stop'] = False
1828 for tweet
in tweet_iter
:
1830 printNicely("-- None --")
1831 elif tweet
is Timeout
:
1832 if(g
['stream_stop']):
1833 StreamLock
.release()
1835 elif tweet
is HeartbeatTimeout
:
1836 printNicely("-- Heartbeat Timeout --")
1837 guide
= light_magenta("You can use ") + \
1838 light_green("switch") + \
1839 light_magenta(" command to return to your stream.\n")
1840 guide
+= light_magenta("Type ") + \
1841 light_green("h stream") + \
1842 light_magenta(" for more details.")
1844 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1846 StreamLock
.release()
1848 elif tweet
is Hangup
:
1849 printNicely("-- Hangup --")
1850 elif tweet
.get('text'):
1851 # Check the semaphore pause and lock (stream process only)
1859 keyword
=args
.track_keywords
,
1864 # Current readline buffer
1865 current_buffer
= readline
.get_line_buffer().strip()
1866 # There is an unexpected behaviour in MacOSX readline + Python 2:
1867 # after completely delete a word after typing it,
1868 # somehow readline buffer still contains
1869 # the 1st character of that word
1870 if current_buffer
and g
['cmd'] != current_buffer
:
1872 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1874 elif not c
['HIDE_PROMPT']:
1875 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1877 elif tweet
.get('direct_message'):
1878 # Check the semaphore pause and lock (stream process only)
1883 print_message(tweet
['direct_message'])
1884 elif tweet
.get('event'):
1885 g
['events'].append(tweet
)
1887 except TwitterHTTPError
:
1890 magenta("We have maximum connection problem with twitter'stream API right now :("))
1898 args
= parse_arguments()
1901 except TwitterHTTPError
:
1904 magenta("We have connection problem with twitter'stream API right now :("))
1905 printNicely(magenta("Let's try again later."))
1908 # Spawn stream thread
1909 th
= threading
.Thread(
1914 g
['original_name']))
1917 # Start listen process