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
['original_name'] = screen_name
[1:]
126 g
['full_name'] = name
127 g
['decorated_name'] = lambda x
: color_func(
128 c
['DECORATED_NAME'])('[' + x
+ ']: ')
130 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
131 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
134 g
['message_threads'] = {}
139 # Init tweet dict and message dict
141 c
['message_dict'] = []
143 c
['IMAGE_ON_TERM'] = args
.image_on_term
144 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
146 c
['IGNORE_LIST'] += build_mute_dict()
153 t
= Twitter(auth
=authen())
154 # Get country and town
156 country
= g
['stuff'].split()[0]
160 town
= g
['stuff'].split()[1]
163 avail
= t
.trends
.available()
166 trends
= t
.trends
.place(_id
=1)[0]['trends']
169 for location
in avail
:
170 # Search for country and Town
172 if location
['countryCode'] == country \
173 and location
['placeType']['name'] == 'Town' \
174 and location
['name'] == town
:
175 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
177 # Search for country only
179 if location
['countryCode'] == country \
180 and location
['placeType']['name'] == 'Country':
181 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
189 t
= Twitter(auth
=authen())
190 num
= c
['HOME_TWEET_NUM']
191 if g
['stuff'].isdigit():
192 num
= int(g
['stuff'])
193 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
202 t
= Twitter(auth
=authen())
203 num
= c
['HOME_TWEET_NUM']
204 if g
['stuff'].isdigit():
205 num
= int(g
['stuff'])
206 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
213 Show profile of a specific user
215 t
= Twitter(auth
=authen())
216 screen_name
= g
['stuff'].split()[0]
217 if screen_name
.startswith('@'):
220 screen_name
=screen_name
[1:],
221 include_entities
=False)
224 printNicely(red('Omg no user.'))
226 printNicely(red('A name should begin with a \'@\''))
233 t
= Twitter(auth
=authen())
234 user
= g
['stuff'].split()[0]
237 num
= int(g
['stuff'].split()[1])
239 num
= c
['HOME_TWEET_NUM']
240 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
244 printNicely(red('A name should begin with a \'@\''))
251 t
= Twitter(auth
=authen())
252 g
['stuff'] = g
['stuff'].strip()
253 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
255 printNicely('Newest tweets:')
256 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
261 printNicely(magenta('I\'m afraid there is no result'))
268 t
= Twitter(auth
=authen())
269 t
.statuses
.update(status
=g
['stuff'])
276 t
= Twitter(auth
=authen())
278 id = int(g
['stuff'].split()[0])
280 printNicely(red('Sorry I can\'t understand.'))
282 tid
= c
['tweet_dict'][id]
283 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
291 t
= Twitter(auth
=authen())
293 id = int(g
['stuff'].split()[0])
295 printNicely(red('Sorry I can\'t understand.'))
297 tid
= c
['tweet_dict'][id]
298 tweet
= t
.statuses
.show(id=tid
)
300 formater
= format_quote(tweet
)
304 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
305 comment
= raw_input(prefix
)
307 quote
= comment
.join(formater
.split('#comment'))
308 t
.statuses
.update(status
=quote
)
310 printNicely(light_magenta('No text added.'))
317 t
= Twitter(auth
=authen())
320 id = int(g
['stuff'].split()[0])
322 printNicely(red('Sorry I can\'t understand.'))
324 tid
= c
['tweet_dict'][id]
325 # Get display num if exist
327 num
= int(g
['stuff'].split()[1])
329 num
= c
['RETWEETS_SHOW_NUM']
330 # Get result and display
331 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
333 printNicely(magenta('This tweet has no retweet.'))
335 for tweet
in reversed(rt_ary
):
344 t
= Twitter(auth
=authen())
346 id = int(g
['stuff'].split()[0])
348 printNicely(red('Sorry I can\'t understand.'))
350 tid
= c
['tweet_dict'][id]
351 tweet
= t
.statuses
.show(id=tid
)
352 limit
= c
['CONVERSATION_MAX']
354 thread_ref
.append(tweet
)
355 prev_tid
= tweet
['in_reply_to_status_id']
356 while prev_tid
and limit
:
358 tweet
= t
.statuses
.show(id=prev_tid
)
359 prev_tid
= tweet
['in_reply_to_status_id']
360 thread_ref
.append(tweet
)
362 for tweet
in reversed(thread_ref
):
371 t
= Twitter(auth
=authen())
373 id = int(g
['stuff'].split()[0])
375 printNicely(red('Sorry I can\'t understand.'))
377 tid
= c
['tweet_dict'][id]
378 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
379 status
= ' '.join(g
['stuff'].split()[1:])
380 status
= '@' + user
+ ' ' + str2u(status
)
381 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
388 t
= Twitter(auth
=authen())
390 id = int(g
['stuff'].split()[0])
392 printNicely(red('Sorry I can\'t understand.'))
394 tid
= c
['tweet_dict'][id]
395 t
.favorites
.create(_id
=tid
, include_entities
=False)
396 printNicely(green('Favorited.'))
397 draw(t
.statuses
.show(id=tid
))
405 t
= Twitter(auth
=authen())
407 id = int(g
['stuff'].split()[0])
409 printNicely(red('Sorry I can\'t understand.'))
411 tid
= c
['tweet_dict'][id]
412 t
.favorites
.destroy(_id
=tid
)
413 printNicely(green('Okay it\'s unfavorited.'))
414 draw(t
.statuses
.show(id=tid
))
422 t
= Twitter(auth
=authen())
424 id = int(g
['stuff'].split()[0])
426 printNicely(red('Sorry I can\'t understand.'))
428 tid
= c
['tweet_dict'][id]
429 t
.statuses
.destroy(id=tid
)
430 printNicely(green('Okay it\'s gone.'))
437 t
= Twitter(auth
=authen())
439 target
= g
['stuff'].split()[0]
440 if target
!= 'image':
442 id = int(g
['stuff'].split()[1])
443 tid
= c
['tweet_dict'][id]
444 tweet
= t
.statuses
.show(id=tid
)
445 media
= tweet
['entities']['media']
447 res
= requests
.get(m
['media_url'])
448 img
= Image
.open(BytesIO(res
.content
))
451 printNicely(red('Sorry I can\'t show this image.'))
458 t
= Twitter(auth
=authen())
460 if not g
['stuff'].isdigit():
462 tid
= c
['tweet_dict'][int(g
['stuff'])]
463 tweet
= t
.statuses
.show(id=tid
)
465 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
467 printNicely(light_magenta('No url here @.@!'))
469 for link
in link_ary
:
470 webbrowser
.open(link
)
472 printNicely(red('Sorry I can\'t open url in this tweet.'))
479 t
= Twitter(auth
=authen())
480 num
= c
['MESSAGES_DISPLAY']
481 if g
['stuff'].isdigit():
487 inbox
= inbox
+ t
.direct_messages(
490 include_entities
=False,
495 inbox
= inbox
+ t
.direct_messages(
498 include_entities
=False,
502 num
= c
['MESSAGES_DISPLAY']
503 if g
['stuff'].isdigit():
508 sent
= sent
+ t
.direct_messages
.sent(
511 include_entities
=False,
516 sent
= sent
+ t
.direct_messages
.sent(
519 include_entities
=False,
524 uniq_inbox
= list(set(
525 [(m
['sender_screen_name'],m
['sender']['name']) for m
in inbox
]
528 [(m
['recipient_screen_name'],m
['recipient']['name']) for m
in sent
]
530 for partner
in uniq_inbox
:
531 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
532 sent_ary
= [m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
533 d
[partner
] = inbox_ary
+ sent_ary
534 for partner
in uniq_sent
:
536 d
[partner
] = [m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
537 g
['message_threads'] = print_threads(d
)
542 View a thread of message
545 thread_id
= int(g
['stuff'])
546 print_thread(g
['message_threads'][thread_id
],g
['original_name'],g
['full_name'])
547 except Exception as e
:
550 print(traceback
.format_exc())
551 printNicely(red('No such thread.'))
556 Send a direct message
558 t
= Twitter(auth
=authen())
559 user
= g
['stuff'].split()[0]
560 if user
[0].startswith('@'):
562 content
= g
['stuff'].split()[1]
564 printNicely(red('Sorry I can\'t understand.'))
565 t
.direct_messages
.new(
566 screen_name
=user
[1:],
569 printNicely(green('Message sent.'))
571 printNicely(red('A name should begin with a \'@\''))
578 t
= Twitter(auth
=authen())
580 id = int(g
['stuff'].split()[0])
582 printNicely(red('Sorry I can\'t understand.'))
583 mid
= c
['message_dict'][id]
584 t
.direct_messages
.destroy(id=mid
)
585 printNicely(green('Message deleted.'))
590 List friends for followers
592 t
= Twitter(auth
=authen())
595 name
= g
['stuff'].split()[1]
596 if name
.startswith('@'):
599 printNicely(red('A name should begin with a \'@\''))
600 raise Exception('Invalid name')
602 name
= g
['original_name']
603 # Get list followers or friends
605 target
= g
['stuff'].split()[0]
607 printNicely(red('Omg some syntax is wrong.'))
609 d
= {'fl': 'followers', 'fr': 'friends'}
613 while next_cursor
!= 0:
614 list = getattr(t
, d
[target
]).list(
618 include_entities
=False,
620 for u
in list['users']:
621 rel
[u
['name']] = '@' + u
['screen_name']
622 next_cursor
= list['next_cursor']
624 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
626 user
= ' ' + cycle_color(name
)
627 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
635 t
= Twitter(auth
=authen())
636 screen_name
= g
['stuff'].split()[0]
637 if screen_name
.startswith('@'):
638 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
639 printNicely(green('You are following ' + screen_name
+ ' now!'))
641 printNicely(red('A name should begin with a \'@\''))
648 t
= Twitter(auth
=authen())
649 screen_name
= g
['stuff'].split()[0]
650 if screen_name
.startswith('@'):
651 t
.friendships
.destroy(
652 screen_name
=screen_name
[1:],
653 include_entities
=False)
654 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
656 printNicely(red('A name should begin with a \'@\''))
663 t
= Twitter(auth
=authen())
665 screen_name
= g
['stuff'].split()[0]
667 printNicely(red('A name should be specified. '))
669 if screen_name
.startswith('@'):
671 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
672 if isinstance(rel
, dict):
673 printNicely(green(screen_name
+ ' is muted.'))
674 c
['IGNORE_LIST'] += [unc(screen_name
)]
675 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
677 printNicely(red(rel
))
679 printNicely(red('Something is wrong, can not mute now :('))
681 printNicely(red('A name should begin with a \'@\''))
688 t
= Twitter(auth
=authen())
690 screen_name
= g
['stuff'].split()[0]
692 printNicely(red('A name should be specified. '))
694 if screen_name
.startswith('@'):
696 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
697 if isinstance(rel
, dict):
698 printNicely(green(screen_name
+ ' is unmuted.'))
699 c
['IGNORE_LIST'].remove(screen_name
)
701 printNicely(red(rel
))
703 printNicely(red('Maybe you are not muting this person ?'))
705 printNicely(red('A name should begin with a \'@\''))
712 # Get dict of muting users
713 md
= build_mute_dict(dict_data
=True)
714 printNicely('All: ' + str(len(md
)) + ' people.')
716 user
= ' ' + cycle_color(md
[name
])
717 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
719 # Update from Twitter
720 c
['IGNORE_LIST'] = [n
for n
in md
]
727 t
= Twitter(auth
=authen())
728 screen_name
= g
['stuff'].split()[0]
729 if screen_name
.startswith('@'):
731 screen_name
=screen_name
[1:],
732 include_entities
=False,
734 printNicely(green('You blocked ' + screen_name
+ '.'))
736 printNicely(red('A name should begin with a \'@\''))
743 t
= Twitter(auth
=authen())
744 screen_name
= g
['stuff'].split()[0]
745 if screen_name
.startswith('@'):
747 screen_name
=screen_name
[1:],
748 include_entities
=False,
750 printNicely(green('Unblock ' + screen_name
+ ' success!'))
752 printNicely(red('A name should begin with a \'@\''))
757 Report a user as a spam account
759 t
= Twitter(auth
=authen())
760 screen_name
= g
['stuff'].split()[0]
761 if screen_name
.startswith('@'):
763 screen_name
=screen_name
[1:])
764 printNicely(green('You reported ' + screen_name
+ '.'))
766 printNicely(red('Sorry I can\'t understand.'))
774 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
775 # Get list name and owner
777 owner
, slug
= list_name
.split('/')
778 if slug
.startswith('@'):
783 light_magenta('List name should follow "@owner/list_name" format.'))
784 raise Exception('Wrong list name')
791 rel
= t
.lists
.list(screen_name
=g
['original_name'])
795 printNicely(light_magenta('You belong to no lists :)'))
802 owner
, slug
= get_slug()
803 res
= t
.lists
.statuses(
805 owner_screen_name
=owner
,
807 include_entities
=False)
817 owner
, slug
= get_slug()
821 while next_cursor
!= 0:
824 owner_screen_name
=owner
,
826 include_entities
=False)
828 rel
[u
['name']] = '@' + u
['screen_name']
829 next_cursor
= m
['next_cursor']
830 printNicely('All: ' + str(len(rel
)) + ' members.')
832 user
= ' ' + cycle_color(name
)
833 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
837 def list_subscribers(t
):
841 owner
, slug
= get_slug()
845 while next_cursor
!= 0:
846 m
= t
.lists
.subscribers(
848 owner_screen_name
=owner
,
850 include_entities
=False)
852 rel
[u
['name']] = '@' + u
['screen_name']
853 next_cursor
= m
['next_cursor']
854 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
856 user
= ' ' + cycle_color(name
)
857 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
863 Add specific user to a list
865 owner
, slug
= get_slug()
867 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
868 if user_name
.startswith('@'):
869 user_name
= user_name
[1:]
871 t
.lists
.members
.create(
873 owner_screen_name
=owner
,
874 screen_name
=user_name
)
875 printNicely(green('Added.'))
877 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
882 Remove specific user from a list
884 owner
, slug
= get_slug()
886 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
887 if user_name
.startswith('@'):
888 user_name
= user_name
[1:]
890 t
.lists
.members
.destroy(
892 owner_screen_name
=owner
,
893 screen_name
=user_name
)
894 printNicely(green('Gone.'))
896 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
899 def list_subscribe(t
):
903 owner
, slug
= get_slug()
906 t
.lists
.subscribers
.create(
908 owner_screen_name
=owner
)
909 printNicely(green('Done.'))
912 light_magenta('I\'m sorry you can not subscribe to this list.'))
915 def list_unsubscribe(t
):
919 owner
, slug
= get_slug()
922 t
.lists
.subscribers
.destroy(
924 owner_screen_name
=owner
)
925 printNicely(green('Done.'))
928 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
937 while next_cursor
!= 0:
938 res
= t
.lists
.ownerships(
939 screen_name
=g
['original_name'],
942 next_cursor
= res
['next_cursor']
946 printNicely(light_magenta('You own no lists :)'))
953 name
= raw_input(light_magenta('New list\'s name: '))
954 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
955 description
= raw_input(light_magenta('New list\'s description: '))
960 description
=description
)
961 printNicely(green(name
+ ' list is created.'))
963 printNicely(red('Oops something is wrong with Twitter :('))
970 slug
= raw_input(light_magenta('Your list that you want to update: '))
971 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
972 mode
= raw_input(light_magenta('Update mode (public/private): '))
973 description
= raw_input(light_magenta('Update description: '))
977 slug
='-'.join(slug
.split()),
978 owner_screen_name
=g
['original_name'],
981 description
=description
)
985 owner_screen_name
=g
['original_name'],
987 description
=description
)
988 printNicely(green(slug
+ ' list is updated.'))
990 printNicely(red('Oops something is wrong with Twitter :('))
997 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1000 slug
='-'.join(slug
.split()),
1001 owner_screen_name
=g
['original_name'])
1002 printNicely(green(slug
+ ' list is deleted.'))
1004 printNicely(red('Oops something is wrong with Twitter :('))
1011 t
= Twitter(auth
=authen())
1012 # List all lists or base on action
1014 g
['list_action'] = g
['stuff'].split()[0]
1021 'all_mem': list_members
,
1022 'all_sub': list_subscribers
,
1025 'sub': list_subscribe
,
1026 'unsub': list_unsubscribe
,
1029 'update': list_update
,
1033 return action_ary
[g
['list_action']](t
)
1035 printNicely(red('Please try again.'))
1043 target
= g
['stuff'].split()[0]
1045 args
= parse_arguments()
1047 if g
['stuff'].split()[-1] == '-f':
1048 guide
= 'To ignore an option, just hit Enter key.'
1049 printNicely(light_magenta(guide
))
1050 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1051 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1052 args
.filter = filter(None, only
.split(','))
1053 args
.ignore
= filter(None, ignore
.split(','))
1054 elif g
['stuff'].split()[-1] == '-d':
1055 args
.filter = c
['ONLY_LIST']
1056 args
.ignore
= c
['IGNORE_LIST']
1058 printNicely(red('Sorry, wrong format.'))
1061 if target
== 'public':
1062 keyword
= g
['stuff'].split()[1]
1063 if keyword
[0] == '#':
1064 keyword
= keyword
[1:]
1066 g
['stream_stop'] = True
1067 args
.track_keywords
= keyword
1069 th
= threading
.Thread(
1077 elif target
== 'mine':
1079 g
['stream_stop'] = True
1081 th
= threading
.Thread(
1086 g
['original_name']))
1091 printNicely(cyan('Only: ' + str(args
.filter)))
1093 printNicely(red('Ignore: ' + str(args
.ignore
)))
1096 printNicely(red('Sorry I can\'t understand.'))
1101 Unix's command `cal`
1104 rel
= os
.popen('cal').read().split('\n')
1107 show_calendar(month
, date
, rel
)
1112 List and change theme
1116 for theme
in g
['themes']:
1117 line
= light_magenta(theme
)
1118 if c
['THEME'] == theme
:
1119 line
= ' ' * 2 + light_yellow('* ') + line
1121 line
= ' ' * 4 + line
1127 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1128 # Redefine decorated_name
1129 g
['decorated_name'] = lambda x
: color_func(
1130 c
['DECORATED_NAME'])(
1132 printNicely(green('Theme changed.'))
1134 printNicely(red('No such theme exists.'))
1139 Browse and change config
1141 all_config
= get_all_config()
1142 g
['stuff'] = g
['stuff'].strip()
1145 for k
in all_config
:
1147 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1149 guide
= 'Detailed explanation can be found at ' + \
1150 color_func(c
['TWEET']['link'])(
1151 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1153 # Print specific config
1154 elif len(g
['stuff'].split()) == 1:
1155 if g
['stuff'] in all_config
:
1158 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1161 printNicely(red('No such config key.'))
1162 # Print specific config's default value
1163 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1164 key
= g
['stuff'].split()[0]
1166 value
= get_default_config(key
)
1167 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1169 except Exception as e
:
1171 # Delete specific config key in config file
1172 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1173 key
= g
['stuff'].split()[0]
1176 printNicely(green('Config key is dropped.'))
1177 except Exception as e
:
1179 # Set specific config
1180 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1181 key
= g
['stuff'].split()[0]
1182 value
= g
['stuff'].split()[-1]
1183 if key
== 'THEME' and not validate_theme(value
):
1184 printNicely(red('Invalid theme\'s value.'))
1187 set_config(key
, value
)
1188 # Apply theme immediately
1190 c
['THEME'] = reload_theme(value
, c
['THEME'])
1191 g
['decorated_name'] = lambda x
: color_func(
1192 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1194 printNicely(green('Updated successfully.'))
1195 except Exception as e
:
1198 printNicely(light_magenta('Sorry I can\'s understand.'))
1201 def help_discover():
1206 # Discover the world
1208 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1209 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1210 'You can try ' + light_green('trend US') + ' or ' + \
1211 light_green('trend JP Tokyo') + '.\n'
1212 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1213 light_green('home 7') + ' will show 7 tweets.\n'
1214 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1215 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1216 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1217 magenta('@mdo') + '.\n'
1218 usage
+= s
* 2 + light_green('view @mdo') + \
1219 ' will show ' + magenta('@mdo') + '\'s home.\n'
1220 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1221 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1222 'Search can be performed with or without hashtag.\n'
1233 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1234 usage
+= s
* 2 + light_green('t oops ') + \
1235 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1237 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1238 light_yellow('[id=12]') + '.\n'
1240 light_green('quote 12 ') + ' will quote the tweet with ' + \
1241 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1242 'the quote will be canceled.\n'
1244 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1245 light_yellow('[id=12]') + '.\n'
1246 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1247 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1248 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1249 light_yellow('oops') + '" to tweet with ' + \
1250 light_yellow('[id=12]') + '.\n'
1252 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1253 light_yellow('[id=12]') + '.\n'
1255 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1256 light_yellow('[id=12]') + '.\n'
1258 light_green('del 12 ') + ' will delete tweet with ' + \
1259 light_yellow('[id=12]') + '.\n'
1260 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1261 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1262 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1263 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1267 def help_messages():
1274 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1275 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1276 light_green('inbox 7') + ' will show newest 7 messages.\n'
1277 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1278 light_green('sent 7') + ' will show newest 7 messages.\n'
1279 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1280 magenta('@dtvd88') + '.\n'
1281 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1282 light_yellow('[message_id=5]') + '.\n'
1286 def help_friends_and_followers():
1288 Friends and Followers
1291 # Follower and following
1293 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1295 light_green('ls fl') + \
1296 ' will list all followers (people who are following you).\n'
1298 light_green('ls fr') + \
1299 ' will list all friends (people who you are following).\n'
1300 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1301 magenta('@dtvd88') + '.\n'
1302 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1303 magenta('@dtvd88') + '.\n'
1304 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1305 magenta('@dtvd88') + '.\n'
1306 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1307 magenta('@dtvd88') + '.\n'
1308 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1309 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1310 magenta('@dtvd88') + '.\n'
1311 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1312 magenta('@dtvd88') + '.\n'
1313 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1314 magenta('@dtvd88') + ' as a spam account.\n'
1325 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1326 usage
+= s
* 2 + light_green('list') + \
1327 ' will show all lists you are belong to.\n'
1328 usage
+= s
* 2 + light_green('list home') + \
1329 ' will show timeline of list. You will be asked for list\'s name.\n'
1330 usage
+= s
* 2 + light_green('list all_mem') + \
1331 ' will show list\'s all members.\n'
1332 usage
+= s
* 2 + light_green('list all_sub') + \
1333 ' will show list\'s all subscribers.\n'
1334 usage
+= s
* 2 + light_green('list add') + \
1335 ' will add specific person to a list owned by you.' + \
1336 ' You will be asked for list\'s name and person\'s name.\n'
1337 usage
+= s
* 2 + light_green('list rm') + \
1338 ' will remove specific person from a list owned by you.' + \
1339 ' You will be asked for list\'s name and person\'s name.\n'
1340 usage
+= s
* 2 + light_green('list sub') + \
1341 ' will subscribe you to a specific list.\n'
1342 usage
+= s
* 2 + light_green('list unsub') + \
1343 ' will unsubscribe you from a specific list.\n'
1344 usage
+= s
* 2 + light_green('list own') + \
1345 ' will show all list owned by you.\n'
1346 usage
+= s
* 2 + light_green('list new') + \
1347 ' will create a new list.\n'
1348 usage
+= s
* 2 + light_green('list update') + \
1349 ' will update a list owned by you.\n'
1350 usage
+= s
* 2 + light_green('list del') + \
1351 ' will delete a list owned by you.\n'
1362 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1363 usage
+= s
* 2 + light_green('switch public #AKB') + \
1364 ' will switch to public stream and follow "' + \
1365 light_yellow('AKB') + '" keyword.\n'
1366 usage
+= s
* 2 + light_green('switch mine') + \
1367 ' will switch to your personal stream.\n'
1368 usage
+= s
* 2 + light_green('switch mine -f ') + \
1369 ' will prompt to enter the filter.\n'
1370 usage
+= s
* 3 + light_yellow('Only nicks') + \
1371 ' filter will decide nicks will be INCLUDE ONLY.\n'
1372 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1373 ' filter will decide nicks will be EXCLUDE.\n'
1374 usage
+= s
* 2 + light_green('switch mine -d') + \
1375 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1384 h
, w
= os
.popen('stty size', 'r').read().split()
1387 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1388 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1389 usage
+= s
+ 'You are ' + \
1390 light_yellow('already') + ' on your personal stream.\n'
1391 usage
+= s
+ 'Any update from Twitter will show up ' + \
1392 light_yellow('immediately') + '.\n'
1393 usage
+= s
+ 'In addition, following commands are available right now:\n'
1394 # Twitter help section
1396 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1397 usage
+= s
* 2 + light_green('h discover') + \
1398 ' will show help for discover commands.\n'
1399 usage
+= s
* 2 + light_green('h tweets') + \
1400 ' will show help for tweets commands.\n'
1401 usage
+= s
* 2 + light_green('h messages') + \
1402 ' will show help for messages commands.\n'
1403 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1404 ' will show help for friends and followers commands.\n'
1405 usage
+= s
* 2 + light_green('h list') + \
1406 ' will show help for list commands.\n'
1407 usage
+= s
* 2 + light_green('h stream') + \
1408 ' will show help for stream commands.\n'
1411 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1412 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1413 'will be evaluate by Python interpreter.\n'
1414 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1415 ' for current month.\n'
1418 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1419 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1420 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1421 ' theme immediately.\n'
1422 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1424 light_green('config ASCII_ART') + ' will output current value of ' +\
1425 light_yellow('ASCII_ART') + ' config key.\n'
1427 light_green('config TREND_MAX default') + ' will output default value of ' + \
1428 light_yellow('TREND_MAX') + ' config key.\n'
1430 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1431 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1433 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1434 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1435 light_yellow('True') + '.\n'
1438 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1439 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1440 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1441 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1442 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1443 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1446 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1447 usage
+= s
+ 'Have fun and hang tight! \n'
1450 'discover': help_discover
,
1451 'tweets': help_tweets
,
1452 'messages': help_messages
,
1453 'friends_and_followers': help_friends_and_followers
,
1455 'stream': help_stream
,
1460 lambda: printNicely(red('No such command.'))
1468 Pause stream display
1471 printNicely(green('Stream is paused'))
1479 printNicely(green('Stream is running back now'))
1495 printNicely(green('See you next time :)'))
1503 Reset prefix of line
1506 if c
.get('USER_JSON_ERROR'):
1507 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1508 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1510 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1513 printNicely(str(eval(g
['cmd'])))
1562 # Handle function set
1611 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1616 Listen to user's input
1621 ['public', 'mine'], # switch
1637 ['image'], # show image
1639 ['fl', 'fr'], # list
1641 [i
for i
in g
['message_threads']], #sent
1666 [key
for key
in dict(get_all_config())], # config
1667 g
['themes'], # theme
1672 'friends_and_followers',
1682 init_interactive_shell(d
)
1689 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1692 # Save cmd to compare with readline buffer
1693 g
['cmd'] = line
.strip()
1694 # Get short cmd to pass to handle function
1696 cmd
= line
.split()[0]
1699 # Lock the semaphore
1701 # Save cmd to global variable and call process
1702 g
['stuff'] = ' '.join(line
.split()[1:])
1703 # Process the command
1706 if cmd
in ['switch', 't', 'rt', 'rep']:
1710 # Release the semaphore lock
1715 printNicely(red('OMG something is wrong with Twitter right now.'))
1718 def stream(domain
, args
, name
='Rainbow Stream'):
1724 c
['USER_DOMAIN']: name
,
1725 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1726 c
['SITE_DOMAIN']: name
,
1729 ascii_art(art_dict
[domain
])
1730 # These arguments are optional:
1732 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1734 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1737 if args
.track_keywords
:
1738 query_args
['track'] = args
.track_keywords
1740 stream
= TwitterStream(
1745 if domain
== c
['USER_DOMAIN']:
1746 tweet_iter
= stream
.user(**query_args
)
1747 elif domain
== c
['SITE_DOMAIN']:
1748 tweet_iter
= stream
.site(**query_args
)
1750 if args
.track_keywords
:
1751 tweet_iter
= stream
.statuses
.filter(**query_args
)
1753 tweet_iter
= stream
.statuses
.sample()
1754 # Block new stream until other one exits
1755 StreamLock
.acquire()
1756 g
['stream_stop'] = False
1757 for tweet
in tweet_iter
:
1759 printNicely("-- None --")
1760 elif tweet
is Timeout
:
1761 if(g
['stream_stop']):
1762 StreamLock
.release()
1764 elif tweet
is HeartbeatTimeout
:
1765 printNicely("-- Heartbeat Timeout --")
1766 guide
= light_magenta("You can use ") + \
1767 light_green("switch") + \
1768 light_magenta(" command to return to your stream.\n")
1769 guide
+= light_magenta("Type ") + \
1770 light_green("h stream") + \
1771 light_magenta(" for more details.")
1773 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1775 StreamLock
.release()
1777 elif tweet
is Hangup
:
1778 printNicely("-- Hangup --")
1779 elif tweet
.get('text'):
1780 # Check the semaphore pause and lock (stream process only)
1788 keyword
=args
.track_keywords
,
1793 # Current readline buffer
1794 current_buffer
= readline
.get_line_buffer().strip()
1795 # There is an unexpected behaviour in MacOSX readline + Python 2:
1796 # after completely delete a word after typing it,
1797 # somehow readline buffer still contains
1798 # the 1st character of that word
1799 if current_buffer
and g
['cmd'] != current_buffer
:
1801 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1803 elif not c
['HIDE_PROMPT']:
1804 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1806 elif tweet
.get('direct_message'):
1807 # Check the semaphore pause and lock (stream process only)
1812 print_message(tweet
['direct_message'])
1813 except TwitterHTTPError
:
1816 magenta("We have maximum connection problem with twitter'stream API right now :("))
1824 args
= parse_arguments()
1827 except TwitterHTTPError
:
1830 magenta("We have connection problem with twitter'stream API right now :("))
1831 printNicely(magenta("Let's try again later."))
1834 # Spawn stream thread
1835 th
= threading
.Thread(
1840 g
['original_name']))
1843 # Start listen process