2 Colorful user's timeline stream
14 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
15 from twitter
.api
import *
16 from twitter
.oauth
import OAuth
, read_token_file
17 from twitter
.oauth_dance
import oauth_dance
18 from twitter
.util
import printNicely
23 from .consumer
import *
24 from .interactive
import *
25 from .c_image
import *
26 from .py3patch
import *
32 StreamLock
= threading
.Lock()
35 def parse_arguments():
39 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
43 help='Timeout for the stream (seconds).')
47 help='Search the stream for specific text.')
51 help='Filter specific screen_name.')
55 help='Ignore specific screen_name.')
60 help='Display all image on terminal.')
61 return parser
.parse_args()
66 Authenticate with Twitter OAuth
68 # When using rainbow stream you must authorize.
69 twitter_credential
= os
.environ
.get(
73 '')) + os
.sep
+ '.rainbow_oauth'
74 if not os
.path
.exists(twitter_credential
):
75 oauth_dance("Rainbow Stream",
79 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
87 def build_mute_dict(dict_data
=False):
91 t
= Twitter(auth
=authen())
97 while next_cursor
!= 0:
98 list = t
.mutes
.users
.list(
99 screen_name
=g
['original_name'],
102 include_entities
=False,
104 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
105 name_list
+= [u
['name'] for u
in list['users']]
106 next_cursor
= list['next_cursor']
107 # Return dict or list
109 return dict(zip(screen_name_list
, name_list
))
111 return screen_name_list
119 ctrl_c_handler
= lambda signum
, frame
: quit()
120 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
122 t
= Twitter(auth
=authen())
123 name
= '@' + t
.account
.verify_credentials()['screen_name']
124 if not get_config('PREFIX'):
125 set_config('PREFIX', name
)
126 g
['original_name'] = name
[1:]
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']
138 # Init tweet dict and message dict
140 c
['message_dict'] = []
142 c
['IMAGE_ON_TERM'] = args
.image_on_term
143 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
145 c
['IGNORE_LIST'] += build_mute_dict()
153 target
= g
['stuff'].split()[0]
155 args
= parse_arguments()
157 if g
['stuff'].split()[-1] == '-f':
158 guide
= 'To ignore an option, just hit Enter key.'
159 printNicely(light_magenta(guide
))
160 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
161 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
162 args
.filter = filter(None, only
.split(','))
163 args
.ignore
= filter(None, ignore
.split(','))
164 elif g
['stuff'].split()[-1] == '-d':
165 args
.filter = c
['ONLY_LIST']
166 args
.ignore
= c
['IGNORE_LIST']
168 printNicely(red('Sorry, wrong format.'))
171 if target
== 'public':
172 keyword
= g
['stuff'].split()[1]
173 if keyword
[0] == '#':
174 keyword
= keyword
[1:]
176 g
['stream_stop'] = True
177 args
.track_keywords
= keyword
179 th
= threading
.Thread(
187 elif target
== 'mine':
189 g
['stream_stop'] = True
191 th
= threading
.Thread(
201 printNicely(cyan('Only: ' + str(args
.filter)))
203 printNicely(red('Ignore: ' + str(args
.ignore
)))
206 printNicely(red('Sorry I can\'t understand.'))
213 t
= Twitter(auth
=authen())
214 # Get country and town
216 country
= g
['stuff'].split()[0]
220 town
= g
['stuff'].split()[1]
223 avail
= t
.trends
.available()
226 trends
= t
.trends
.place(_id
=1)[0]['trends']
229 for location
in avail
:
230 # Search for country and Town
232 if location
['countryCode'] == country \
233 and location
['placeType']['name'] == 'Town' \
234 and location
['name'] == town
:
235 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
237 # Search for country only
239 if location
['countryCode'] == country \
240 and location
['placeType']['name'] == 'Country':
241 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
249 t
= Twitter(auth
=authen())
250 num
= c
['HOME_TWEET_NUM']
251 if g
['stuff'].isdigit():
252 num
= int(g
['stuff'])
253 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
262 t
= Twitter(auth
=authen())
263 user
= g
['stuff'].split()[0]
266 num
= int(g
['stuff'].split()[1])
268 num
= c
['HOME_TWEET_NUM']
269 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
273 printNicely(red('A name should begin with a \'@\''))
280 t
= Twitter(auth
=authen())
281 num
= c
['HOME_TWEET_NUM']
282 if g
['stuff'].isdigit():
283 num
= int(g
['stuff'])
284 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
293 t
= Twitter(auth
=authen())
295 id = int(g
['stuff'].split()[0])
297 printNicely(red('Sorry I can\'t understand.'))
299 tid
= c
['tweet_dict'][id]
300 tweet
= t
.statuses
.show(id=tid
)
303 thread_ref
.append (tweet
)
304 prev_tid
= tweet
['in_reply_to_status_id']
305 while prev_tid
and limit
:
307 tweet
= t
.statuses
.show(id=prev_tid
)
308 prev_tid
= tweet
['in_reply_to_status_id']
309 thread_ref
.append (tweet
)
311 for tweet
in reversed(thread_ref
):
320 t
= Twitter(auth
=authen())
321 t
.statuses
.update(status
=g
['stuff'])
328 t
= Twitter(auth
=authen())
330 id = int(g
['stuff'].split()[0])
332 printNicely(red('Sorry I can\'t understand.'))
334 tid
= c
['tweet_dict'][id]
335 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
343 t
= Twitter(auth
=authen())
345 id = int(g
['stuff'].split()[0])
347 printNicely(red('Sorry I can\'t understand.'))
349 tid
= c
['tweet_dict'][id]
350 tweet
= t
.statuses
.show(id=tid
)
352 formater
= format_quote(tweet
)
356 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
357 comment
= raw_input(prefix
)
359 quote
= comment
.join(formater
.split('#comment'))
360 t
.statuses
.update(status
=quote
)
362 printNicely(light_magenta('No text added.'))
369 t
= Twitter(auth
=authen())
372 id = int(g
['stuff'].split()[0])
374 printNicely(red('Sorry I can\'t understand.'))
376 tid
= c
['tweet_dict'][id]
377 # Get display num if exist
379 num
= int(g
['stuff'].split()[1])
381 num
= c
['RETWEETS_SHOW_NUM']
382 # Get result and display
383 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
385 printNicely(magenta('This tweet has no retweet.'))
387 for tweet
in reversed(rt_ary
):
396 t
= Twitter(auth
=authen())
398 id = int(g
['stuff'].split()[0])
400 printNicely(red('Sorry I can\'t understand.'))
402 tid
= c
['tweet_dict'][id]
403 t
.favorites
.create(_id
=tid
, include_entities
=False)
404 printNicely(green('Favorited.'))
405 draw(t
.statuses
.show(id=tid
))
413 t
= Twitter(auth
=authen())
415 id = int(g
['stuff'].split()[0])
417 printNicely(red('Sorry I can\'t understand.'))
419 tid
= c
['tweet_dict'][id]
420 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
421 status
= ' '.join(g
['stuff'].split()[1:])
422 status
= '@' + user
+ ' ' + str2u(status
)
423 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
430 t
= Twitter(auth
=authen())
432 id = int(g
['stuff'].split()[0])
434 printNicely(red('Sorry I can\'t understand.'))
436 tid
= c
['tweet_dict'][id]
437 t
.statuses
.destroy(id=tid
)
438 printNicely(green('Okay it\'s gone.'))
445 t
= Twitter(auth
=authen())
447 id = int(g
['stuff'].split()[0])
449 printNicely(red('Sorry I can\'t understand.'))
451 tid
= c
['tweet_dict'][id]
452 t
.favorites
.destroy(_id
=tid
)
453 printNicely(green('Okay it\'s unfavorited.'))
454 draw(t
.statuses
.show(id=tid
))
462 t
= Twitter(auth
=authen())
463 g
['stuff'] = g
['stuff'].strip()
464 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
466 printNicely('Newest tweets:')
467 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
472 printNicely(magenta('I\'m afraid there is no result'))
477 Send a direct message
479 t
= Twitter(auth
=authen())
480 user
= g
['stuff'].split()[0]
481 if user
[0].startswith('@'):
483 content
= g
['stuff'].split()[1]
485 printNicely(red('Sorry I can\'t understand.'))
486 t
.direct_messages
.new(
487 screen_name
=user
[1:],
490 printNicely(green('Message sent.'))
492 printNicely(red('A name should begin with a \'@\''))
499 t
= Twitter(auth
=authen())
501 target
= g
['stuff'].split()[0]
502 if target
!= 'image':
504 id = int(g
['stuff'].split()[1])
505 tid
= c
['tweet_dict'][id]
506 tweet
= t
.statuses
.show(id=tid
)
507 media
= tweet
['entities']['media']
509 res
= requests
.get(m
['media_url'])
510 img
= Image
.open(BytesIO(res
.content
))
513 printNicely(red('Sorry I can\'t show this image.'))
520 t
= Twitter(auth
=authen())
522 if not g
['stuff'].isdigit():
524 tid
= c
['tweet_dict'][int(g
['stuff'])]
525 tweet
= t
.statuses
.show(id=tid
)
527 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
529 printNicely(light_magenta('No url here @.@!'))
531 for link
in link_ary
:
532 webbrowser
.open(link
)
534 printNicely(red('Sorry I can\'t open url in this tweet.'))
539 List friends for followers
541 t
= Twitter(auth
=authen())
544 name
= g
['stuff'].split()[1]
545 if name
.startswith('@'):
548 printNicely(red('A name should begin with a \'@\''))
549 raise Exception('Invalid name')
551 name
= g
['original_name']
552 # Get list followers or friends
554 target
= g
['stuff'].split()[0]
556 printNicely(red('Omg some syntax is wrong.'))
558 d
= {'fl': 'followers', 'fr': 'friends'}
562 while next_cursor
!= 0:
563 list = getattr(t
, d
[target
]).list(
567 include_entities
=False,
569 for u
in list['users']:
570 rel
[u
['name']] = '@' + u
['screen_name']
571 next_cursor
= list['next_cursor']
573 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
575 user
= ' ' + cycle_color(name
)
576 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
582 Inbox direct messages
584 t
= Twitter(auth
=authen())
585 num
= c
['MESSAGES_DISPLAY']
587 if g
['stuff'].isdigit():
590 # Max message per page is 20 so we have to loop
592 rel
= rel
+ t
.direct_messages(
595 include_entities
=False,
600 rel
= rel
+ t
.direct_messages(
603 include_entities
=False,
607 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
608 for m
in reversed(rel
):
617 t
= Twitter(auth
=authen())
618 num
= c
['MESSAGES_DISPLAY']
620 if g
['stuff'].isdigit():
621 num
= int(g
['stuff'])
623 # Max message per page is 20 so we have to loop
625 rel
= rel
+ t
.direct_messages
.sent(
628 include_entities
=False,
633 rel
= rel
+ t
.direct_messages
.sent(
636 include_entities
=False,
640 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
641 for m
in reversed(rel
):
650 t
= Twitter(auth
=authen())
652 id = int(g
['stuff'].split()[0])
654 printNicely(red('Sorry I can\'t understand.'))
655 mid
= c
['message_dict'][id]
656 t
.direct_messages
.destroy(id=mid
)
657 printNicely(green('Message deleted.'))
662 Show profile of a specific user
664 t
= Twitter(auth
=authen())
665 screen_name
= g
['stuff'].split()[0]
666 if screen_name
.startswith('@'):
669 screen_name
=screen_name
[1:],
670 include_entities
=False)
673 printNicely(red('Omg no user.'))
675 printNicely(red('A name should begin with a \'@\''))
682 t
= Twitter(auth
=authen())
683 screen_name
= g
['stuff'].split()[0]
684 if screen_name
.startswith('@'):
685 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
686 printNicely(green('You are following ' + screen_name
+ ' now!'))
688 printNicely(red('A name should begin with a \'@\''))
695 t
= Twitter(auth
=authen())
696 screen_name
= g
['stuff'].split()[0]
697 if screen_name
.startswith('@'):
698 t
.friendships
.destroy(
699 screen_name
=screen_name
[1:],
700 include_entities
=False)
701 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
703 printNicely(red('A name should begin with a \'@\''))
710 t
= Twitter(auth
=authen())
712 screen_name
= g
['stuff'].split()[0]
714 printNicely(red('A name should be specified. '))
716 if screen_name
.startswith('@'):
718 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
719 if isinstance(rel
, dict):
720 printNicely(green(screen_name
+ ' is muted.'))
721 c
['IGNORE_LIST'] += [unc(screen_name
)]
722 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
724 printNicely(red(rel
))
726 printNicely(red('Something is wrong, can not mute now :('))
728 printNicely(red('A name should begin with a \'@\''))
735 t
= Twitter(auth
=authen())
737 screen_name
= g
['stuff'].split()[0]
739 printNicely(red('A name should be specified. '))
741 if screen_name
.startswith('@'):
743 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
744 if isinstance(rel
, dict):
745 printNicely(green(screen_name
+ ' is unmuted.'))
746 c
['IGNORE_LIST'].remove(screen_name
)
748 printNicely(red(rel
))
750 printNicely(red('Maybe you are not muting this person ?'))
752 printNicely(red('A name should begin with a \'@\''))
759 # Get dict of muting users
760 md
= build_mute_dict(dict_data
=True)
761 printNicely('All: ' + str(len(md
)) + ' people.')
763 user
= ' ' + cycle_color(md
[name
])
764 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
766 # Update from Twitter
767 c
['IGNORE_LIST'] = [n
for n
in md
]
774 t
= Twitter(auth
=authen())
775 screen_name
= g
['stuff'].split()[0]
776 if screen_name
.startswith('@'):
778 screen_name
=screen_name
[1:],
779 include_entities
=False,
781 printNicely(green('You blocked ' + screen_name
+ '.'))
783 printNicely(red('A name should begin with a \'@\''))
790 t
= Twitter(auth
=authen())
791 screen_name
= g
['stuff'].split()[0]
792 if screen_name
.startswith('@'):
794 screen_name
=screen_name
[1:],
795 include_entities
=False,
797 printNicely(green('Unblock ' + screen_name
+ ' success!'))
799 printNicely(red('A name should begin with a \'@\''))
804 Report a user as a spam account
806 t
= Twitter(auth
=authen())
807 screen_name
= g
['stuff'].split()[0]
808 if screen_name
.startswith('@'):
810 screen_name
=screen_name
[1:])
811 printNicely(green('You reported ' + screen_name
+ '.'))
813 printNicely(red('Sorry I can\'t understand.'))
821 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
822 # Get list name and owner
824 owner
, slug
= list_name
.split('/')
825 if slug
.startswith('@'):
830 light_magenta('List name should follow "@owner/list_name" format.'))
831 raise Exception('Wrong list name')
838 rel
= t
.lists
.list(screen_name
=g
['original_name'])
842 printNicely(light_magenta('You belong to no lists :)'))
849 owner
, slug
= get_slug()
850 res
= t
.lists
.statuses(
852 owner_screen_name
=owner
,
854 include_entities
=False)
864 owner
, slug
= get_slug()
868 while next_cursor
!= 0:
871 owner_screen_name
=owner
,
873 include_entities
=False)
875 rel
[u
['name']] = '@' + u
['screen_name']
876 next_cursor
= m
['next_cursor']
877 printNicely('All: ' + str(len(rel
)) + ' members.')
879 user
= ' ' + cycle_color(name
)
880 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
884 def list_subscribers(t
):
888 owner
, slug
= get_slug()
892 while next_cursor
!= 0:
893 m
= t
.lists
.subscribers(
895 owner_screen_name
=owner
,
897 include_entities
=False)
899 rel
[u
['name']] = '@' + u
['screen_name']
900 next_cursor
= m
['next_cursor']
901 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
903 user
= ' ' + cycle_color(name
)
904 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
910 Add specific user to a list
912 owner
, slug
= get_slug()
914 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
915 if user_name
.startswith('@'):
916 user_name
= user_name
[1:]
918 t
.lists
.members
.create(
920 owner_screen_name
=owner
,
921 screen_name
=user_name
)
922 printNicely(green('Added.'))
924 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
929 Remove specific user from a list
931 owner
, slug
= get_slug()
933 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
934 if user_name
.startswith('@'):
935 user_name
= user_name
[1:]
937 t
.lists
.members
.destroy(
939 owner_screen_name
=owner
,
940 screen_name
=user_name
)
941 printNicely(green('Gone.'))
943 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
946 def list_subscribe(t
):
950 owner
, slug
= get_slug()
953 t
.lists
.subscribers
.create(
955 owner_screen_name
=owner
)
956 printNicely(green('Done.'))
959 light_magenta('I\'m sorry you can not subscribe to this list.'))
962 def list_unsubscribe(t
):
966 owner
, slug
= get_slug()
969 t
.lists
.subscribers
.destroy(
971 owner_screen_name
=owner
)
972 printNicely(green('Done.'))
975 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
984 while next_cursor
!= 0:
985 res
= t
.lists
.ownerships(
986 screen_name
=g
['original_name'],
989 next_cursor
= res
['next_cursor']
993 printNicely(light_magenta('You own no lists :)'))
1000 name
= raw_input(light_magenta('New list\'s name: '))
1001 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1002 description
= raw_input(light_magenta('New list\'s description: '))
1007 description
=description
)
1008 printNicely(green(name
+ ' list is created.'))
1010 printNicely(red('Oops something is wrong with Twitter :('))
1017 slug
= raw_input(light_magenta('Your list that you want to update: '))
1018 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1019 mode
= raw_input(light_magenta('Update mode (public/private): '))
1020 description
= raw_input(light_magenta('Update description: '))
1024 slug
='-'.join(slug
.split()),
1025 owner_screen_name
=g
['original_name'],
1028 description
=description
)
1032 owner_screen_name
=g
['original_name'],
1034 description
=description
)
1035 printNicely(green(slug
+ ' list is updated.'))
1037 printNicely(red('Oops something is wrong with Twitter :('))
1044 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1047 slug
='-'.join(slug
.split()),
1048 owner_screen_name
=g
['original_name'])
1049 printNicely(green(slug
+ ' list is deleted.'))
1051 printNicely(red('Oops something is wrong with Twitter :('))
1058 t
= Twitter(auth
=authen())
1059 # List all lists or base on action
1061 g
['list_action'] = g
['stuff'].split()[0]
1068 'all_mem': list_members
,
1069 'all_sub': list_subscribers
,
1072 'sub': list_subscribe
,
1073 'unsub': list_unsubscribe
,
1076 'update': list_update
,
1080 return action_ary
[g
['list_action']](t
)
1082 printNicely(red('Please try again.'))
1087 Unix's command `cal`
1090 rel
= os
.popen('cal').read().split('\n')
1093 show_calendar(month
, date
, rel
)
1098 Browse and change config
1100 all_config
= get_all_config()
1101 g
['stuff'] = g
['stuff'].strip()
1104 for k
in all_config
:
1106 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1108 guide
= 'Detailed explanation can be found at ' + \
1109 color_func(c
['TWEET']['link'])(
1110 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1112 # Print specific config
1113 elif len(g
['stuff'].split()) == 1:
1114 if g
['stuff'] in all_config
:
1117 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1120 printNicely(red('No such config key.'))
1121 # Print specific config's default value
1122 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1123 key
= g
['stuff'].split()[0]
1125 value
= get_default_config(key
)
1126 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1128 except Exception as e
:
1130 # Delete specific config key in config file
1131 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1132 key
= g
['stuff'].split()[0]
1135 printNicely(green('Config key is dropped.'))
1136 except Exception as e
:
1138 # Set specific config
1139 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1140 key
= g
['stuff'].split()[0]
1141 value
= g
['stuff'].split()[-1]
1142 if key
== 'THEME' and not validate_theme(value
):
1143 printNicely(red('Invalid theme\'s value.'))
1146 set_config(key
, value
)
1147 # Apply theme immediately
1149 c
['THEME'] = reload_theme(value
, c
['THEME'])
1150 g
['decorated_name'] = lambda x
: color_func(
1151 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1153 printNicely(green('Updated successfully.'))
1154 except Exception as e
:
1157 printNicely(light_magenta('Sorry I can\'s understand.'))
1162 List and change theme
1166 for theme
in g
['themes']:
1167 line
= light_magenta(theme
)
1168 if c
['THEME'] == theme
:
1169 line
= ' ' * 2 + light_yellow('* ') + line
1171 line
= ' ' * 4 + line
1177 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1178 # Redefine decorated_name
1179 g
['decorated_name'] = lambda x
: color_func(
1180 c
['DECORATED_NAME'])(
1182 printNicely(green('Theme changed.'))
1184 printNicely(red('No such theme exists.'))
1187 def help_discover():
1192 # Discover the world
1194 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1195 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1196 'You can try ' + light_green('trend US') + ' or ' + \
1197 light_green('trend JP Tokyo') + '.\n'
1198 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1199 light_green('home 7') + ' will show 7 tweets.\n'
1200 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1201 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1202 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of replies prior to the tweet with ' + \
1203 light_yellow('[id=12]') + '.\n'
1204 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1205 magenta('@mdo') + '.\n'
1206 usage
+= s
* 2 + light_green('view @mdo') + \
1207 ' will show ' + magenta('@mdo') + '\'s home.\n'
1208 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1209 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1210 'Search can be performed with or without hashtag.\n'
1221 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1222 usage
+= s
* 2 + light_green('t oops ') + \
1223 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1225 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1226 light_yellow('[id=12]') + '.\n'
1228 light_green('quote 12 ') + ' will quote the tweet with ' + \
1229 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1230 'the quote will be canceled.\n'
1232 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1233 light_yellow('[id=12]') + '.\n'
1234 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1235 light_yellow('oops') + '" to tweet with ' + \
1236 light_yellow('[id=12]') + '.\n'
1238 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1239 light_yellow('[id=12]') + '.\n'
1241 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1242 light_yellow('[id=12]') + '.\n'
1244 light_green('del 12 ') + ' will delete tweet with ' + \
1245 light_yellow('[id=12]') + '.\n'
1246 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1247 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1248 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1249 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1253 def help_messages():
1260 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1261 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1262 light_green('inbox 7') + ' will show newest 7 messages.\n'
1263 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1264 light_green('sent 7') + ' will show newest 7 messages.\n'
1265 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1266 magenta('@dtvd88') + '.\n'
1267 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1268 light_yellow('[message_id=5]') + '.\n'
1272 def help_friends_and_followers():
1274 Friends and Followers
1277 # Follower and following
1279 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1281 light_green('ls fl') + \
1282 ' will list all followers (people who are following you).\n'
1284 light_green('ls fr') + \
1285 ' will list all friends (people who you are following).\n'
1286 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1289 magenta('@dtvd88') + '.\n'
1290 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1291 magenta('@dtvd88') + '.\n'
1292 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1293 magenta('@dtvd88') + '.\n'
1294 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1295 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1296 magenta('@dtvd88') + '.\n'
1297 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1298 magenta('@dtvd88') + '.\n'
1299 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1300 magenta('@dtvd88') + ' as a spam account.\n'
1311 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1312 usage
+= s
* 2 + light_green('list') + \
1313 ' will show all lists you are belong to.\n'
1314 usage
+= s
* 2 + light_green('list home') + \
1315 ' will show timeline of list. You will be asked for list\'s name.\n'
1316 usage
+= s
* 2 + light_green('list all_mem') + \
1317 ' will show list\'s all members.\n'
1318 usage
+= s
* 2 + light_green('list all_sub') + \
1319 ' will show list\'s all subscribers.\n'
1320 usage
+= s
* 2 + light_green('list add') + \
1321 ' will add specific person to a list owned by you.' + \
1322 ' You will be asked for list\'s name and person\'s name.\n'
1323 usage
+= s
* 2 + light_green('list rm') + \
1324 ' will remove specific person from a list owned by you.' + \
1325 ' You will be asked for list\'s name and person\'s name.\n'
1326 usage
+= s
* 2 + light_green('list sub') + \
1327 ' will subscribe you to a specific list.\n'
1328 usage
+= s
* 2 + light_green('list unsub') + \
1329 ' will unsubscribe you from a specific list.\n'
1330 usage
+= s
* 2 + light_green('list own') + \
1331 ' will show all list owned by you.\n'
1332 usage
+= s
* 2 + light_green('list new') + \
1333 ' will create a new list.\n'
1334 usage
+= s
* 2 + light_green('list update') + \
1335 ' will update a list owned by you.\n'
1336 usage
+= s
* 2 + light_green('list del') + \
1337 ' will delete a list owned by you.\n'
1348 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1349 usage
+= s
* 2 + light_green('switch public #AKB') + \
1350 ' will switch to public stream and follow "' + \
1351 light_yellow('AKB') + '" keyword.\n'
1352 usage
+= s
* 2 + light_green('switch mine') + \
1353 ' will switch to your personal stream.\n'
1354 usage
+= s
* 2 + light_green('switch mine -f ') + \
1355 ' will prompt to enter the filter.\n'
1356 usage
+= s
* 3 + light_yellow('Only nicks') + \
1357 ' filter will decide nicks will be INCLUDE ONLY.\n'
1358 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1359 ' filter will decide nicks will be EXCLUDE.\n'
1360 usage
+= s
* 2 + light_green('switch mine -d') + \
1361 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1370 h
, w
= os
.popen('stty size', 'r').read().split()
1373 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1374 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1375 usage
+= s
+ 'You are ' + \
1376 light_yellow('already') + ' on your personal stream.\n'
1377 usage
+= s
+ 'Any update from Twitter will show up ' + \
1378 light_yellow('immediately') + '.\n'
1379 usage
+= s
+ 'In addition, following commands are available right now:\n'
1380 # Twitter help section
1382 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1383 usage
+= s
* 2 + light_green('h discover') + \
1384 ' will show help for discover commands.\n'
1385 usage
+= s
* 2 + light_green('h tweets') + \
1386 ' will show help for tweets commands.\n'
1387 usage
+= s
* 2 + light_green('h messages') + \
1388 ' will show help for messages commands.\n'
1389 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1390 ' will show help for friends and followers commands.\n'
1391 usage
+= s
* 2 + light_green('h list') + \
1392 ' will show help for list commands.\n'
1393 usage
+= s
* 2 + light_green('h stream') + \
1394 ' will show help for stream commands.\n'
1397 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1398 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1399 'will be evaluate by Python interpreter.\n'
1400 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1401 ' for current month.\n'
1404 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1405 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1406 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1407 ' theme immediately.\n'
1408 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1410 light_green('config ASCII_ART') + ' will output current value of ' +\
1411 light_yellow('ASCII_ART') + ' config key.\n'
1413 light_green('config TREND_MAX default') + ' will output default value of ' + \
1414 light_yellow('TREND_MAX') + ' config key.\n'
1416 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1417 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1419 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1420 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1421 light_yellow('True') + '.\n'
1424 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1425 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1426 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1427 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1428 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1429 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1432 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1433 usage
+= s
+ 'Have fun and hang tight! \n'
1436 'discover': help_discover
,
1437 'tweets': help_tweets
,
1438 'messages': help_messages
,
1439 'friends_and_followers': help_friends_and_followers
,
1441 'stream': help_stream
,
1446 lambda: printNicely(red('No such command.'))
1454 Pause stream display
1457 printNicely(green('Stream is paused'))
1465 printNicely(green('Stream is running back now'))
1481 printNicely(green('See you next time :)'))
1489 Reset prefix of line
1492 if c
.get('USER_JSON_ERROR'):
1493 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1494 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1496 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1499 printNicely(str(eval(g
['cmd'])))
1548 # Handle function set
1597 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1602 Listen to user's input
1607 ['public', 'mine'], # switch
1623 ['image'], # show image
1625 ['fl', 'fr'], # list
1652 [key
for key
in dict(get_all_config())], # config
1653 g
['themes'], # theme
1658 'friends_and_followers',
1668 init_interactive_shell(d
)
1674 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1677 # Save cmd to compare with readline buffer
1678 g
['cmd'] = line
.strip()
1679 # Get short cmd to pass to handle function
1681 cmd
= line
.split()[0]
1685 # Lock the semaphore
1687 # Save cmd to global variable and call process
1688 g
['stuff'] = ' '.join(line
.split()[1:])
1689 # Process the command
1692 if cmd
in ['switch', 't', 'rt', 'rep']:
1696 # Release the semaphore lock
1699 printNicely(red('OMG something is wrong with Twitter right now.'))
1702 def stream(domain
, args
, name
='Rainbow Stream'):
1708 c
['USER_DOMAIN']: name
,
1709 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1710 c
['SITE_DOMAIN']: name
,
1713 ascii_art(art_dict
[domain
])
1714 # These arguments are optional:
1716 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1718 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1721 if args
.track_keywords
:
1722 query_args
['track'] = args
.track_keywords
1724 stream
= TwitterStream(
1729 if domain
== c
['USER_DOMAIN']:
1730 tweet_iter
= stream
.user(**query_args
)
1731 elif domain
== c
['SITE_DOMAIN']:
1732 tweet_iter
= stream
.site(**query_args
)
1734 if args
.track_keywords
:
1735 tweet_iter
= stream
.statuses
.filter(**query_args
)
1737 tweet_iter
= stream
.statuses
.sample()
1738 # Block new stream until other one exits
1739 StreamLock
.acquire()
1740 g
['stream_stop'] = False
1741 for tweet
in tweet_iter
:
1743 printNicely("-- None --")
1744 elif tweet
is Timeout
:
1745 if(g
['stream_stop']):
1746 StreamLock
.release()
1748 elif tweet
is HeartbeatTimeout
:
1749 printNicely("-- Heartbeat Timeout --")
1750 guide
= light_magenta("You can use ") + \
1751 light_green("switch") + \
1752 light_magenta(" command to return to your stream.\n")
1753 guide
+= light_magenta("Type ") + \
1754 light_green("h stream") + \
1755 light_magenta(" for more details.")
1757 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1759 StreamLock
.release()
1761 elif tweet
is Hangup
:
1762 printNicely("-- Hangup --")
1763 elif tweet
.get('text'):
1766 keyword
=args
.track_keywords
,
1768 check_semaphore
=True,
1772 # Current readline buffer
1773 current_buffer
= readline
.get_line_buffer().strip()
1774 # There is an unexpected behaviour in MacOSX readline + Python 2:
1775 # after completely delete a word after typing it,
1776 # somehow readline buffer still contains
1777 # the 1st character of that word
1778 if current_buffer
and g
['cmd'] != current_buffer
:
1780 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1782 elif not c
['HIDE_PROMPT']:
1783 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1785 elif tweet
.get('direct_message'):
1786 print_message(tweet
['direct_message'], check_semaphore
=True)
1787 except TwitterHTTPError
:
1790 magenta("We have maximum connection problem with twitter'stream API right now :("))
1798 args
= parse_arguments()
1801 except TwitterHTTPError
:
1804 magenta("We have connection problem with twitter'stream API right now :("))
1805 printNicely(magenta("Let's try again later."))
1808 # Spawn stream thread
1809 th
= threading
.Thread(
1814 g
['original_name']))
1817 # Start listen process