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 c
['original_name'] = 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
)
464 link_prefix
= ('http://', 'https://')
465 link_ary
= [u
for u
in tweet
['text'].split()
466 if u
.startswith(link_prefix
)]
468 printNicely(light_magenta('No url here @.@!'))
470 for link
in link_ary
:
471 webbrowser
.open(link
)
473 printNicely(red('Sorry I can\'t open url in this tweet.'))
480 t
= Twitter(auth
=authen())
481 num
= c
['MESSAGES_DISPLAY']
482 if g
['stuff'].isdigit():
488 inbox
= inbox
+ t
.direct_messages(
491 include_entities
=False,
496 inbox
= inbox
+ t
.direct_messages(
499 include_entities
=False,
503 num
= c
['MESSAGES_DISPLAY']
504 if g
['stuff'].isdigit():
509 sent
= sent
+ t
.direct_messages
.sent(
512 include_entities
=False,
517 sent
= sent
+ t
.direct_messages
.sent(
520 include_entities
=False,
525 uniq_inbox
= list(set(
526 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
528 uniq_sent
= list(set(
529 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
531 for partner
in uniq_inbox
:
532 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
534 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
535 d
[partner
] = inbox_ary
+ sent_ary
536 for partner
in uniq_sent
:
539 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
540 g
['message_threads'] = print_threads(d
)
545 View a thread of message
548 thread_id
= int(g
['stuff'])
550 g
['message_threads'][thread_id
],
554 printNicely(red('No such thread.'))
559 Send a direct message
561 t
= Twitter(auth
=authen())
563 user
= g
['stuff'].split()[0]
564 if user
[0].startswith('@'):
565 content
= ' '.join(g
['stuff'].split()[1:])
566 t
.direct_messages
.new(
567 screen_name
=user
[1:],
570 printNicely(green('Message sent.'))
572 printNicely(red('A name should begin with a \'@\''))
574 printNicely(red('Sorry I can\'t understand.'))
581 t
= Twitter(auth
=authen())
583 id = int(g
['stuff'].split()[0])
585 printNicely(red('Sorry I can\'t understand.'))
586 mid
= c
['message_dict'][id]
587 t
.direct_messages
.destroy(id=mid
)
588 printNicely(green('Message deleted.'))
593 List friends for followers
595 t
= Twitter(auth
=authen())
598 name
= g
['stuff'].split()[1]
599 if name
.startswith('@'):
602 printNicely(red('A name should begin with a \'@\''))
603 raise Exception('Invalid name')
605 name
= g
['original_name']
606 # Get list followers or friends
608 target
= g
['stuff'].split()[0]
610 printNicely(red('Omg some syntax is wrong.'))
612 d
= {'fl': 'followers', 'fr': 'friends'}
616 while next_cursor
!= 0:
617 list = getattr(t
, d
[target
]).list(
621 include_entities
=False,
623 for u
in list['users']:
624 rel
[u
['name']] = '@' + u
['screen_name']
625 next_cursor
= list['next_cursor']
627 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
629 user
= ' ' + cycle_color(name
)
630 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
638 t
= Twitter(auth
=authen())
639 screen_name
= g
['stuff'].split()[0]
640 if screen_name
.startswith('@'):
641 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
642 printNicely(green('You are following ' + screen_name
+ ' now!'))
644 printNicely(red('A name should begin with a \'@\''))
651 t
= Twitter(auth
=authen())
652 screen_name
= g
['stuff'].split()[0]
653 if screen_name
.startswith('@'):
654 t
.friendships
.destroy(
655 screen_name
=screen_name
[1:],
656 include_entities
=False)
657 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
659 printNicely(red('A name should begin with a \'@\''))
666 t
= Twitter(auth
=authen())
668 screen_name
= g
['stuff'].split()[0]
670 printNicely(red('A name should be specified. '))
672 if screen_name
.startswith('@'):
674 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
675 if isinstance(rel
, dict):
676 printNicely(green(screen_name
+ ' is muted.'))
677 c
['IGNORE_LIST'] += [unc(screen_name
)]
678 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
680 printNicely(red(rel
))
682 printNicely(red('Something is wrong, can not mute now :('))
684 printNicely(red('A name should begin with a \'@\''))
691 t
= Twitter(auth
=authen())
693 screen_name
= g
['stuff'].split()[0]
695 printNicely(red('A name should be specified. '))
697 if screen_name
.startswith('@'):
699 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
700 if isinstance(rel
, dict):
701 printNicely(green(screen_name
+ ' is unmuted.'))
702 c
['IGNORE_LIST'].remove(screen_name
)
704 printNicely(red(rel
))
706 printNicely(red('Maybe you are not muting this person ?'))
708 printNicely(red('A name should begin with a \'@\''))
715 # Get dict of muting users
716 md
= build_mute_dict(dict_data
=True)
717 printNicely('All: ' + str(len(md
)) + ' people.')
719 user
= ' ' + cycle_color(md
[name
])
720 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
722 # Update from Twitter
723 c
['IGNORE_LIST'] = [n
for n
in md
]
730 t
= Twitter(auth
=authen())
731 screen_name
= g
['stuff'].split()[0]
732 if screen_name
.startswith('@'):
734 screen_name
=screen_name
[1:],
735 include_entities
=False,
737 printNicely(green('You blocked ' + screen_name
+ '.'))
739 printNicely(red('A name should begin with a \'@\''))
746 t
= Twitter(auth
=authen())
747 screen_name
= g
['stuff'].split()[0]
748 if screen_name
.startswith('@'):
750 screen_name
=screen_name
[1:],
751 include_entities
=False,
753 printNicely(green('Unblock ' + screen_name
+ ' success!'))
755 printNicely(red('A name should begin with a \'@\''))
760 Report a user as a spam account
762 t
= Twitter(auth
=authen())
763 screen_name
= g
['stuff'].split()[0]
764 if screen_name
.startswith('@'):
766 screen_name
=screen_name
[1:])
767 printNicely(green('You reported ' + screen_name
+ '.'))
769 printNicely(red('Sorry I can\'t understand.'))
777 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
778 # Get list name and owner
780 owner
, slug
= list_name
.split('/')
781 if slug
.startswith('@'):
786 light_magenta('List name should follow "@owner/list_name" format.'))
787 raise Exception('Wrong list name')
794 rel
= t
.lists
.list(screen_name
=g
['original_name'])
798 printNicely(light_magenta('You belong to no lists :)'))
805 owner
, slug
= get_slug()
806 res
= t
.lists
.statuses(
808 owner_screen_name
=owner
,
810 include_entities
=False)
820 owner
, slug
= get_slug()
824 while next_cursor
!= 0:
827 owner_screen_name
=owner
,
829 include_entities
=False)
831 rel
[u
['name']] = '@' + u
['screen_name']
832 next_cursor
= m
['next_cursor']
833 printNicely('All: ' + str(len(rel
)) + ' members.')
835 user
= ' ' + cycle_color(name
)
836 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
840 def list_subscribers(t
):
844 owner
, slug
= get_slug()
848 while next_cursor
!= 0:
849 m
= t
.lists
.subscribers(
851 owner_screen_name
=owner
,
853 include_entities
=False)
855 rel
[u
['name']] = '@' + u
['screen_name']
856 next_cursor
= m
['next_cursor']
857 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
859 user
= ' ' + cycle_color(name
)
860 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
866 Add specific user to a list
868 owner
, slug
= get_slug()
870 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
871 if user_name
.startswith('@'):
872 user_name
= user_name
[1:]
874 t
.lists
.members
.create(
876 owner_screen_name
=owner
,
877 screen_name
=user_name
)
878 printNicely(green('Added.'))
880 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
885 Remove specific user from a list
887 owner
, slug
= get_slug()
889 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
890 if user_name
.startswith('@'):
891 user_name
= user_name
[1:]
893 t
.lists
.members
.destroy(
895 owner_screen_name
=owner
,
896 screen_name
=user_name
)
897 printNicely(green('Gone.'))
899 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
902 def list_subscribe(t
):
906 owner
, slug
= get_slug()
909 t
.lists
.subscribers
.create(
911 owner_screen_name
=owner
)
912 printNicely(green('Done.'))
915 light_magenta('I\'m sorry you can not subscribe to this list.'))
918 def list_unsubscribe(t
):
922 owner
, slug
= get_slug()
925 t
.lists
.subscribers
.destroy(
927 owner_screen_name
=owner
)
928 printNicely(green('Done.'))
931 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
940 while next_cursor
!= 0:
941 res
= t
.lists
.ownerships(
942 screen_name
=g
['original_name'],
945 next_cursor
= res
['next_cursor']
949 printNicely(light_magenta('You own no lists :)'))
956 name
= raw_input(light_magenta('New list\'s name: '))
957 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
958 description
= raw_input(light_magenta('New list\'s description: '))
963 description
=description
)
964 printNicely(green(name
+ ' list is created.'))
966 printNicely(red('Oops something is wrong with Twitter :('))
973 slug
= raw_input(light_magenta('Your list that you want to update: '))
974 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
975 mode
= raw_input(light_magenta('Update mode (public/private): '))
976 description
= raw_input(light_magenta('Update description: '))
980 slug
='-'.join(slug
.split()),
981 owner_screen_name
=g
['original_name'],
984 description
=description
)
988 owner_screen_name
=g
['original_name'],
990 description
=description
)
991 printNicely(green(slug
+ ' list is updated.'))
993 printNicely(red('Oops something is wrong with Twitter :('))
1000 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1003 slug
='-'.join(slug
.split()),
1004 owner_screen_name
=g
['original_name'])
1005 printNicely(green(slug
+ ' list is deleted.'))
1007 printNicely(red('Oops something is wrong with Twitter :('))
1014 t
= Twitter(auth
=authen())
1015 # List all lists or base on action
1017 g
['list_action'] = g
['stuff'].split()[0]
1024 'all_mem': list_members
,
1025 'all_sub': list_subscribers
,
1028 'sub': list_subscribe
,
1029 'unsub': list_unsubscribe
,
1032 'update': list_update
,
1036 return action_ary
[g
['list_action']](t
)
1038 printNicely(red('Please try again.'))
1046 target
= g
['stuff'].split()[0]
1048 args
= parse_arguments()
1050 if g
['stuff'].split()[-1] == '-f':
1051 guide
= 'To ignore an option, just hit Enter key.'
1052 printNicely(light_magenta(guide
))
1053 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1054 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1055 args
.filter = filter(None, only
.split(','))
1056 args
.ignore
= filter(None, ignore
.split(','))
1057 elif g
['stuff'].split()[-1] == '-d':
1058 args
.filter = c
['ONLY_LIST']
1059 args
.ignore
= c
['IGNORE_LIST']
1061 printNicely(red('Sorry, wrong format.'))
1064 if target
== 'public':
1065 keyword
= g
['stuff'].split()[1]
1066 if keyword
[0] == '#':
1067 keyword
= keyword
[1:]
1069 g
['stream_stop'] = True
1070 args
.track_keywords
= keyword
1072 th
= threading
.Thread(
1080 elif target
== 'mine':
1082 g
['stream_stop'] = True
1084 th
= threading
.Thread(
1089 g
['original_name']))
1094 printNicely(cyan('Only: ' + str(args
.filter)))
1096 printNicely(red('Ignore: ' + str(args
.ignore
)))
1099 printNicely(red('Sorry I can\'t understand.'))
1104 Unix's command `cal`
1107 rel
= os
.popen('cal').read().split('\n')
1110 show_calendar(month
, date
, rel
)
1115 List and change theme
1119 for theme
in g
['themes']:
1120 line
= light_magenta(theme
)
1121 if c
['THEME'] == theme
:
1122 line
= ' ' * 2 + light_yellow('* ') + line
1124 line
= ' ' * 4 + line
1130 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1131 # Redefine decorated_name
1132 g
['decorated_name'] = lambda x
: color_func(
1133 c
['DECORATED_NAME'])(
1135 printNicely(green('Theme changed.'))
1137 printNicely(red('No such theme exists.'))
1142 Browse and change config
1144 all_config
= get_all_config()
1145 g
['stuff'] = g
['stuff'].strip()
1148 for k
in all_config
:
1150 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1152 guide
= 'Detailed explanation can be found at ' + \
1153 color_func(c
['TWEET']['link'])(
1154 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1156 # Print specific config
1157 elif len(g
['stuff'].split()) == 1:
1158 if g
['stuff'] in all_config
:
1161 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1164 printNicely(red('No such config key.'))
1165 # Print specific config's default value
1166 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1167 key
= g
['stuff'].split()[0]
1169 value
= get_default_config(key
)
1170 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1172 except Exception as e
:
1174 # Delete specific config key in config file
1175 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1176 key
= g
['stuff'].split()[0]
1179 printNicely(green('Config key is dropped.'))
1180 except Exception as e
:
1182 # Set specific config
1183 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1184 key
= g
['stuff'].split()[0]
1185 value
= g
['stuff'].split()[-1]
1186 if key
== 'THEME' and not validate_theme(value
):
1187 printNicely(red('Invalid theme\'s value.'))
1190 set_config(key
, value
)
1191 # Apply theme immediately
1193 c
['THEME'] = reload_theme(value
, c
['THEME'])
1194 g
['decorated_name'] = lambda x
: color_func(
1195 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1197 printNicely(green('Updated successfully.'))
1198 except Exception as e
:
1201 printNicely(light_magenta('Sorry I can\'s understand.'))
1204 def help_discover():
1209 # Discover the world
1211 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1212 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1213 'You can try ' + light_green('trend US') + ' or ' + \
1214 light_green('trend JP Tokyo') + '.\n'
1215 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1216 light_green('home 7') + ' will show 7 tweets.\n'
1217 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1218 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1219 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1220 magenta('@mdo') + '.\n'
1221 usage
+= s
* 2 + light_green('view @mdo') + \
1222 ' will show ' + magenta('@mdo') + '\'s home.\n'
1223 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1224 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1225 'Search can be performed with or without hashtag.\n'
1236 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1237 usage
+= s
* 2 + light_green('t oops ') + \
1238 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1240 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1241 light_yellow('[id=12]') + '.\n'
1243 light_green('quote 12 ') + ' will quote the tweet with ' + \
1244 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1245 'the quote will be canceled.\n'
1247 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1248 light_yellow('[id=12]') + '.\n'
1249 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1250 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1251 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1252 light_yellow('oops') + '" to tweet with ' + \
1253 light_yellow('[id=12]') + '.\n'
1255 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1256 light_yellow('[id=12]') + '.\n'
1258 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1259 light_yellow('[id=12]') + '.\n'
1261 light_green('del 12 ') + ' will delete tweet with ' + \
1262 light_yellow('[id=12]') + '.\n'
1263 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1264 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1265 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1266 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1270 def help_messages():
1277 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1278 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1279 light_green('inbox 7') + ' will show newest 7 messages.\n'
1280 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1281 light_yellow('[thread_id=2]') + '.\n'
1282 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1283 magenta('@dtvd88') + '.\n'
1284 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1285 light_yellow('[message_id=5]') + '.\n'
1289 def help_friends_and_followers():
1291 Friends and Followers
1294 # Follower and following
1296 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1298 light_green('ls fl') + \
1299 ' will list all followers (people who are following you).\n'
1301 light_green('ls fr') + \
1302 ' will list all friends (people who you are following).\n'
1303 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1304 magenta('@dtvd88') + '.\n'
1305 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1306 magenta('@dtvd88') + '.\n'
1307 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1308 magenta('@dtvd88') + '.\n'
1309 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1310 magenta('@dtvd88') + '.\n'
1311 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1312 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1313 magenta('@dtvd88') + '.\n'
1314 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1315 magenta('@dtvd88') + '.\n'
1316 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1317 magenta('@dtvd88') + ' as a spam account.\n'
1328 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1329 usage
+= s
* 2 + light_green('list') + \
1330 ' will show all lists you are belong to.\n'
1331 usage
+= s
* 2 + light_green('list home') + \
1332 ' will show timeline of list. You will be asked for list\'s name.\n'
1333 usage
+= s
* 2 + light_green('list all_mem') + \
1334 ' will show list\'s all members.\n'
1335 usage
+= s
* 2 + light_green('list all_sub') + \
1336 ' will show list\'s all subscribers.\n'
1337 usage
+= s
* 2 + light_green('list add') + \
1338 ' will add specific person to 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 rm') + \
1341 ' will remove specific person from a list owned by you.' + \
1342 ' You will be asked for list\'s name and person\'s name.\n'
1343 usage
+= s
* 2 + light_green('list sub') + \
1344 ' will subscribe you to a specific list.\n'
1345 usage
+= s
* 2 + light_green('list unsub') + \
1346 ' will unsubscribe you from a specific list.\n'
1347 usage
+= s
* 2 + light_green('list own') + \
1348 ' will show all list owned by you.\n'
1349 usage
+= s
* 2 + light_green('list new') + \
1350 ' will create a new list.\n'
1351 usage
+= s
* 2 + light_green('list update') + \
1352 ' will update a list owned by you.\n'
1353 usage
+= s
* 2 + light_green('list del') + \
1354 ' will delete a list owned by you.\n'
1365 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1366 usage
+= s
* 2 + light_green('switch public #AKB') + \
1367 ' will switch to public stream and follow "' + \
1368 light_yellow('AKB') + '" keyword.\n'
1369 usage
+= s
* 2 + light_green('switch mine') + \
1370 ' will switch to your personal stream.\n'
1371 usage
+= s
* 2 + light_green('switch mine -f ') + \
1372 ' will prompt to enter the filter.\n'
1373 usage
+= s
* 3 + light_yellow('Only nicks') + \
1374 ' filter will decide nicks will be INCLUDE ONLY.\n'
1375 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1376 ' filter will decide nicks will be EXCLUDE.\n'
1377 usage
+= s
* 2 + light_green('switch mine -d') + \
1378 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1387 h
, w
= os
.popen('stty size', 'r').read().split()
1390 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1391 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1392 usage
+= s
+ 'You are ' + \
1393 light_yellow('already') + ' on your personal stream.\n'
1394 usage
+= s
+ 'Any update from Twitter will show up ' + \
1395 light_yellow('immediately') + '.\n'
1396 usage
+= s
+ 'In addition, following commands are available right now:\n'
1397 # Twitter help section
1399 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1400 usage
+= s
* 2 + light_green('h discover') + \
1401 ' will show help for discover commands.\n'
1402 usage
+= s
* 2 + light_green('h tweets') + \
1403 ' will show help for tweets commands.\n'
1404 usage
+= s
* 2 + light_green('h messages') + \
1405 ' will show help for messages commands.\n'
1406 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1407 ' will show help for friends and followers commands.\n'
1408 usage
+= s
* 2 + light_green('h list') + \
1409 ' will show help for list commands.\n'
1410 usage
+= s
* 2 + light_green('h stream') + \
1411 ' will show help for stream commands.\n'
1414 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1415 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1416 'will be evaluate by Python interpreter.\n'
1417 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1418 ' for current month.\n'
1421 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1422 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1423 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1424 ' theme immediately.\n'
1425 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1427 light_green('config ASCII_ART') + ' will output current value of ' +\
1428 light_yellow('ASCII_ART') + ' config key.\n'
1430 light_green('config TREND_MAX default') + ' will output default value of ' + \
1431 light_yellow('TREND_MAX') + ' config key.\n'
1433 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1434 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1436 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1437 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1438 light_yellow('True') + '.\n'
1441 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1442 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1443 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1444 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1445 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1446 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1449 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1450 usage
+= s
+ 'Have fun and hang tight! \n'
1453 'discover': help_discover
,
1454 'tweets': help_tweets
,
1455 'messages': help_messages
,
1456 'friends_and_followers': help_friends_and_followers
,
1458 'stream': help_stream
,
1463 lambda: printNicely(red('No such command.'))
1471 Pause stream display
1474 printNicely(green('Stream is paused'))
1482 printNicely(green('Stream is running back now'))
1498 printNicely(green('See you next time :)'))
1506 Reset prefix of line
1509 if c
.get('USER_JSON_ERROR'):
1510 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1511 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1513 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1516 printNicely(str(eval(g
['cmd'])))
1565 # Handle function set
1614 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1619 Listen to user's input
1624 ['public', 'mine'], # switch
1640 ['image'], # show image
1642 ['fl', 'fr'], # list
1644 [i
for i
in g
['message_threads']], # sent
1669 [key
for key
in dict(get_all_config())], # config
1670 g
['themes'], # theme
1675 'friends_and_followers',
1685 init_interactive_shell(d
)
1692 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1695 # Save cmd to compare with readline buffer
1696 g
['cmd'] = line
.strip()
1697 # Get short cmd to pass to handle function
1699 cmd
= line
.split()[0]
1702 # Lock the semaphore
1704 # Save cmd to global variable and call process
1705 g
['stuff'] = ' '.join(line
.split()[1:])
1706 # Process the command
1709 if cmd
in ['switch', 't', 'rt', 'rep']:
1713 # Release the semaphore lock
1718 printNicely(red('OMG something is wrong with Twitter right now.'))
1721 def stream(domain
, args
, name
='Rainbow Stream'):
1727 c
['USER_DOMAIN']: name
,
1728 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1729 c
['SITE_DOMAIN']: name
,
1732 ascii_art(art_dict
[domain
])
1733 # These arguments are optional:
1735 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1737 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1740 if args
.track_keywords
:
1741 query_args
['track'] = args
.track_keywords
1743 stream
= TwitterStream(
1748 if domain
== c
['USER_DOMAIN']:
1749 tweet_iter
= stream
.user(**query_args
)
1750 elif domain
== c
['SITE_DOMAIN']:
1751 tweet_iter
= stream
.site(**query_args
)
1753 if args
.track_keywords
:
1754 tweet_iter
= stream
.statuses
.filter(**query_args
)
1756 tweet_iter
= stream
.statuses
.sample()
1757 # Block new stream until other one exits
1758 StreamLock
.acquire()
1759 g
['stream_stop'] = False
1760 for tweet
in tweet_iter
:
1762 printNicely("-- None --")
1763 elif tweet
is Timeout
:
1764 if(g
['stream_stop']):
1765 StreamLock
.release()
1767 elif tweet
is HeartbeatTimeout
:
1768 printNicely("-- Heartbeat Timeout --")
1769 guide
= light_magenta("You can use ") + \
1770 light_green("switch") + \
1771 light_magenta(" command to return to your stream.\n")
1772 guide
+= light_magenta("Type ") + \
1773 light_green("h stream") + \
1774 light_magenta(" for more details.")
1776 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1778 StreamLock
.release()
1780 elif tweet
is Hangup
:
1781 printNicely("-- Hangup --")
1782 elif tweet
.get('text'):
1783 # Check the semaphore pause and lock (stream process only)
1791 keyword
=args
.track_keywords
,
1796 # Current readline buffer
1797 current_buffer
= readline
.get_line_buffer().strip()
1798 # There is an unexpected behaviour in MacOSX readline + Python 2:
1799 # after completely delete a word after typing it,
1800 # somehow readline buffer still contains
1801 # the 1st character of that word
1802 if current_buffer
and g
['cmd'] != current_buffer
:
1804 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1806 elif not c
['HIDE_PROMPT']:
1807 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1809 elif tweet
.get('direct_message'):
1810 # Check the semaphore pause and lock (stream process only)
1815 print_message(tweet
['direct_message'])
1816 except TwitterHTTPError
:
1819 magenta("We have maximum connection problem with twitter'stream API right now :("))
1827 args
= parse_arguments()
1830 except TwitterHTTPError
:
1833 magenta("We have connection problem with twitter'stream API right now :("))
1834 printNicely(magenta("Let's try again later."))
1837 # Spawn stream thread
1838 th
= threading
.Thread(
1843 g
['original_name']))
1846 # Start listen process