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 *
30 StreamLock
= threading
.Lock()
33 def parse_arguments():
37 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
41 help='Timeout for the stream (seconds).')
45 help='Search the stream for specific text.')
49 help='Filter specific screen_name.')
53 help='Ignore specific screen_name.')
58 help='Run in debug mode.')
63 help='Display all image on terminal.')
64 return parser
.parse_args()
69 Authenticate with Twitter OAuth
71 # When using rainbow stream you must authorize.
72 twitter_credential
= os
.environ
.get(
76 '')) + os
.sep
+ '.rainbow_oauth'
77 if not os
.path
.exists(twitter_credential
):
78 oauth_dance("Rainbow Stream",
82 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
90 def build_mute_dict(dict_data
=False):
94 t
= Twitter(auth
=authen())
100 while next_cursor
!= 0:
101 list = t
.mutes
.users
.list(
102 screen_name
=g
['original_name'],
105 include_entities
=False,
107 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
108 name_list
+= [u
['name'] for u
in list['users']]
109 next_cursor
= list['next_cursor']
110 # Return dict or list
112 return dict(zip(screen_name_list
, name_list
))
114 return screen_name_list
119 Save traceback when run in debug mode
122 g
['traceback'].append(traceback
.format_exc())
130 ctrl_c_handler
= lambda signum
, frame
: quit()
131 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
133 t
= Twitter(auth
=authen())
134 credential
= t
.account
.verify_credentials()
135 screen_name
= '@' + credential
['screen_name']
136 name
= credential
['name']
137 if not get_config('PREFIX'):
138 set_config('PREFIX', screen_name
)
139 g
['PREFIX'] = u2str(c
['PREFIX'])
140 c
['original_name'] = g
['original_name'] = screen_name
[1:]
141 g
['full_name'] = name
142 g
['decorated_name'] = lambda x
: color_func(
143 c
['DECORATED_NAME'])('[' + x
+ ']: ')
145 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
146 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
149 g
['message_threads'] = {}
155 g
['debug'] = args
.debug
157 # Retweet of mine events
161 # Init tweet dict and message dict
163 c
['message_dict'] = []
165 c
['IMAGE_ON_TERM'] = args
.image_on_term
166 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
168 c
['IGNORE_LIST'] += build_mute_dict()
175 t
= Twitter(auth
=authen())
176 # Get country and town
178 country
= g
['stuff'].split()[0]
182 town
= g
['stuff'].split()[1]
185 avail
= t
.trends
.available()
188 trends
= t
.trends
.place(_id
=1)[0]['trends']
191 for location
in avail
:
192 # Search for country and Town
194 if location
['countryCode'] == country \
195 and location
['placeType']['name'] == 'Town' \
196 and location
['name'] == town
:
197 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
199 # Search for country only
201 if location
['countryCode'] == country \
202 and location
['placeType']['name'] == 'Country':
203 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
211 t
= Twitter(auth
=authen())
212 num
= c
['HOME_TWEET_NUM']
213 if g
['stuff'].isdigit():
214 num
= int(g
['stuff'])
215 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
224 g
['events'] = g
['events'] + c
['events']
226 for e
in g
['events']:
230 printNicely(magenta('Nothing at this time.'))
237 t
= Twitter(auth
=authen())
238 num
= c
['HOME_TWEET_NUM']
239 if g
['stuff'].isdigit():
240 num
= int(g
['stuff'])
241 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
248 Show profile of a specific user
250 t
= Twitter(auth
=authen())
251 screen_name
= g
['stuff'].split()[0]
252 if screen_name
.startswith('@'):
255 screen_name
=screen_name
[1:],
256 include_entities
=False)
260 printNicely(red('No user.'))
262 printNicely(red('A name should begin with a \'@\''))
269 t
= Twitter(auth
=authen())
270 user
= g
['stuff'].split()[0]
273 num
= int(g
['stuff'].split()[1])
275 num
= c
['HOME_TWEET_NUM']
276 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
280 printNicely(red('A name should begin with a \'@\''))
287 t
= Twitter(auth
=authen())
289 query
= g
['stuff'].strip()
290 type = c
['SEARCH_TYPE']
291 if type not in ['mixed', 'recent', 'popular']:
293 max_record
= c
['SEARCH_MAX_RECORD']
294 count
= min(max_record
, 100)
296 rel
= t
.search
.tweets(
303 printNicely('Newest tweets:')
304 for i
in reversed(xrange(count
)):
305 draw(t
=rel
[i
], keyword
=query
)
308 printNicely(magenta('I\'m afraid there is no result'))
315 t
= Twitter(auth
=authen())
316 t
.statuses
.update(status
=g
['stuff'])
323 t
= Twitter(auth
=authen())
325 id = int(g
['stuff'].split()[0])
327 printNicely(red('Sorry I can\'t understand.'))
329 tid
= c
['tweet_dict'][id]
330 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
338 t
= Twitter(auth
=authen())
340 id = int(g
['stuff'].split()[0])
342 printNicely(red('Sorry I can\'t understand.'))
344 tid
= c
['tweet_dict'][id]
345 tweet
= t
.statuses
.show(id=tid
)
347 formater
= format_quote(tweet
)
351 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
352 comment
= raw_input(prefix
)
354 quote
= comment
.join(formater
.split('#comment'))
355 t
.statuses
.update(status
=quote
)
357 printNicely(light_magenta('No text added.'))
364 t
= Twitter(auth
=authen())
367 id = int(g
['stuff'].split()[0])
369 printNicely(red('Sorry I can\'t understand.'))
371 tid
= c
['tweet_dict'][id]
372 # Get display num if exist
374 num
= int(g
['stuff'].split()[1])
376 num
= c
['RETWEETS_SHOW_NUM']
377 # Get result and display
378 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
380 printNicely(magenta('This tweet has no retweet.'))
382 for tweet
in reversed(rt_ary
):
391 t
= Twitter(auth
=authen())
393 id = int(g
['stuff'].split()[0])
395 printNicely(red('Sorry I can\'t understand.'))
397 tid
= c
['tweet_dict'][id]
398 tweet
= t
.statuses
.show(id=tid
)
399 limit
= c
['CONVERSATION_MAX']
401 thread_ref
.append(tweet
)
402 prev_tid
= tweet
['in_reply_to_status_id']
403 while prev_tid
and limit
:
405 tweet
= t
.statuses
.show(id=prev_tid
)
406 prev_tid
= tweet
['in_reply_to_status_id']
407 thread_ref
.append(tweet
)
409 for tweet
in reversed(thread_ref
):
418 t
= Twitter(auth
=authen())
420 id = int(g
['stuff'].split()[0])
422 printNicely(red('Sorry I can\'t understand.'))
424 tid
= c
['tweet_dict'][id]
425 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
426 status
= ' '.join(g
['stuff'].split()[1:])
427 status
= '@' + user
+ ' ' + str2u(status
)
428 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
435 t
= Twitter(auth
=authen())
437 id = int(g
['stuff'].split()[0])
439 printNicely(red('Sorry I can\'t understand.'))
441 tid
= c
['tweet_dict'][id]
442 t
.favorites
.create(_id
=tid
, include_entities
=False)
443 printNicely(green('Favorited.'))
444 draw(t
.statuses
.show(id=tid
))
452 t
= Twitter(auth
=authen())
454 id = int(g
['stuff'].split()[0])
456 printNicely(red('Sorry I can\'t understand.'))
458 tid
= c
['tweet_dict'][id]
459 t
.favorites
.destroy(_id
=tid
)
460 printNicely(green('Okay it\'s unfavorited.'))
461 draw(t
.statuses
.show(id=tid
))
469 t
= Twitter(auth
=authen())
471 id = int(g
['stuff'].split()[0])
473 printNicely(red('Sorry I can\'t understand.'))
475 tid
= c
['tweet_dict'][id]
476 t
.statuses
.destroy(id=tid
)
477 printNicely(green('Okay it\'s gone.'))
484 t
= Twitter(auth
=authen())
486 target
= g
['stuff'].split()[0]
487 if target
!= 'image':
489 id = int(g
['stuff'].split()[1])
490 tid
= c
['tweet_dict'][id]
491 tweet
= t
.statuses
.show(id=tid
)
492 media
= tweet
['entities']['media']
494 res
= requests
.get(m
['media_url'])
495 img
= Image
.open(BytesIO(res
.content
))
499 printNicely(red('Sorry I can\'t show this image.'))
506 t
= Twitter(auth
=authen())
508 if not g
['stuff'].isdigit():
510 tid
= c
['tweet_dict'][int(g
['stuff'])]
511 tweet
= t
.statuses
.show(id=tid
)
512 link_prefix
= ('http://', 'https://')
513 link_ary
= [u
for u
in tweet
['text'].split()
514 if u
.startswith(link_prefix
)]
516 printNicely(light_magenta('No url here @.@!'))
518 for link
in link_ary
:
519 webbrowser
.open(link
)
522 printNicely(red('Sorry I can\'t open url in this tweet.'))
529 t
= Twitter(auth
=authen())
530 num
= c
['MESSAGES_DISPLAY']
531 if g
['stuff'].isdigit():
537 inbox
= inbox
+ t
.direct_messages(
540 include_entities
=False,
545 inbox
= inbox
+ t
.direct_messages(
548 include_entities
=False,
552 num
= c
['MESSAGES_DISPLAY']
553 if g
['stuff'].isdigit():
558 sent
= sent
+ t
.direct_messages
.sent(
561 include_entities
=False,
566 sent
= sent
+ t
.direct_messages
.sent(
569 include_entities
=False,
574 uniq_inbox
= list(set(
575 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
577 uniq_sent
= list(set(
578 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
580 for partner
in uniq_inbox
:
581 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
583 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
584 d
[partner
] = inbox_ary
+ sent_ary
585 for partner
in uniq_sent
:
588 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
589 g
['message_threads'] = print_threads(d
)
594 View a thread of message
597 thread_id
= int(g
['stuff'])
599 g
['message_threads'][thread_id
],
604 printNicely(red('No such thread.'))
609 Send a direct message
611 t
= Twitter(auth
=authen())
613 user
= g
['stuff'].split()[0]
614 if user
[0].startswith('@'):
615 content
= ' '.join(g
['stuff'].split()[1:])
616 t
.direct_messages
.new(
617 screen_name
=user
[1:],
620 printNicely(green('Message sent.'))
622 printNicely(red('A name should begin with a \'@\''))
625 printNicely(red('Sorry I can\'t understand.'))
632 t
= Twitter(auth
=authen())
634 id = int(g
['stuff'].split()[0])
636 printNicely(red('Sorry I can\'t understand.'))
637 mid
= c
['message_dict'][id]
638 t
.direct_messages
.destroy(id=mid
)
639 printNicely(green('Message deleted.'))
644 List friends for followers
646 t
= Twitter(auth
=authen())
649 name
= g
['stuff'].split()[1]
650 if name
.startswith('@'):
653 printNicely(red('A name should begin with a \'@\''))
654 raise Exception('Invalid name')
656 name
= g
['original_name']
657 # Get list followers or friends
659 target
= g
['stuff'].split()[0]
661 printNicely(red('Omg some syntax is wrong.'))
663 d
= {'fl': 'followers', 'fr': 'friends'}
667 while next_cursor
!= 0:
668 list = getattr(t
, d
[target
]).list(
672 include_entities
=False,
674 for u
in list['users']:
675 rel
[u
['name']] = '@' + u
['screen_name']
676 next_cursor
= list['next_cursor']
678 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
680 user
= ' ' + cycle_color(name
)
681 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
689 t
= Twitter(auth
=authen())
690 screen_name
= g
['stuff'].split()[0]
691 if screen_name
.startswith('@'):
692 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
693 printNicely(green('You are following ' + screen_name
+ ' now!'))
695 printNicely(red('A name should begin with a \'@\''))
702 t
= Twitter(auth
=authen())
703 screen_name
= g
['stuff'].split()[0]
704 if screen_name
.startswith('@'):
705 t
.friendships
.destroy(
706 screen_name
=screen_name
[1:],
707 include_entities
=False)
708 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
710 printNicely(red('A name should begin with a \'@\''))
717 t
= Twitter(auth
=authen())
719 screen_name
= g
['stuff'].split()[0]
721 printNicely(red('A name should be specified. '))
723 if screen_name
.startswith('@'):
725 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
726 if isinstance(rel
, dict):
727 printNicely(green(screen_name
+ ' is muted.'))
728 c
['IGNORE_LIST'] += [unc(screen_name
)]
729 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
731 printNicely(red(rel
))
734 printNicely(red('Something is wrong, can not mute now :('))
736 printNicely(red('A name should begin with a \'@\''))
743 t
= Twitter(auth
=authen())
745 screen_name
= g
['stuff'].split()[0]
747 printNicely(red('A name should be specified. '))
749 if screen_name
.startswith('@'):
751 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
752 if isinstance(rel
, dict):
753 printNicely(green(screen_name
+ ' is unmuted.'))
754 c
['IGNORE_LIST'].remove(screen_name
)
756 printNicely(red(rel
))
758 printNicely(red('Maybe you are not muting this person ?'))
760 printNicely(red('A name should begin with a \'@\''))
767 # Get dict of muting users
768 md
= build_mute_dict(dict_data
=True)
769 printNicely('All: ' + str(len(md
)) + ' people.')
771 user
= ' ' + cycle_color(md
[name
])
772 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
774 # Update from Twitter
775 c
['IGNORE_LIST'] = [n
for n
in md
]
782 t
= Twitter(auth
=authen())
783 screen_name
= g
['stuff'].split()[0]
784 if screen_name
.startswith('@'):
786 screen_name
=screen_name
[1:],
787 include_entities
=False,
789 printNicely(green('You blocked ' + screen_name
+ '.'))
791 printNicely(red('A name should begin with a \'@\''))
798 t
= Twitter(auth
=authen())
799 screen_name
= g
['stuff'].split()[0]
800 if screen_name
.startswith('@'):
802 screen_name
=screen_name
[1:],
803 include_entities
=False,
805 printNicely(green('Unblock ' + screen_name
+ ' success!'))
807 printNicely(red('A name should begin with a \'@\''))
812 Report a user as a spam account
814 t
= Twitter(auth
=authen())
815 screen_name
= g
['stuff'].split()[0]
816 if screen_name
.startswith('@'):
818 screen_name
=screen_name
[1:])
819 printNicely(green('You reported ' + screen_name
+ '.'))
821 printNicely(red('Sorry I can\'t understand.'))
829 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
830 # Get list name and owner
832 owner
, slug
= list_name
.split('/')
833 if slug
.startswith('@'):
838 light_magenta('List name should follow "@owner/list_name" format.'))
839 raise Exception('Wrong list name')
846 rel
= t
.lists
.list(screen_name
=g
['original_name'])
850 printNicely(light_magenta('You belong to no lists :)'))
857 owner
, slug
= get_slug()
858 res
= t
.lists
.statuses(
860 owner_screen_name
=owner
,
862 include_entities
=False)
872 owner
, slug
= get_slug()
876 while next_cursor
!= 0:
879 owner_screen_name
=owner
,
881 include_entities
=False)
883 rel
[u
['name']] = '@' + u
['screen_name']
884 next_cursor
= m
['next_cursor']
885 printNicely('All: ' + str(len(rel
)) + ' members.')
887 user
= ' ' + cycle_color(name
)
888 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
892 def list_subscribers(t
):
896 owner
, slug
= get_slug()
900 while next_cursor
!= 0:
901 m
= t
.lists
.subscribers(
903 owner_screen_name
=owner
,
905 include_entities
=False)
907 rel
[u
['name']] = '@' + u
['screen_name']
908 next_cursor
= m
['next_cursor']
909 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
911 user
= ' ' + cycle_color(name
)
912 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
918 Add specific user to a list
920 owner
, slug
= get_slug()
922 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
923 if user_name
.startswith('@'):
924 user_name
= user_name
[1:]
926 t
.lists
.members
.create(
928 owner_screen_name
=owner
,
929 screen_name
=user_name
)
930 printNicely(green('Added.'))
933 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
938 Remove specific user from a list
940 owner
, slug
= get_slug()
942 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
943 if user_name
.startswith('@'):
944 user_name
= user_name
[1:]
946 t
.lists
.members
.destroy(
948 owner_screen_name
=owner
,
949 screen_name
=user_name
)
950 printNicely(green('Gone.'))
953 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
956 def list_subscribe(t
):
960 owner
, slug
= get_slug()
963 t
.lists
.subscribers
.create(
965 owner_screen_name
=owner
)
966 printNicely(green('Done.'))
970 light_magenta('I\'m sorry you can not subscribe to this list.'))
973 def list_unsubscribe(t
):
977 owner
, slug
= get_slug()
980 t
.lists
.subscribers
.destroy(
982 owner_screen_name
=owner
)
983 printNicely(green('Done.'))
987 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
996 while next_cursor
!= 0:
997 res
= t
.lists
.ownerships(
998 screen_name
=g
['original_name'],
1001 next_cursor
= res
['next_cursor']
1005 printNicely(light_magenta('You own no lists :)'))
1012 name
= raw_input(light_magenta('New list\'s name: '))
1013 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1014 description
= raw_input(light_magenta('New list\'s description: '))
1019 description
=description
)
1020 printNicely(green(name
+ ' list is created.'))
1023 printNicely(red('Oops something is wrong with Twitter :('))
1030 slug
= raw_input(light_magenta('Your list that you want to update: '))
1031 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1032 mode
= raw_input(light_magenta('Update mode (public/private): '))
1033 description
= raw_input(light_magenta('Update description: '))
1037 slug
='-'.join(slug
.split()),
1038 owner_screen_name
=g
['original_name'],
1041 description
=description
)
1045 owner_screen_name
=g
['original_name'],
1047 description
=description
)
1048 printNicely(green(slug
+ ' list is updated.'))
1051 printNicely(red('Oops something is wrong with Twitter :('))
1058 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1061 slug
='-'.join(slug
.split()),
1062 owner_screen_name
=g
['original_name'])
1063 printNicely(green(slug
+ ' list is deleted.'))
1066 printNicely(red('Oops something is wrong with Twitter :('))
1073 t
= Twitter(auth
=authen())
1074 # List all lists or base on action
1076 g
['list_action'] = g
['stuff'].split()[0]
1083 'all_mem': list_members
,
1084 'all_sub': list_subscribers
,
1087 'sub': list_subscribe
,
1088 'unsub': list_unsubscribe
,
1091 'update': list_update
,
1095 return action_ary
[g
['list_action']](t
)
1097 printNicely(red('Please try again.'))
1105 target
= g
['stuff'].split()[0]
1107 args
= parse_arguments()
1109 if g
['stuff'].split()[-1] == '-f':
1110 guide
= 'To ignore an option, just hit Enter key.'
1111 printNicely(light_magenta(guide
))
1112 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1113 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1114 args
.filter = filter(None, only
.split(','))
1115 args
.ignore
= filter(None, ignore
.split(','))
1116 elif g
['stuff'].split()[-1] == '-d':
1117 args
.filter = c
['ONLY_LIST']
1118 args
.ignore
= c
['IGNORE_LIST']
1120 printNicely(red('Sorry, wrong format.'))
1123 if target
== 'public':
1124 keyword
= g
['stuff'].split()[1]
1125 if keyword
[0] == '#':
1126 keyword
= keyword
[1:]
1128 g
['stream_stop'] = True
1129 args
.track_keywords
= keyword
1131 th
= threading
.Thread(
1139 elif target
== 'mine':
1141 g
['stream_stop'] = True
1143 th
= threading
.Thread(
1148 g
['original_name']))
1153 printNicely(cyan('Only: ' + str(args
.filter)))
1155 printNicely(red('Ignore: ' + str(args
.ignore
)))
1158 printNicely(red('Sorry I can\'t understand.'))
1163 Unix's command `cal`
1166 rel
= os
.popen('cal').read().split('\n')
1169 show_calendar(month
, date
, rel
)
1174 List and change theme
1178 for theme
in g
['themes']:
1179 line
= light_magenta(theme
)
1180 if c
['THEME'] == theme
:
1181 line
= ' ' * 2 + light_yellow('* ') + line
1183 line
= ' ' * 4 + line
1189 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1190 # Redefine decorated_name
1191 g
['decorated_name'] = lambda x
: color_func(
1192 c
['DECORATED_NAME'])(
1194 printNicely(green('Theme changed.'))
1196 printNicely(red('No such theme exists.'))
1201 Browse and change config
1203 all_config
= get_all_config()
1204 g
['stuff'] = g
['stuff'].strip()
1207 for k
in all_config
:
1209 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1211 guide
= 'Detailed explanation can be found at ' + \
1212 color_func(c
['TWEET']['link'])(
1213 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1215 # Print specific config
1216 elif len(g
['stuff'].split()) == 1:
1217 if g
['stuff'] in all_config
:
1220 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1223 printNicely(red('No such config key.'))
1224 # Print specific config's default value
1225 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1226 key
= g
['stuff'].split()[0]
1228 value
= get_default_config(key
)
1229 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1231 except Exception as e
:
1233 # Delete specific config key in config file
1234 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1235 key
= g
['stuff'].split()[0]
1238 printNicely(green('Config key is dropped.'))
1239 except Exception as e
:
1241 # Set specific config
1242 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1243 key
= g
['stuff'].split()[0]
1244 value
= g
['stuff'].split()[-1]
1245 if key
== 'THEME' and not validate_theme(value
):
1246 printNicely(red('Invalid theme\'s value.'))
1249 set_config(key
, value
)
1250 # Apply theme immediately
1252 c
['THEME'] = reload_theme(value
, c
['THEME'])
1253 g
['decorated_name'] = lambda x
: color_func(
1254 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1256 printNicely(green('Updated successfully.'))
1257 except Exception as e
:
1260 printNicely(light_magenta('Sorry I can\'s understand.'))
1263 def help_discover():
1268 # Discover the world
1270 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1271 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1272 'You can try ' + light_green('trend US') + ' or ' + \
1273 light_green('trend JP Tokyo') + '.\n'
1274 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1275 light_green('home 7') + ' will show 7 tweets.\n'
1277 light_green('notification') + ' will show your recent notification.\n'
1278 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1279 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1280 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1281 magenta('@mdo') + '.\n'
1282 usage
+= s
* 2 + light_green('view @mdo') + \
1283 ' will show ' + magenta('@mdo') + '\'s home.\n'
1284 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1285 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1286 'Search can be performed with or without hashtag.\n'
1297 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1298 usage
+= s
* 2 + light_green('t oops ') + \
1299 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1301 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1302 light_yellow('[id=12]') + '.\n'
1304 light_green('quote 12 ') + ' will quote the tweet with ' + \
1305 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1306 'the quote will be canceled.\n'
1308 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1309 light_yellow('[id=12]') + '.\n'
1310 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1311 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1312 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1313 light_yellow('oops') + '" to tweet with ' + \
1314 light_yellow('[id=12]') + '.\n'
1316 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1317 light_yellow('[id=12]') + '.\n'
1319 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1320 light_yellow('[id=12]') + '.\n'
1322 light_green('del 12 ') + ' will delete tweet with ' + \
1323 light_yellow('[id=12]') + '.\n'
1324 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1325 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1326 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1327 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1331 def help_messages():
1338 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1339 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1340 light_green('inbox 7') + ' will show newest 7 messages.\n'
1341 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1342 light_yellow('[thread_id=2]') + '.\n'
1343 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1344 magenta('@dtvd88') + '.\n'
1345 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1346 light_yellow('[message_id=5]') + '.\n'
1350 def help_friends_and_followers():
1352 Friends and Followers
1355 # Follower and following
1357 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1359 light_green('ls fl') + \
1360 ' will list all followers (people who are following you).\n'
1362 light_green('ls fr') + \
1363 ' will list all friends (people who you are following).\n'
1364 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1365 magenta('@dtvd88') + '.\n'
1366 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1367 magenta('@dtvd88') + '.\n'
1368 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1369 magenta('@dtvd88') + '.\n'
1370 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1371 magenta('@dtvd88') + '.\n'
1372 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1373 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1374 magenta('@dtvd88') + '.\n'
1375 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1376 magenta('@dtvd88') + '.\n'
1377 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1378 magenta('@dtvd88') + ' as a spam account.\n'
1389 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1390 usage
+= s
* 2 + light_green('list') + \
1391 ' will show all lists you are belong to.\n'
1392 usage
+= s
* 2 + light_green('list home') + \
1393 ' will show timeline of list. You will be asked for list\'s name.\n'
1394 usage
+= s
* 2 + light_green('list all_mem') + \
1395 ' will show list\'s all members.\n'
1396 usage
+= s
* 2 + light_green('list all_sub') + \
1397 ' will show list\'s all subscribers.\n'
1398 usage
+= s
* 2 + light_green('list add') + \
1399 ' will add specific person to a list owned by you.' + \
1400 ' You will be asked for list\'s name and person\'s name.\n'
1401 usage
+= s
* 2 + light_green('list rm') + \
1402 ' will remove specific person from a list owned by you.' + \
1403 ' You will be asked for list\'s name and person\'s name.\n'
1404 usage
+= s
* 2 + light_green('list sub') + \
1405 ' will subscribe you to a specific list.\n'
1406 usage
+= s
* 2 + light_green('list unsub') + \
1407 ' will unsubscribe you from a specific list.\n'
1408 usage
+= s
* 2 + light_green('list own') + \
1409 ' will show all list owned by you.\n'
1410 usage
+= s
* 2 + light_green('list new') + \
1411 ' will create a new list.\n'
1412 usage
+= s
* 2 + light_green('list update') + \
1413 ' will update a list owned by you.\n'
1414 usage
+= s
* 2 + light_green('list del') + \
1415 ' will delete a list owned by you.\n'
1426 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1427 usage
+= s
* 2 + light_green('switch public #AKB') + \
1428 ' will switch to public stream and follow "' + \
1429 light_yellow('AKB') + '" keyword.\n'
1430 usage
+= s
* 2 + light_green('switch mine') + \
1431 ' will switch to your personal stream.\n'
1432 usage
+= s
* 2 + light_green('switch mine -f ') + \
1433 ' will prompt to enter the filter.\n'
1434 usage
+= s
* 3 + light_yellow('Only nicks') + \
1435 ' filter will decide nicks will be INCLUDE ONLY.\n'
1436 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1437 ' filter will decide nicks will be EXCLUDE.\n'
1438 usage
+= s
* 2 + light_green('switch mine -d') + \
1439 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1448 h
, w
= os
.popen('stty size', 'r').read().split()
1451 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1452 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1453 usage
+= s
+ 'You are ' + \
1454 light_yellow('already') + ' on your personal stream.\n'
1455 usage
+= s
+ 'Any update from Twitter will show up ' + \
1456 light_yellow('immediately') + '.\n'
1457 usage
+= s
+ 'In addition, following commands are available right now:\n'
1458 # Twitter help section
1460 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1461 usage
+= s
* 2 + light_green('h discover') + \
1462 ' will show help for discover commands.\n'
1463 usage
+= s
* 2 + light_green('h tweets') + \
1464 ' will show help for tweets commands.\n'
1465 usage
+= s
* 2 + light_green('h messages') + \
1466 ' will show help for messages commands.\n'
1467 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1468 ' will show help for friends and followers commands.\n'
1469 usage
+= s
* 2 + light_green('h list') + \
1470 ' will show help for list commands.\n'
1471 usage
+= s
* 2 + light_green('h stream') + \
1472 ' will show help for stream commands.\n'
1475 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1476 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1477 'will be evaluate by Python interpreter.\n'
1478 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1479 ' for current month.\n'
1482 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1483 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1484 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1485 ' theme immediately.\n'
1486 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1488 light_green('config ASCII_ART') + ' will output current value of ' +\
1489 light_yellow('ASCII_ART') + ' config key.\n'
1491 light_green('config TREND_MAX default') + ' will output default value of ' + \
1492 light_yellow('TREND_MAX') + ' config key.\n'
1494 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1495 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1497 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1498 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1499 light_yellow('True') + '.\n'
1502 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1503 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1504 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1505 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1506 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1507 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1510 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1511 usage
+= s
+ 'Have fun and hang tight! \n'
1514 'discover': help_discover
,
1515 'tweets': help_tweets
,
1516 'messages': help_messages
,
1517 'friends_and_followers': help_friends_and_followers
,
1519 'stream': help_stream
,
1524 lambda: printNicely(red('No such command.'))
1532 Pause stream display
1535 printNicely(green('Stream is paused'))
1543 printNicely(green('Stream is running back now'))
1559 printNicely(green('See you next time :)'))
1567 Reset prefix of line
1570 if c
.get('USER_JSON_ERROR'):
1571 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1572 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1574 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1577 printNicely(str(eval(g
['cmd'])))
1627 # Handle function set
1677 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1682 Listen to user's input
1687 ['public', 'mine'], # switch
1704 ['image'], # show image
1706 ['fl', 'fr'], # list
1708 [i
for i
in g
['message_threads']], # sent
1733 [key
for key
in dict(get_all_config())], # config
1734 g
['themes'], # theme
1739 'friends_and_followers',
1749 init_interactive_shell(d
)
1756 # Only use PREFIX as a string with raw_input
1757 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1760 # Save cmd to compare with readline buffer
1761 g
['cmd'] = line
.strip()
1762 # Get short cmd to pass to handle function
1764 cmd
= line
.split()[0]
1767 # Lock the semaphore
1769 # Save cmd to global variable and call process
1770 g
['stuff'] = ' '.join(line
.split()[1:])
1771 # Process the command
1774 if cmd
in ['switch', 't', 'rt', 'rep']:
1778 # Release the semaphore lock
1784 printNicely(red('OMG something is wrong with Twitter right now.'))
1787 def stream(domain
, args
, name
='Rainbow Stream'):
1793 c
['USER_DOMAIN']: name
,
1794 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1795 c
['SITE_DOMAIN']: name
,
1798 ascii_art(art_dict
[domain
])
1799 # These arguments are optional:
1801 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1803 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1806 if args
.track_keywords
:
1807 query_args
['track'] = args
.track_keywords
1809 stream
= TwitterStream(
1814 if domain
== c
['USER_DOMAIN']:
1815 tweet_iter
= stream
.user(**query_args
)
1816 elif domain
== c
['SITE_DOMAIN']:
1817 tweet_iter
= stream
.site(**query_args
)
1819 if args
.track_keywords
:
1820 tweet_iter
= stream
.statuses
.filter(**query_args
)
1822 tweet_iter
= stream
.statuses
.sample()
1823 # Block new stream until other one exits
1824 StreamLock
.acquire()
1825 g
['stream_stop'] = False
1826 for tweet
in tweet_iter
:
1828 printNicely("-- None --")
1829 elif tweet
is Timeout
:
1830 if(g
['stream_stop']):
1831 StreamLock
.release()
1833 elif tweet
is HeartbeatTimeout
:
1834 printNicely("-- Heartbeat Timeout --")
1835 guide
= light_magenta("You can use ") + \
1836 light_green("switch") + \
1837 light_magenta(" command to return to your stream.\n")
1838 guide
+= light_magenta("Type ") + \
1839 light_green("h stream") + \
1840 light_magenta(" for more details.")
1842 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1844 StreamLock
.release()
1846 elif tweet
is Hangup
:
1847 printNicely("-- Hangup --")
1848 elif tweet
.get('text'):
1849 # Check the semaphore pause and lock (stream process only)
1857 keyword
=args
.track_keywords
,
1862 # Current readline buffer
1863 current_buffer
= readline
.get_line_buffer().strip()
1864 # There is an unexpected behaviour in MacOSX readline + Python 2:
1865 # after completely delete a word after typing it,
1866 # somehow readline buffer still contains
1867 # the 1st character of that word
1868 if current_buffer
and g
['cmd'] != current_buffer
:
1870 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1872 elif not c
['HIDE_PROMPT']:
1873 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1875 elif tweet
.get('direct_message'):
1876 # Check the semaphore pause and lock (stream process only)
1881 print_message(tweet
['direct_message'])
1882 elif tweet
.get('event'):
1883 g
['events'].append(tweet
)
1885 except TwitterHTTPError
:
1888 magenta("We have maximum connection problem with twitter'stream API right now :("))
1896 args
= parse_arguments()
1899 except TwitterHTTPError
:
1902 magenta("We have connection problem with twitter'stream API right now :("))
1903 printNicely(magenta("Let's try again later."))
1906 # Spawn stream thread
1907 th
= threading
.Thread(
1912 g
['original_name']))
1915 # Start listen process