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).')
46 '--heartbeat-timeout',
47 help='Set heartbeat timeout.',
53 help='Set stream to non-blocking.')
57 help='Search the stream for specific text.')
61 help='Filter specific screen_name.')
65 help='Ignore specific screen_name.')
70 help='Display all image on terminal.')
71 return parser
.parse_args()
76 Authenticate with Twitter OAuth
78 # When using rainbow stream you must authorize.
79 twitter_credential
= os
.environ
.get(
83 '')) + os
.sep
+ '.rainbow_oauth'
84 if not os
.path
.exists(twitter_credential
):
85 oauth_dance("Rainbow Stream",
89 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
97 def build_mute_dict(dict_data
=False):
101 t
= Twitter(auth
=authen())
104 screen_name_list
= []
107 while next_cursor
!= 0:
108 list = t
.mutes
.users
.list(
109 screen_name
=g
['original_name'],
112 include_entities
=False,
114 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
115 name_list
+= [u
['name'] for u
in list['users']]
116 next_cursor
= list['next_cursor']
117 # Return dict or list
119 return dict(zip(screen_name_list
, name_list
))
121 return screen_name_list
129 ctrl_c_handler
= lambda signum
, frame
: quit()
130 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
132 t
= Twitter(auth
=authen())
133 name
= '@' + t
.account
.verify_credentials()['screen_name']
134 if not get_config('PREFIX'):
135 set_config('PREFIX', name
)
136 g
['original_name'] = name
[1:]
137 g
['decorated_name'] = lambda x
: color_func(
138 c
['DECORATED_NAME'])('[' + x
+ ']: ')
140 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
141 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
148 # Init tweet dict and message dict
150 c
['message_dict'] = []
152 c
['IMAGE_ON_TERM'] = args
.image_on_term
153 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
155 c
['IGNORE_LIST'] += build_mute_dict()
163 target
= g
['stuff'].split()[0]
165 args
= parse_arguments()
167 if g
['stuff'].split()[-1] == '-f':
168 guide
= 'To ignore an option, just hit Enter key.'
169 printNicely(light_magenta(guide
))
170 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
171 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
172 args
.filter = filter(None, only
.split(','))
173 args
.ignore
= filter(None, ignore
.split(','))
174 elif g
['stuff'].split()[-1] == '-d':
175 args
.filter = c
['ONLY_LIST']
176 args
.ignore
= c
['IGNORE_LIST']
178 printNicely(red('Sorry, wrong format.'))
181 if target
== 'public':
182 keyword
= g
['stuff'].split()[1]
183 if keyword
[0] == '#':
184 keyword
= keyword
[1:]
186 g
['stream_stop'] = True
187 args
.track_keywords
= keyword
189 th
= threading
.Thread(
197 elif target
== 'mine':
199 g
['stream_stop'] = True
201 th
= threading
.Thread(
211 printNicely(cyan('Only: ' + str(args
.filter)))
213 printNicely(red('Ignore: ' + str(args
.ignore
)))
216 printNicely(red('Sorry I can\'t understand.'))
223 t
= Twitter(auth
=authen())
224 # Get country and town
226 country
= g
['stuff'].split()[0]
230 town
= g
['stuff'].split()[1]
233 avail
= t
.trends
.available()
236 trends
= t
.trends
.place(_id
=1)[0]['trends']
239 for location
in avail
:
240 # Search for country and Town
242 if location
['countryCode'] == country \
243 and location
['placeType']['name'] == 'Town' \
244 and location
['name'] == town
:
245 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
247 # Search for country only
249 if location
['countryCode'] == country \
250 and location
['placeType']['name'] == 'Country':
251 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
259 t
= Twitter(auth
=authen())
260 num
= c
['HOME_TWEET_NUM']
261 if g
['stuff'].isdigit():
262 num
= int(g
['stuff'])
263 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
272 t
= Twitter(auth
=authen())
273 user
= g
['stuff'].split()[0]
276 num
= int(g
['stuff'].split()[1])
278 num
= c
['HOME_TWEET_NUM']
279 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
283 printNicely(red('A name should begin with a \'@\''))
290 t
= Twitter(auth
=authen())
291 num
= c
['HOME_TWEET_NUM']
292 if g
['stuff'].isdigit():
293 num
= int(g
['stuff'])
294 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
303 t
= Twitter(auth
=authen())
304 t
.statuses
.update(status
=g
['stuff'])
311 t
= Twitter(auth
=authen())
313 id = int(g
['stuff'].split()[0])
315 printNicely(red('Sorry I can\'t understand.'))
317 tid
= c
['tweet_dict'][id]
318 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
325 t
= Twitter(auth
=authen())
327 id = int(g
['stuff'].split()[0])
329 printNicely(red('Sorry I can\'t understand.'))
331 tid
= c
['tweet_dict'][id]
332 tweet
= t
.statuses
.show(id=tid
)
333 screen_name
= tweet
['user']['screen_name']
335 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
336 quote
= quote
.encode('utf8')
337 notice
= light_magenta('Compose mode ')
338 notice
+= light_yellow('(Enter nothing will cancel the quote)')
339 notice
+= light_magenta(':')
341 extra
= raw_input(quote
)
343 t
.statuses
.update(status
=quote
+ extra
)
345 printNicely(light_magenta('No text added.'))
352 t
= Twitter(auth
=authen())
355 id = int(g
['stuff'].split()[0])
357 printNicely(red('Sorry I can\'t understand.'))
359 tid
= c
['tweet_dict'][id]
360 # Get display num if exist
362 num
= int(g
['stuff'].split()[1])
364 num
= c
['RETWEETS_SHOW_NUM']
365 # Get result and display
366 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
368 printNicely(magenta('This tweet has no retweet.'))
370 for tweet
in reversed(rt_ary
):
379 t
= Twitter(auth
=authen())
381 id = int(g
['stuff'].split()[0])
383 printNicely(red('Sorry I can\'t understand.'))
385 tid
= c
['tweet_dict'][id]
386 t
.favorites
.create(_id
=tid
, include_entities
=False)
387 printNicely(green('Favorited.'))
388 draw(t
.statuses
.show(id=tid
))
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 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
404 status
= ' '.join(g
['stuff'].split()[1:])
405 status
= '@' + user
+ ' ' + unc(status
)
406 t
.statuses
.update(status
=status
, in_reply_to_status_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 t
.statuses
.destroy(id=tid
)
421 printNicely(green('Okay it\'s gone.'))
428 t
= Twitter(auth
=authen())
430 id = int(g
['stuff'].split()[0])
432 printNicely(red('Sorry I can\'t understand.'))
434 tid
= c
['tweet_dict'][id]
435 t
.favorites
.destroy(_id
=tid
)
436 printNicely(green('Okay it\'s unfavorited.'))
437 draw(t
.statuses
.show(id=tid
))
445 t
= Twitter(auth
=authen())
446 g
['stuff'] = g
['stuff'].strip()
447 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
449 printNicely('Newest tweets:')
450 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
455 printNicely(magenta('I\'m afraid there is no result'))
460 Send a direct message
462 t
= Twitter(auth
=authen())
463 user
= g
['stuff'].split()[0]
464 if user
[0].startswith('@'):
466 content
= g
['stuff'].split()[1]
468 printNicely(red('Sorry I can\'t understand.'))
469 t
.direct_messages
.new(
470 screen_name
=user
[1:],
473 printNicely(green('Message sent.'))
475 printNicely(red('A name should begin with a \'@\''))
482 t
= Twitter(auth
=authen())
484 target
= g
['stuff'].split()[0]
485 if target
!= 'image':
487 id = int(g
['stuff'].split()[1])
488 tid
= c
['tweet_dict'][id]
489 tweet
= t
.statuses
.show(id=tid
)
490 media
= tweet
['entities']['media']
492 res
= requests
.get(m
['media_url'])
493 img
= Image
.open(BytesIO(res
.content
))
496 printNicely(red('Sorry I can\'t show this image.'))
503 t
= Twitter(auth
=authen())
505 if not g
['stuff'].isdigit():
507 tid
= c
['tweet_dict'][int(g
['stuff'])]
508 tweet
= t
.statuses
.show(id=tid
)
510 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
512 printNicely(light_magenta('No url here @.@!'))
514 for link
in link_ary
:
515 webbrowser
.open(link
)
517 printNicely(red('Sorry I can\'t open url in this tweet.'))
522 List friends for followers
524 t
= Twitter(auth
=authen())
527 name
= g
['stuff'].split()[1]
528 if name
.startswith('@'):
531 printNicely(red('A name should begin with a \'@\''))
532 raise Exception('Invalid name')
534 name
= g
['original_name']
535 # Get list followers or friends
537 target
= g
['stuff'].split()[0]
539 printNicely(red('Omg some syntax is wrong.'))
541 d
= {'fl': 'followers', 'fr': 'friends'}
545 while next_cursor
!= 0:
546 list = getattr(t
, d
[target
]).list(
550 include_entities
=False,
552 for u
in list['users']:
553 rel
[u
['name']] = '@' + u
['screen_name']
554 next_cursor
= list['next_cursor']
556 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
558 user
= ' ' + cycle_color(name
)
559 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
565 Inbox direct messages
567 t
= Twitter(auth
=authen())
568 num
= c
['MESSAGES_DISPLAY']
570 if g
['stuff'].isdigit():
573 # Max message per page is 20 so we have to loop
575 rel
= rel
+ t
.direct_messages(
578 include_entities
=False,
583 rel
= rel
+ t
.direct_messages(
586 include_entities
=False,
590 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
591 for m
in reversed(rel
):
600 t
= Twitter(auth
=authen())
601 num
= c
['MESSAGES_DISPLAY']
603 if g
['stuff'].isdigit():
604 num
= int(g
['stuff'])
606 # Max message per page is 20 so we have to loop
608 rel
= rel
+ t
.direct_messages
.sent(
611 include_entities
=False,
616 rel
= rel
+ t
.direct_messages
.sent(
619 include_entities
=False,
623 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
624 for m
in reversed(rel
):
633 t
= Twitter(auth
=authen())
635 id = int(g
['stuff'].split()[0])
637 printNicely(red('Sorry I can\'t understand.'))
638 mid
= c
['message_dict'][id]
639 t
.direct_messages
.destroy(id=mid
)
640 printNicely(green('Message deleted.'))
645 Show profile of a specific user
647 t
= Twitter(auth
=authen())
648 screen_name
= g
['stuff'].split()[0]
649 if screen_name
.startswith('@'):
652 screen_name
=screen_name
[1:],
653 include_entities
=False)
656 printNicely(red('Omg no user.'))
658 printNicely(red('A name should begin with a \'@\''))
665 t
= Twitter(auth
=authen())
666 screen_name
= g
['stuff'].split()[0]
667 if screen_name
.startswith('@'):
668 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
669 printNicely(green('You are following ' + screen_name
+ ' now!'))
671 printNicely(red('A name should begin with a \'@\''))
678 t
= Twitter(auth
=authen())
679 screen_name
= g
['stuff'].split()[0]
680 if screen_name
.startswith('@'):
681 t
.friendships
.destroy(
682 screen_name
=screen_name
[1:],
683 include_entities
=False)
684 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
686 printNicely(red('A name should begin with a \'@\''))
693 t
= Twitter(auth
=authen())
695 screen_name
= g
['stuff'].split()[0]
697 printNicely(red('A name should be specified. '))
699 if screen_name
.startswith('@'):
701 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
702 if isinstance(rel
, dict):
703 printNicely(green(screen_name
+ ' is muted.'))
704 c
['IGNORE_LIST'] += [unc(screen_name
)]
705 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
707 printNicely(red(rel
))
709 printNicely(red('Something is wrong, can not mute now :('))
711 printNicely(red('A name should begin with a \'@\''))
718 t
= Twitter(auth
=authen())
720 screen_name
= g
['stuff'].split()[0]
722 printNicely(red('A name should be specified. '))
724 if screen_name
.startswith('@'):
726 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
727 if isinstance(rel
, dict):
728 printNicely(green(screen_name
+ ' is unmuted.'))
729 c
['IGNORE_LIST'].remove(screen_name
)
731 printNicely(red(rel
))
733 printNicely(red('Maybe you are not muting this person ?'))
735 printNicely(red('A name should begin with a \'@\''))
742 # Get dict of muting users
743 md
= build_mute_dict(dict_data
=True)
744 printNicely('All: ' + str(len(md
)) + ' people.')
746 user
= ' ' + cycle_color(md
[name
])
747 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
749 # Update from Twitter
750 c
['IGNORE_LIST'] = [n
for n
in md
]
757 t
= Twitter(auth
=authen())
758 screen_name
= g
['stuff'].split()[0]
759 if screen_name
.startswith('@'):
761 screen_name
=screen_name
[1:],
762 include_entities
=False,
764 printNicely(green('You blocked ' + screen_name
+ '.'))
766 printNicely(red('A name should begin with a \'@\''))
773 t
= Twitter(auth
=authen())
774 screen_name
= g
['stuff'].split()[0]
775 if screen_name
.startswith('@'):
777 screen_name
=screen_name
[1:],
778 include_entities
=False,
780 printNicely(green('Unblock ' + screen_name
+ ' success!'))
782 printNicely(red('A name should begin with a \'@\''))
787 Report a user as a spam account
789 t
= Twitter(auth
=authen())
790 screen_name
= g
['stuff'].split()[0]
791 if screen_name
.startswith('@'):
793 screen_name
=screen_name
[1:])
794 printNicely(green('You reported ' + screen_name
+ '.'))
796 printNicely(red('Sorry I can\'t understand.'))
804 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
805 # Get list name and owner
807 owner
, slug
= list_name
.split('/')
808 if slug
.startswith('@'):
813 light_magenta('List name should follow "@owner/list_name" format.'))
814 raise Exception('Wrong list name')
821 rel
= t
.lists
.list(screen_name
=g
['original_name'])
825 printNicely(light_magenta('You belong to no lists :)'))
832 owner
, slug
= get_slug()
833 res
= t
.lists
.statuses(
835 owner_screen_name
=owner
,
837 include_entities
=False)
847 owner
, slug
= get_slug()
851 while next_cursor
!= 0:
854 owner_screen_name
=owner
,
856 include_entities
=False)
858 rel
[u
['name']] = '@' + u
['screen_name']
859 next_cursor
= m
['next_cursor']
860 printNicely('All: ' + str(len(rel
)) + ' members.')
862 user
= ' ' + cycle_color(name
)
863 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
867 def list_subscribers(t
):
871 owner
, slug
= get_slug()
875 while next_cursor
!= 0:
876 m
= t
.lists
.subscribers(
878 owner_screen_name
=owner
,
880 include_entities
=False)
882 rel
[u
['name']] = '@' + u
['screen_name']
883 next_cursor
= m
['next_cursor']
884 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
886 user
= ' ' + cycle_color(name
)
887 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
893 Add specific user to a list
895 owner
, slug
= get_slug()
897 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
898 if user_name
.startswith('@'):
899 user_name
= user_name
[1:]
901 t
.lists
.members
.create(
903 owner_screen_name
=owner
,
904 screen_name
=user_name
)
905 printNicely(green('Added.'))
907 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
912 Remove specific user from a list
914 owner
, slug
= get_slug()
916 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
917 if user_name
.startswith('@'):
918 user_name
= user_name
[1:]
920 t
.lists
.members
.destroy(
922 owner_screen_name
=owner
,
923 screen_name
=user_name
)
924 printNicely(green('Gone.'))
926 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
929 def list_subscribe(t
):
933 owner
, slug
= get_slug()
936 t
.lists
.subscribers
.create(
938 owner_screen_name
=owner
)
939 printNicely(green('Done.'))
942 light_magenta('I\'m sorry you can not subscribe to this list.'))
945 def list_unsubscribe(t
):
949 owner
, slug
= get_slug()
952 t
.lists
.subscribers
.destroy(
954 owner_screen_name
=owner
)
955 printNicely(green('Done.'))
958 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
967 while next_cursor
!= 0:
968 res
= t
.lists
.ownerships(
969 screen_name
=g
['original_name'],
972 next_cursor
= res
['next_cursor']
976 printNicely(light_magenta('You own no lists :)'))
983 name
= raw_input(light_magenta('New list\'s name: '))
984 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
985 description
= raw_input(light_magenta('New list\'s description: '))
990 description
=description
)
991 printNicely(green(name
+ ' list is created.'))
993 printNicely(red('Oops something is wrong with Twitter :('))
1000 slug
= raw_input(light_magenta('Your list that you want to update: '))
1001 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1002 mode
= raw_input(light_magenta('Update mode (public/private): '))
1003 description
= raw_input(light_magenta('Update description: '))
1007 slug
='-'.join(slug
.split()),
1008 owner_screen_name
=g
['original_name'],
1011 description
=description
)
1015 owner_screen_name
=g
['original_name'],
1017 description
=description
)
1018 printNicely(green(slug
+ ' list is updated.'))
1020 printNicely(red('Oops something is wrong with Twitter :('))
1027 slug
= raw_input(light_magenta('Your list that you want to update: '))
1030 slug
='-'.join(slug
.split()),
1031 owner_screen_name
=g
['original_name'])
1032 printNicely(green(slug
+ ' list is deleted.'))
1034 printNicely(red('Oops something is wrong with Twitter :('))
1041 t
= Twitter(auth
=authen())
1042 # List all lists or base on action
1044 g
['list_action'] = g
['stuff'].split()[0]
1051 'all_mem': list_members
,
1052 'all_sub': list_subscribers
,
1055 'sub': list_subscribe
,
1056 'unsub': list_unsubscribe
,
1059 'update': list_update
,
1063 return action_ary
[g
['list_action']](t
)
1065 printNicely(red('Please try again.'))
1070 Unix's command `cal`
1073 rel
= os
.popen('cal').read().split('\n')
1076 show_calendar(month
, date
, rel
)
1081 Browse and change config
1083 all_config
= get_all_config()
1084 g
['stuff'] = g
['stuff'].strip()
1087 for k
in all_config
:
1089 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1091 guide
= 'Detailed explanation can be found at ' + \
1092 color_func(c
['TWEET']['link'])(
1093 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1095 # Print specific config
1096 elif len(g
['stuff'].split()) == 1:
1097 if g
['stuff'] in all_config
:
1100 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1103 printNicely(red('No such config key.'))
1104 # Print specific config's default value
1105 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1106 key
= g
['stuff'].split()[0]
1108 value
= get_default_config(key
)
1109 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1111 except Exception as e
:
1113 # Delete specific config key in config file
1114 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1115 key
= g
['stuff'].split()[0]
1118 printNicely(green('Config key is dropped.'))
1119 except Exception as e
:
1121 # Set specific config
1122 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1123 key
= g
['stuff'].split()[0]
1124 value
= g
['stuff'].split()[-1]
1125 if key
== 'THEME' and not validate_theme(value
):
1126 printNicely(red('Invalid theme\'s value.'))
1129 set_config(key
, value
)
1130 # Apply theme immediately
1132 c
['THEME'] = reload_theme(value
, c
['THEME'])
1133 g
['decorated_name'] = lambda x
: color_func(
1134 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1136 printNicely(green('Updated successfully.'))
1137 except Exception as e
:
1140 printNicely(light_magenta('Sorry I can\'s understand.'))
1145 List and change theme
1149 for theme
in g
['themes']:
1150 line
= light_magenta(theme
)
1151 if c
['THEME'] == theme
:
1152 line
= ' ' * 2 + light_yellow('* ') + line
1154 line
= ' ' * 4 + line
1160 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1161 # Redefine decorated_name
1162 g
['decorated_name'] = lambda x
: color_func(
1163 c
['DECORATED_NAME'])(
1165 printNicely(green('Theme changed.'))
1167 printNicely(red('No such theme exists.'))
1170 def help_discover():
1175 # Discover the world
1177 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1178 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1179 'You can try ' + light_green('trend US') + ' or ' + \
1180 light_green('trend JP Tokyo') + '.\n'
1181 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1182 light_green('home 7') + ' will show 7 tweets.\n'
1183 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1184 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1185 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1186 magenta('@mdo') + '.\n'
1187 usage
+= s
* 2 + light_green('view @mdo') + \
1188 ' will show ' + magenta('@mdo') + '\'s home.\n'
1189 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1190 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1191 'Search can be performed with or without hashtag.\n'
1202 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1203 usage
+= s
* 2 + light_green('t oops ') + \
1204 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1206 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1207 light_yellow('[id=12]') + '.\n'
1209 light_green('quote 12 ') + ' will quote the tweet with ' + \
1210 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1211 'the quote will be canceled.\n'
1213 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1214 light_yellow('[id=12]') + '.\n'
1215 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1216 light_yellow('oops') + '" to tweet with ' + \
1217 light_yellow('[id=12]') + '.\n'
1219 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1220 light_yellow('[id=12]') + '.\n'
1222 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1223 light_yellow('[id=12]') + '.\n'
1225 light_green('del 12 ') + ' will delete tweet with ' + \
1226 light_yellow('[id=12]') + '.\n'
1227 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1228 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1229 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1230 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1234 def help_messages():
1241 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1242 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1243 light_green('inbox 7') + ' will show newest 7 messages.\n'
1244 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1245 light_green('sent 7') + ' will show newest 7 messages.\n'
1246 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1247 magenta('@dtvd88') + '.\n'
1248 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1249 light_yellow('[message_id=5]') + '.\n'
1253 def help_friends_and_followers():
1255 Friends and Followers
1258 # Follower and following
1260 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1262 light_green('ls fl') + \
1263 ' will list all followers (people who are following you).\n'
1265 light_green('ls fr') + \
1266 ' will list all friends (people who you are following).\n'
1267 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1268 magenta('@dtvd88') + '.\n'
1269 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1270 magenta('@dtvd88') + '.\n'
1271 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1272 magenta('@dtvd88') + '.\n'
1273 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1274 magenta('@dtvd88') + '.\n'
1275 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1276 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1277 magenta('@dtvd88') + '.\n'
1278 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1279 magenta('@dtvd88') + '.\n'
1280 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1281 magenta('@dtvd88') + ' as a spam account.\n'
1292 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1293 usage
+= s
* 2 + light_green('list') + \
1294 ' will show all lists you are belong to.\n'
1295 usage
+= s
* 2 + light_green('list home') + \
1296 ' will show timeline of list. You will be asked for list\'s name.\n'
1297 usage
+= s
* 2 + light_green('list all_mem') + \
1298 ' will show list\'s all members.\n'
1299 usage
+= s
* 2 + light_green('list all_sub') + \
1300 ' will show list\'s all subscribers.\n'
1301 usage
+= s
* 2 + light_green('list add') + \
1302 ' will add specific person to a list owned by you.' + \
1303 ' You will be asked for list\'s name and person\'s name.\n'
1304 usage
+= s
* 2 + light_green('list rm') + \
1305 ' will remove specific person from a list owned by you.' + \
1306 ' You will be asked for list\'s name and person\'s name.\n'
1307 usage
+= s
* 2 + light_green('list sub') + \
1308 ' will subscribe you to a specific list.\n'
1309 usage
+= s
* 2 + light_green('list unsub') + \
1310 ' will unsubscribe you from a specific list.\n'
1311 usage
+= s
* 2 + light_green('list own') + \
1312 ' will show all list owned by you.\n'
1313 usage
+= s
* 2 + light_green('list new') + \
1314 ' will create a new list.\n'
1315 usage
+= s
* 2 + light_green('list update') + \
1316 ' will update a list owned by you.\n'
1317 usage
+= s
* 2 + light_green('list del') + \
1318 ' will delete a list owned by you.\n'
1329 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1330 usage
+= s
* 2 + light_green('switch public #AKB') + \
1331 ' will switch to public stream and follow "' + \
1332 light_yellow('AKB') + '" keyword.\n'
1333 usage
+= s
* 2 + light_green('switch mine') + \
1334 ' will switch to your personal stream.\n'
1335 usage
+= s
* 2 + light_green('switch mine -f ') + \
1336 ' will prompt to enter the filter.\n'
1337 usage
+= s
* 3 + light_yellow('Only nicks') + \
1338 ' filter will decide nicks will be INCLUDE ONLY.\n'
1339 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1340 ' filter will decide nicks will be EXCLUDE.\n'
1341 usage
+= s
* 2 + light_green('switch mine -d') + \
1342 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1351 h
, w
= os
.popen('stty size', 'r').read().split()
1354 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1355 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1356 usage
+= s
+ 'You are ' + \
1357 light_yellow('already') + ' on your personal stream.\n'
1358 usage
+= s
+ 'Any update from Twitter will show up ' + \
1359 light_yellow('immediately') + '.\n'
1360 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1361 # Twitter help section
1363 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1364 usage
+= s
* 2 + light_green('h discover') + \
1365 ' will show help for discover commands.\n'
1366 usage
+= s
* 2 + light_green('h tweets') + \
1367 ' will show help for tweets commands.\n'
1368 usage
+= s
* 2 + light_green('h messages') + \
1369 ' will show help for messages commands.\n'
1370 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1371 ' will show help for friends and followers commands.\n'
1372 usage
+= s
* 2 + light_green('h list') + \
1373 ' will show help for list commands.\n'
1374 usage
+= s
* 2 + light_green('h stream') + \
1375 ' will show help for stream commands.\n'
1378 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1379 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1380 'will be evaluate by Python interpreter.\n'
1381 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1382 ' for current month.\n'
1385 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1386 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1387 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1388 ' theme immediately.\n'
1389 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1391 light_green('config ASCII_ART') + ' will output current value of ' +\
1392 light_yellow('ASCII_ART') + ' config key.\n'
1394 light_green('config TREND_MAX default') + ' will output default value of ' + \
1395 light_yellow('TREND_MAX') + ' config key.\n'
1397 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1398 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1400 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1401 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1402 light_yellow('True') + '.\n'
1405 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1406 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1407 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1408 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1409 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1410 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1413 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1414 usage
+= s
+ 'Have fun and hang tight! \n'
1417 'discover': help_discover
,
1418 'tweets': help_tweets
,
1419 'messages': help_messages
,
1420 'friends_and_followers': help_friends_and_followers
,
1422 'stream': help_stream
,
1427 lambda: printNicely(red('No such command.'))
1435 Pause stream display
1438 printNicely(green('Stream is paused'))
1446 printNicely(green('Stream is running back now'))
1462 printNicely(green('See you next time :)'))
1470 Reset prefix of line
1473 if c
.get('USER_JSON_ERROR'):
1474 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1475 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1477 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1480 printNicely(str(eval(g
['cmd'])))
1528 # Handle function set
1576 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1581 Listen to user's input
1586 ['public', 'mine'], # switch
1601 ['image'], # show image
1603 ['fl', 'fr'], # list
1630 [key
for key
in dict(get_all_config())], # config
1631 g
['themes'], # theme
1636 'friends_and_followers',
1646 init_interactive_shell(d
)
1652 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1655 # Save cmd to compare with readline buffer
1656 g
['cmd'] = line
.strip()
1657 # Get short cmd to pass to handle function
1659 cmd
= line
.split()[0]
1663 # Lock the semaphore
1665 # Save cmd to global variable and call process
1666 g
['stuff'] = ' '.join(line
.split()[1:])
1667 # Process the command
1670 if cmd
in ['switch', 't', 'rt', 'rep']:
1674 # Release the semaphore lock
1677 printNicely(red('OMG something is wrong with Twitter right now.'))
1680 def stream(domain
, args
, name
='Rainbow Stream'):
1686 c
['USER_DOMAIN']: name
,
1687 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1688 c
['SITE_DOMAIN']: name
,
1691 ascii_art(art_dict
[domain
])
1692 # These arguments are optional:
1694 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1695 block
=not args
.no_block
,
1696 heartbeat_timeout
=args
.heartbeat_timeout
)
1699 if args
.track_keywords
:
1700 query_args
['track'] = args
.track_keywords
1702 stream
= TwitterStream(
1707 if domain
== c
['USER_DOMAIN']:
1708 tweet_iter
= stream
.user(**query_args
)
1709 elif domain
== c
['SITE_DOMAIN']:
1710 tweet_iter
= stream
.site(**query_args
)
1712 if args
.track_keywords
:
1713 tweet_iter
= stream
.statuses
.filter(**query_args
)
1715 tweet_iter
= stream
.statuses
.sample()
1716 # Block new stream until other one exits
1717 StreamLock
.acquire()
1718 g
['stream_stop'] = False
1719 for tweet
in tweet_iter
:
1721 printNicely("-- None --")
1722 elif tweet
is Timeout
:
1723 if(g
['stream_stop']):
1724 StreamLock
.release()
1726 elif tweet
is HeartbeatTimeout
:
1727 printNicely("-- Heartbeat Timeout --")
1728 elif tweet
is Hangup
:
1729 printNicely("-- Hangup --")
1730 elif tweet
.get('text'):
1733 keyword
=args
.track_keywords
,
1734 check_semaphore
=True,
1738 # Current readline buffer
1739 current_buffer
= readline
.get_line_buffer().strip()
1740 # There is an unexpected behaviour in MacOSX readline + Python 2:
1741 # after completely delete a word after typing it,
1742 # somehow readline buffer still contains
1743 # the 1st character of that word
1744 if current_buffer
and g
['cmd'] != current_buffer
:
1746 g
['decorated_name'](c
['PREFIX']) + unc(current_buffer
))
1748 elif not c
['HIDE_PROMPT']:
1749 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1751 elif tweet
.get('direct_message'):
1752 print_message(tweet
['direct_message'], check_semaphore
=True)
1753 except TwitterHTTPError
:
1756 magenta("We have maximum connection problem with twitter'stream API right now :("))
1764 args
= parse_arguments()
1767 except TwitterHTTPError
:
1770 magenta("We have connection problem with twitter'stream API right now :("))
1771 printNicely(magenta("Let's try again later."))
1774 # Spawn stream thread
1775 th
= threading
.Thread(
1780 g
['original_name']))
1783 # Start listen process