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 name
= '@' + t
.account
.verify_credentials()['screen_name']
121 if not get_config('PREFIX'):
122 set_config('PREFIX', name
)
123 g
['original_name'] = name
[1:]
124 g
['decorated_name'] = lambda x
: color_func(
125 c
['DECORATED_NAME'])('[' + x
+ ']: ')
127 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
128 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
135 # Init tweet dict and message dict
137 c
['message_dict'] = []
139 c
['IMAGE_ON_TERM'] = args
.image_on_term
140 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
142 c
['IGNORE_LIST'] += build_mute_dict()
149 t
= Twitter(auth
=authen())
150 # Get country and town
152 country
= g
['stuff'].split()[0]
156 town
= g
['stuff'].split()[1]
159 avail
= t
.trends
.available()
162 trends
= t
.trends
.place(_id
=1)[0]['trends']
165 for location
in avail
:
166 # Search for country and Town
168 if location
['countryCode'] == country \
169 and location
['placeType']['name'] == 'Town' \
170 and location
['name'] == town
:
171 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
173 # Search for country only
175 if location
['countryCode'] == country \
176 and location
['placeType']['name'] == 'Country':
177 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
185 t
= Twitter(auth
=authen())
186 num
= c
['HOME_TWEET_NUM']
187 if g
['stuff'].isdigit():
188 num
= int(g
['stuff'])
189 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
198 t
= Twitter(auth
=authen())
199 num
= c
['HOME_TWEET_NUM']
200 if g
['stuff'].isdigit():
201 num
= int(g
['stuff'])
202 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
209 Show profile of a specific user
211 t
= Twitter(auth
=authen())
212 screen_name
= g
['stuff'].split()[0]
213 if screen_name
.startswith('@'):
216 screen_name
=screen_name
[1:],
217 include_entities
=False)
220 printNicely(red('Omg no user.'))
222 printNicely(red('A name should begin with a \'@\''))
229 t
= Twitter(auth
=authen())
230 user
= g
['stuff'].split()[0]
233 num
= int(g
['stuff'].split()[1])
235 num
= c
['HOME_TWEET_NUM']
236 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
240 printNicely(red('A name should begin with a \'@\''))
247 t
= Twitter(auth
=authen())
248 g
['stuff'] = g
['stuff'].strip()
249 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
251 printNicely('Newest tweets:')
252 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
257 printNicely(magenta('I\'m afraid there is no result'))
264 t
= Twitter(auth
=authen())
265 t
.statuses
.update(status
=g
['stuff'])
272 t
= Twitter(auth
=authen())
274 id = int(g
['stuff'].split()[0])
276 printNicely(red('Sorry I can\'t understand.'))
278 tid
= c
['tweet_dict'][id]
279 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
287 t
= Twitter(auth
=authen())
289 id = int(g
['stuff'].split()[0])
291 printNicely(red('Sorry I can\'t understand.'))
293 tid
= c
['tweet_dict'][id]
294 tweet
= t
.statuses
.show(id=tid
)
296 formater
= format_quote(tweet
)
300 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
301 comment
= raw_input(prefix
)
303 quote
= comment
.join(formater
.split('#comment'))
304 t
.statuses
.update(status
=quote
)
306 printNicely(light_magenta('No text added.'))
313 t
= Twitter(auth
=authen())
316 id = int(g
['stuff'].split()[0])
318 printNicely(red('Sorry I can\'t understand.'))
320 tid
= c
['tweet_dict'][id]
321 # Get display num if exist
323 num
= int(g
['stuff'].split()[1])
325 num
= c
['RETWEETS_SHOW_NUM']
326 # Get result and display
327 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
329 printNicely(magenta('This tweet has no retweet.'))
331 for tweet
in reversed(rt_ary
):
340 t
= Twitter(auth
=authen())
342 id = int(g
['stuff'].split()[0])
344 printNicely(red('Sorry I can\'t understand.'))
346 tid
= c
['tweet_dict'][id]
347 tweet
= t
.statuses
.show(id=tid
)
348 limit
= c
['CONVERSATION_MAX']
350 thread_ref
.append(tweet
)
351 prev_tid
= tweet
['in_reply_to_status_id']
352 while prev_tid
and limit
:
354 tweet
= t
.statuses
.show(id=prev_tid
)
355 prev_tid
= tweet
['in_reply_to_status_id']
356 thread_ref
.append(tweet
)
358 for tweet
in reversed(thread_ref
):
367 t
= Twitter(auth
=authen())
369 id = int(g
['stuff'].split()[0])
371 printNicely(red('Sorry I can\'t understand.'))
373 tid
= c
['tweet_dict'][id]
374 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
375 status
= ' '.join(g
['stuff'].split()[1:])
376 status
= '@' + user
+ ' ' + str2u(status
)
377 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
384 t
= Twitter(auth
=authen())
386 id = int(g
['stuff'].split()[0])
388 printNicely(red('Sorry I can\'t understand.'))
390 tid
= c
['tweet_dict'][id]
391 t
.favorites
.create(_id
=tid
, include_entities
=False)
392 printNicely(green('Favorited.'))
393 draw(t
.statuses
.show(id=tid
))
401 t
= Twitter(auth
=authen())
403 id = int(g
['stuff'].split()[0])
405 printNicely(red('Sorry I can\'t understand.'))
407 tid
= c
['tweet_dict'][id]
408 t
.favorites
.destroy(_id
=tid
)
409 printNicely(green('Okay it\'s unfavorited.'))
410 draw(t
.statuses
.show(id=tid
))
418 t
= Twitter(auth
=authen())
420 id = int(g
['stuff'].split()[0])
422 printNicely(red('Sorry I can\'t understand.'))
424 tid
= c
['tweet_dict'][id]
425 t
.statuses
.destroy(id=tid
)
426 printNicely(green('Okay it\'s gone.'))
433 t
= Twitter(auth
=authen())
435 target
= g
['stuff'].split()[0]
436 if target
!= 'image':
438 id = int(g
['stuff'].split()[1])
439 tid
= c
['tweet_dict'][id]
440 tweet
= t
.statuses
.show(id=tid
)
441 media
= tweet
['entities']['media']
443 res
= requests
.get(m
['media_url'])
444 img
= Image
.open(BytesIO(res
.content
))
447 printNicely(red('Sorry I can\'t show this image.'))
454 t
= Twitter(auth
=authen())
456 if not g
['stuff'].isdigit():
458 tid
= c
['tweet_dict'][int(g
['stuff'])]
459 tweet
= t
.statuses
.show(id=tid
)
461 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
463 printNicely(light_magenta('No url here @.@!'))
465 for link
in link_ary
:
466 webbrowser
.open(link
)
468 printNicely(red('Sorry I can\'t open url in this tweet.'))
473 Inbox direct messages
475 t
= Twitter(auth
=authen())
476 num
= c
['MESSAGES_DISPLAY']
478 if g
['stuff'].isdigit():
481 # Max message per page is 20 so we have to loop
483 rel
= rel
+ t
.direct_messages(
486 include_entities
=False,
491 rel
= rel
+ t
.direct_messages(
494 include_entities
=False,
498 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
499 for m
in reversed(rel
):
508 t
= Twitter(auth
=authen())
509 num
= c
['MESSAGES_DISPLAY']
511 if g
['stuff'].isdigit():
512 num
= int(g
['stuff'])
514 # Max message per page is 20 so we have to loop
516 rel
= rel
+ t
.direct_messages
.sent(
519 include_entities
=False,
524 rel
= rel
+ t
.direct_messages
.sent(
527 include_entities
=False,
531 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
532 for m
in reversed(rel
):
539 Send a direct message
541 t
= Twitter(auth
=authen())
542 user
= g
['stuff'].split()[0]
543 if user
[0].startswith('@'):
545 content
= g
['stuff'].split()[1]
547 printNicely(red('Sorry I can\'t understand.'))
548 t
.direct_messages
.new(
549 screen_name
=user
[1:],
552 printNicely(green('Message sent.'))
554 printNicely(red('A name should begin with a \'@\''))
561 t
= Twitter(auth
=authen())
563 id = int(g
['stuff'].split()[0])
565 printNicely(red('Sorry I can\'t understand.'))
566 mid
= c
['message_dict'][id]
567 t
.direct_messages
.destroy(id=mid
)
568 printNicely(green('Message deleted.'))
573 List friends for followers
575 t
= Twitter(auth
=authen())
578 name
= g
['stuff'].split()[1]
579 if name
.startswith('@'):
582 printNicely(red('A name should begin with a \'@\''))
583 raise Exception('Invalid name')
585 name
= g
['original_name']
586 # Get list followers or friends
588 target
= g
['stuff'].split()[0]
590 printNicely(red('Omg some syntax is wrong.'))
592 d
= {'fl': 'followers', 'fr': 'friends'}
596 while next_cursor
!= 0:
597 list = getattr(t
, d
[target
]).list(
601 include_entities
=False,
603 for u
in list['users']:
604 rel
[u
['name']] = '@' + u
['screen_name']
605 next_cursor
= list['next_cursor']
607 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
609 user
= ' ' + cycle_color(name
)
610 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
618 t
= Twitter(auth
=authen())
619 screen_name
= g
['stuff'].split()[0]
620 if screen_name
.startswith('@'):
621 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
622 printNicely(green('You are following ' + screen_name
+ ' now!'))
624 printNicely(red('A name should begin with a \'@\''))
631 t
= Twitter(auth
=authen())
632 screen_name
= g
['stuff'].split()[0]
633 if screen_name
.startswith('@'):
634 t
.friendships
.destroy(
635 screen_name
=screen_name
[1:],
636 include_entities
=False)
637 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
639 printNicely(red('A name should begin with a \'@\''))
646 t
= Twitter(auth
=authen())
648 screen_name
= g
['stuff'].split()[0]
650 printNicely(red('A name should be specified. '))
652 if screen_name
.startswith('@'):
654 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
655 if isinstance(rel
, dict):
656 printNicely(green(screen_name
+ ' is muted.'))
657 c
['IGNORE_LIST'] += [unc(screen_name
)]
658 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
660 printNicely(red(rel
))
662 printNicely(red('Something is wrong, can not mute now :('))
664 printNicely(red('A name should begin with a \'@\''))
671 t
= Twitter(auth
=authen())
673 screen_name
= g
['stuff'].split()[0]
675 printNicely(red('A name should be specified. '))
677 if screen_name
.startswith('@'):
679 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
680 if isinstance(rel
, dict):
681 printNicely(green(screen_name
+ ' is unmuted.'))
682 c
['IGNORE_LIST'].remove(screen_name
)
684 printNicely(red(rel
))
686 printNicely(red('Maybe you are not muting this person ?'))
688 printNicely(red('A name should begin with a \'@\''))
695 # Get dict of muting users
696 md
= build_mute_dict(dict_data
=True)
697 printNicely('All: ' + str(len(md
)) + ' people.')
699 user
= ' ' + cycle_color(md
[name
])
700 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
702 # Update from Twitter
703 c
['IGNORE_LIST'] = [n
for n
in md
]
710 t
= Twitter(auth
=authen())
711 screen_name
= g
['stuff'].split()[0]
712 if screen_name
.startswith('@'):
714 screen_name
=screen_name
[1:],
715 include_entities
=False,
717 printNicely(green('You blocked ' + screen_name
+ '.'))
719 printNicely(red('A name should begin with a \'@\''))
726 t
= Twitter(auth
=authen())
727 screen_name
= g
['stuff'].split()[0]
728 if screen_name
.startswith('@'):
730 screen_name
=screen_name
[1:],
731 include_entities
=False,
733 printNicely(green('Unblock ' + screen_name
+ ' success!'))
735 printNicely(red('A name should begin with a \'@\''))
740 Report a user as a spam account
742 t
= Twitter(auth
=authen())
743 screen_name
= g
['stuff'].split()[0]
744 if screen_name
.startswith('@'):
746 screen_name
=screen_name
[1:])
747 printNicely(green('You reported ' + screen_name
+ '.'))
749 printNicely(red('Sorry I can\'t understand.'))
757 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
758 # Get list name and owner
760 owner
, slug
= list_name
.split('/')
761 if slug
.startswith('@'):
766 light_magenta('List name should follow "@owner/list_name" format.'))
767 raise Exception('Wrong list name')
774 rel
= t
.lists
.list(screen_name
=g
['original_name'])
778 printNicely(light_magenta('You belong to no lists :)'))
785 owner
, slug
= get_slug()
786 res
= t
.lists
.statuses(
788 owner_screen_name
=owner
,
790 include_entities
=False)
800 owner
, slug
= get_slug()
804 while next_cursor
!= 0:
807 owner_screen_name
=owner
,
809 include_entities
=False)
811 rel
[u
['name']] = '@' + u
['screen_name']
812 next_cursor
= m
['next_cursor']
813 printNicely('All: ' + str(len(rel
)) + ' members.')
815 user
= ' ' + cycle_color(name
)
816 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
820 def list_subscribers(t
):
824 owner
, slug
= get_slug()
828 while next_cursor
!= 0:
829 m
= t
.lists
.subscribers(
831 owner_screen_name
=owner
,
833 include_entities
=False)
835 rel
[u
['name']] = '@' + u
['screen_name']
836 next_cursor
= m
['next_cursor']
837 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
839 user
= ' ' + cycle_color(name
)
840 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
846 Add specific user to a list
848 owner
, slug
= get_slug()
850 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
851 if user_name
.startswith('@'):
852 user_name
= user_name
[1:]
854 t
.lists
.members
.create(
856 owner_screen_name
=owner
,
857 screen_name
=user_name
)
858 printNicely(green('Added.'))
860 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
865 Remove specific user from a list
867 owner
, slug
= get_slug()
869 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
870 if user_name
.startswith('@'):
871 user_name
= user_name
[1:]
873 t
.lists
.members
.destroy(
875 owner_screen_name
=owner
,
876 screen_name
=user_name
)
877 printNicely(green('Gone.'))
879 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
882 def list_subscribe(t
):
886 owner
, slug
= get_slug()
889 t
.lists
.subscribers
.create(
891 owner_screen_name
=owner
)
892 printNicely(green('Done.'))
895 light_magenta('I\'m sorry you can not subscribe to this list.'))
898 def list_unsubscribe(t
):
902 owner
, slug
= get_slug()
905 t
.lists
.subscribers
.destroy(
907 owner_screen_name
=owner
)
908 printNicely(green('Done.'))
911 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
920 while next_cursor
!= 0:
921 res
= t
.lists
.ownerships(
922 screen_name
=g
['original_name'],
925 next_cursor
= res
['next_cursor']
929 printNicely(light_magenta('You own no lists :)'))
936 name
= raw_input(light_magenta('New list\'s name: '))
937 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
938 description
= raw_input(light_magenta('New list\'s description: '))
943 description
=description
)
944 printNicely(green(name
+ ' list is created.'))
946 printNicely(red('Oops something is wrong with Twitter :('))
953 slug
= raw_input(light_magenta('Your list that you want to update: '))
954 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
955 mode
= raw_input(light_magenta('Update mode (public/private): '))
956 description
= raw_input(light_magenta('Update description: '))
960 slug
='-'.join(slug
.split()),
961 owner_screen_name
=g
['original_name'],
964 description
=description
)
968 owner_screen_name
=g
['original_name'],
970 description
=description
)
971 printNicely(green(slug
+ ' list is updated.'))
973 printNicely(red('Oops something is wrong with Twitter :('))
980 slug
= raw_input(light_magenta('Your list that you want to delete: '))
983 slug
='-'.join(slug
.split()),
984 owner_screen_name
=g
['original_name'])
985 printNicely(green(slug
+ ' list is deleted.'))
987 printNicely(red('Oops something is wrong with Twitter :('))
994 t
= Twitter(auth
=authen())
995 # List all lists or base on action
997 g
['list_action'] = g
['stuff'].split()[0]
1004 'all_mem': list_members
,
1005 'all_sub': list_subscribers
,
1008 'sub': list_subscribe
,
1009 'unsub': list_unsubscribe
,
1012 'update': list_update
,
1016 return action_ary
[g
['list_action']](t
)
1018 printNicely(red('Please try again.'))
1026 target
= g
['stuff'].split()[0]
1028 args
= parse_arguments()
1030 if g
['stuff'].split()[-1] == '-f':
1031 guide
= 'To ignore an option, just hit Enter key.'
1032 printNicely(light_magenta(guide
))
1033 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1034 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1035 args
.filter = filter(None, only
.split(','))
1036 args
.ignore
= filter(None, ignore
.split(','))
1037 elif g
['stuff'].split()[-1] == '-d':
1038 args
.filter = c
['ONLY_LIST']
1039 args
.ignore
= c
['IGNORE_LIST']
1041 printNicely(red('Sorry, wrong format.'))
1044 if target
== 'public':
1045 keyword
= g
['stuff'].split()[1]
1046 if keyword
[0] == '#':
1047 keyword
= keyword
[1:]
1049 g
['stream_stop'] = True
1050 args
.track_keywords
= keyword
1052 th
= threading
.Thread(
1060 elif target
== 'mine':
1062 g
['stream_stop'] = True
1064 th
= threading
.Thread(
1069 g
['original_name']))
1074 printNicely(cyan('Only: ' + str(args
.filter)))
1076 printNicely(red('Ignore: ' + str(args
.ignore
)))
1079 printNicely(red('Sorry I can\'t understand.'))
1084 Unix's command `cal`
1087 rel
= os
.popen('cal').read().split('\n')
1090 show_calendar(month
, date
, rel
)
1095 List and change theme
1099 for theme
in g
['themes']:
1100 line
= light_magenta(theme
)
1101 if c
['THEME'] == theme
:
1102 line
= ' ' * 2 + light_yellow('* ') + line
1104 line
= ' ' * 4 + line
1110 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1111 # Redefine decorated_name
1112 g
['decorated_name'] = lambda x
: color_func(
1113 c
['DECORATED_NAME'])(
1115 printNicely(green('Theme changed.'))
1117 printNicely(red('No such theme exists.'))
1122 Browse and change config
1124 all_config
= get_all_config()
1125 g
['stuff'] = g
['stuff'].strip()
1128 for k
in all_config
:
1130 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1132 guide
= 'Detailed explanation can be found at ' + \
1133 color_func(c
['TWEET']['link'])(
1134 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1136 # Print specific config
1137 elif len(g
['stuff'].split()) == 1:
1138 if g
['stuff'] in all_config
:
1141 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1144 printNicely(red('No such config key.'))
1145 # Print specific config's default value
1146 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1147 key
= g
['stuff'].split()[0]
1149 value
= get_default_config(key
)
1150 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1152 except Exception as e
:
1154 # Delete specific config key in config file
1155 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1156 key
= g
['stuff'].split()[0]
1159 printNicely(green('Config key is dropped.'))
1160 except Exception as e
:
1162 # Set specific config
1163 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1164 key
= g
['stuff'].split()[0]
1165 value
= g
['stuff'].split()[-1]
1166 if key
== 'THEME' and not validate_theme(value
):
1167 printNicely(red('Invalid theme\'s value.'))
1170 set_config(key
, value
)
1171 # Apply theme immediately
1173 c
['THEME'] = reload_theme(value
, c
['THEME'])
1174 g
['decorated_name'] = lambda x
: color_func(
1175 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1177 printNicely(green('Updated successfully.'))
1178 except Exception as e
:
1181 printNicely(light_magenta('Sorry I can\'s understand.'))
1184 def help_discover():
1189 # Discover the world
1191 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1192 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1193 'You can try ' + light_green('trend US') + ' or ' + \
1194 light_green('trend JP Tokyo') + '.\n'
1195 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1196 light_green('home 7') + ' will show 7 tweets.\n'
1197 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1198 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1199 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1200 magenta('@mdo') + '.\n'
1201 usage
+= s
* 2 + light_green('view @mdo') + \
1202 ' will show ' + magenta('@mdo') + '\'s home.\n'
1203 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1204 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1205 'Search can be performed with or without hashtag.\n'
1216 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1217 usage
+= s
* 2 + light_green('t oops ') + \
1218 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1220 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1221 light_yellow('[id=12]') + '.\n'
1223 light_green('quote 12 ') + ' will quote the tweet with ' + \
1224 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1225 'the quote will be canceled.\n'
1227 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1228 light_yellow('[id=12]') + '.\n'
1229 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1230 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1231 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1232 light_yellow('oops') + '" to tweet with ' + \
1233 light_yellow('[id=12]') + '.\n'
1235 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1236 light_yellow('[id=12]') + '.\n'
1238 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1239 light_yellow('[id=12]') + '.\n'
1241 light_green('del 12 ') + ' will delete tweet with ' + \
1242 light_yellow('[id=12]') + '.\n'
1243 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1244 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1245 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1246 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1250 def help_messages():
1257 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1258 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1259 light_green('inbox 7') + ' will show newest 7 messages.\n'
1260 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1261 light_green('sent 7') + ' will show newest 7 messages.\n'
1262 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1263 magenta('@dtvd88') + '.\n'
1264 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1265 light_yellow('[message_id=5]') + '.\n'
1269 def help_friends_and_followers():
1271 Friends and Followers
1274 # Follower and following
1276 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1278 light_green('ls fl') + \
1279 ' will list all followers (people who are following you).\n'
1281 light_green('ls fr') + \
1282 ' will list all friends (people who you are following).\n'
1283 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1284 magenta('@dtvd88') + '.\n'
1285 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1286 magenta('@dtvd88') + '.\n'
1287 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1288 magenta('@dtvd88') + '.\n'
1289 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1290 magenta('@dtvd88') + '.\n'
1291 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1292 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1293 magenta('@dtvd88') + '.\n'
1294 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1295 magenta('@dtvd88') + '.\n'
1296 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1297 magenta('@dtvd88') + ' as a spam account.\n'
1308 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1309 usage
+= s
* 2 + light_green('list') + \
1310 ' will show all lists you are belong to.\n'
1311 usage
+= s
* 2 + light_green('list home') + \
1312 ' will show timeline of list. You will be asked for list\'s name.\n'
1313 usage
+= s
* 2 + light_green('list all_mem') + \
1314 ' will show list\'s all members.\n'
1315 usage
+= s
* 2 + light_green('list all_sub') + \
1316 ' will show list\'s all subscribers.\n'
1317 usage
+= s
* 2 + light_green('list add') + \
1318 ' will add specific person to a list owned by you.' + \
1319 ' You will be asked for list\'s name and person\'s name.\n'
1320 usage
+= s
* 2 + light_green('list rm') + \
1321 ' will remove specific person from 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 sub') + \
1324 ' will subscribe you to a specific list.\n'
1325 usage
+= s
* 2 + light_green('list unsub') + \
1326 ' will unsubscribe you from a specific list.\n'
1327 usage
+= s
* 2 + light_green('list own') + \
1328 ' will show all list owned by you.\n'
1329 usage
+= s
* 2 + light_green('list new') + \
1330 ' will create a new list.\n'
1331 usage
+= s
* 2 + light_green('list update') + \
1332 ' will update a list owned by you.\n'
1333 usage
+= s
* 2 + light_green('list del') + \
1334 ' will delete a list owned by you.\n'
1345 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1346 usage
+= s
* 2 + light_green('switch public #AKB') + \
1347 ' will switch to public stream and follow "' + \
1348 light_yellow('AKB') + '" keyword.\n'
1349 usage
+= s
* 2 + light_green('switch mine') + \
1350 ' will switch to your personal stream.\n'
1351 usage
+= s
* 2 + light_green('switch mine -f ') + \
1352 ' will prompt to enter the filter.\n'
1353 usage
+= s
* 3 + light_yellow('Only nicks') + \
1354 ' filter will decide nicks will be INCLUDE ONLY.\n'
1355 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1356 ' filter will decide nicks will be EXCLUDE.\n'
1357 usage
+= s
* 2 + light_green('switch mine -d') + \
1358 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1367 h
, w
= os
.popen('stty size', 'r').read().split()
1370 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1371 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1372 usage
+= s
+ 'You are ' + \
1373 light_yellow('already') + ' on your personal stream.\n'
1374 usage
+= s
+ 'Any update from Twitter will show up ' + \
1375 light_yellow('immediately') + '.\n'
1376 usage
+= s
+ 'In addition, following commands are available right now:\n'
1377 # Twitter help section
1379 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1380 usage
+= s
* 2 + light_green('h discover') + \
1381 ' will show help for discover commands.\n'
1382 usage
+= s
* 2 + light_green('h tweets') + \
1383 ' will show help for tweets commands.\n'
1384 usage
+= s
* 2 + light_green('h messages') + \
1385 ' will show help for messages commands.\n'
1386 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1387 ' will show help for friends and followers commands.\n'
1388 usage
+= s
* 2 + light_green('h list') + \
1389 ' will show help for list commands.\n'
1390 usage
+= s
* 2 + light_green('h stream') + \
1391 ' will show help for stream commands.\n'
1394 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1395 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1396 'will be evaluate by Python interpreter.\n'
1397 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1398 ' for current month.\n'
1401 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1402 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1403 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1404 ' theme immediately.\n'
1405 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1407 light_green('config ASCII_ART') + ' will output current value of ' +\
1408 light_yellow('ASCII_ART') + ' config key.\n'
1410 light_green('config TREND_MAX default') + ' will output default value of ' + \
1411 light_yellow('TREND_MAX') + ' config key.\n'
1413 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1414 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1416 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1417 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1418 light_yellow('True') + '.\n'
1421 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1422 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1423 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1424 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1425 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1426 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1429 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1430 usage
+= s
+ 'Have fun and hang tight! \n'
1433 'discover': help_discover
,
1434 'tweets': help_tweets
,
1435 'messages': help_messages
,
1436 'friends_and_followers': help_friends_and_followers
,
1438 'stream': help_stream
,
1443 lambda: printNicely(red('No such command.'))
1451 Pause stream display
1454 printNicely(green('Stream is paused'))
1462 printNicely(green('Stream is running back now'))
1478 printNicely(green('See you next time :)'))
1486 Reset prefix of line
1489 if c
.get('USER_JSON_ERROR'):
1490 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1491 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1493 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1496 printNicely(str(eval(g
['cmd'])))
1545 # Handle function set
1594 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1599 Listen to user's input
1604 ['public', 'mine'], # switch
1620 ['image'], # show image
1622 ['fl', 'fr'], # list
1649 [key
for key
in dict(get_all_config())], # config
1650 g
['themes'], # theme
1655 'friends_and_followers',
1665 init_interactive_shell(d
)
1672 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1675 # Save cmd to compare with readline buffer
1676 g
['cmd'] = line
.strip()
1677 # Get short cmd to pass to handle function
1679 cmd
= line
.split()[0]
1682 # Lock the semaphore
1684 # Save cmd to global variable and call process
1685 g
['stuff'] = ' '.join(line
.split()[1:])
1686 # Process the command
1689 if cmd
in ['switch', 't', 'rt', 'rep']:
1693 # Release the semaphore lock
1698 printNicely(red('OMG something is wrong with Twitter right now.'))
1701 def stream(domain
, args
, name
='Rainbow Stream'):
1707 c
['USER_DOMAIN']: name
,
1708 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1709 c
['SITE_DOMAIN']: name
,
1712 ascii_art(art_dict
[domain
])
1713 # These arguments are optional:
1715 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1717 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1720 if args
.track_keywords
:
1721 query_args
['track'] = args
.track_keywords
1723 stream
= TwitterStream(
1728 if domain
== c
['USER_DOMAIN']:
1729 tweet_iter
= stream
.user(**query_args
)
1730 elif domain
== c
['SITE_DOMAIN']:
1731 tweet_iter
= stream
.site(**query_args
)
1733 if args
.track_keywords
:
1734 tweet_iter
= stream
.statuses
.filter(**query_args
)
1736 tweet_iter
= stream
.statuses
.sample()
1737 # Block new stream until other one exits
1738 StreamLock
.acquire()
1739 g
['stream_stop'] = False
1740 for tweet
in tweet_iter
:
1742 printNicely("-- None --")
1743 elif tweet
is Timeout
:
1744 if(g
['stream_stop']):
1745 StreamLock
.release()
1747 elif tweet
is HeartbeatTimeout
:
1748 printNicely("-- Heartbeat Timeout --")
1749 guide
= light_magenta("You can use ") + \
1750 light_green("switch") + \
1751 light_magenta(" command to return to your stream.\n")
1752 guide
+= light_magenta("Type ") + \
1753 light_green("h stream") + \
1754 light_magenta(" for more details.")
1756 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1758 StreamLock
.release()
1760 elif tweet
is Hangup
:
1761 printNicely("-- Hangup --")
1762 elif tweet
.get('text'):
1765 keyword
=args
.track_keywords
,
1767 check_semaphore
=True,
1771 # Current readline buffer
1772 current_buffer
= readline
.get_line_buffer().strip()
1773 # There is an unexpected behaviour in MacOSX readline + Python 2:
1774 # after completely delete a word after typing it,
1775 # somehow readline buffer still contains
1776 # the 1st character of that word
1777 if current_buffer
and g
['cmd'] != current_buffer
:
1779 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1781 elif not c
['HIDE_PROMPT']:
1782 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1784 elif tweet
.get('direct_message'):
1785 print_message(tweet
['direct_message'], check_semaphore
=True)
1786 except TwitterHTTPError
:
1789 magenta("We have maximum connection problem with twitter'stream API right now :("))
1797 args
= parse_arguments()
1800 except TwitterHTTPError
:
1803 magenta("We have connection problem with twitter'stream API right now :("))
1804 printNicely(magenta("Let's try again later."))
1807 # Spawn stream thread
1808 th
= threading
.Thread(
1813 g
['original_name']))
1816 # Start listen process