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()
78 def parse_arguments():
82 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
86 help='Timeout for the stream (seconds).')
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
96 help='Set stream to non-blocking.')
100 help='Search the stream for specific text.')
104 help='Filter specific screen_name.')
108 help='Ignore specific screen_name.')
113 help='Display all image on terminal.')
114 return parser
.parse_args()
119 Authenticate with Twitter OAuth
121 # When using rainbow stream you must authorize.
122 twitter_credential
= os
.environ
.get(
126 '')) + os
.sep
+ '.rainbow_oauth'
127 if not os
.path
.exists(twitter_credential
):
128 oauth_dance("Rainbow Stream",
132 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
145 ctrl_c_handler
= lambda signum
, frame
: quit()
146 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
148 t
= Twitter(auth
=authen())
149 name
= '@' + t
.account
.verify_credentials()['screen_name']
150 if not get_config('PREFIX'):
151 set_config('PREFIX', name
)
152 g
['original_name'] = name
[1:]
153 g
['decorated_name'] = lambda x
: color_func(
154 c
['DECORATED_NAME'])(
157 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
158 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
161 g
['OSX_readline_bug'] = False
162 g
['previous_cmd'] = ''
166 # Init tweet dict and message dict
168 c
['message_dict'] = []
170 c
['IMAGE_ON_TERM'] = args
.image_on_term
178 target
= g
['stuff'].split()[0]
180 args
= parse_arguments()
182 if g
['stuff'].split()[-1] == '-f':
183 guide
= 'To ignore an option, just hit Enter key.'
184 printNicely(light_magenta(guide
))
185 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
186 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
187 args
.filter = filter(None, only
.split(','))
188 args
.ignore
= filter(None, ignore
.split(','))
189 elif g
['stuff'].split()[-1] == '-d':
190 args
.filter = c
['ONLY_LIST']
191 args
.ignore
= c
['IGNORE_LIST']
193 printNicely(red('Sorry, wrong format.'))
196 if target
== 'public':
197 keyword
= g
['stuff'].split()[1]
198 if keyword
[0] == '#':
199 keyword
= keyword
[1:]
201 g
['stream_stop'] = True
202 args
.track_keywords
= keyword
204 th
= threading
.Thread(
212 elif target
== 'mine':
214 g
['stream_stop'] = True
216 th
= threading
.Thread(
226 printNicely(cyan('Only: ' + str(args
.filter)))
228 printNicely(red('Ignore: ' + str(args
.ignore
)))
231 printNicely(red('Sorry I can\'t understand.'))
238 t
= Twitter(auth
=authen())
239 # Get country and town
241 country
= g
['stuff'].split()[0]
245 town
= g
['stuff'].split()[1]
248 avail
= t
.trends
.available()
251 trends
= t
.trends
.place(_id
=1)[0]['trends']
254 for location
in avail
:
255 # Search for country and Town
257 if location
['countryCode'] == country \
258 and location
['placeType']['name'] == 'Town' \
259 and location
['name'] == town
:
260 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
262 # Search for country only
264 if location
['countryCode'] == country \
265 and location
['placeType']['name'] == 'Country':
266 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
274 t
= Twitter(auth
=authen())
275 num
= c
['HOME_TWEET_NUM']
276 if g
['stuff'].isdigit():
277 num
= int(g
['stuff'])
278 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
287 t
= Twitter(auth
=authen())
288 user
= g
['stuff'].split()[0]
291 num
= int(g
['stuff'].split()[1])
293 num
= c
['HOME_TWEET_NUM']
294 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
298 printNicely(red('A name should begin with a \'@\''))
305 t
= Twitter(auth
=authen())
306 num
= c
['HOME_TWEET_NUM']
307 if g
['stuff'].isdigit():
308 num
= int(g
['stuff'])
309 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
318 t
= Twitter(auth
=authen())
319 t
.statuses
.update(status
=g
['stuff'])
326 t
= Twitter(auth
=authen())
328 id = int(g
['stuff'].split()[0])
330 printNicely(red('Sorry I can\'t understand.'))
332 tid
= c
['tweet_dict'][id]
333 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
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 screen_name
= tweet
['user']['screen_name']
350 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
351 quote
= quote
.encode('utf8')
352 notice
= light_magenta('Compose mode ')
353 notice
+= light_yellow('(Enter nothing will cancel the quote)')
354 notice
+= light_magenta(':')
356 extra
= raw_input(quote
)
358 t
.statuses
.update(status
=quote
+ extra
)
360 printNicely(light_magenta('No text added.'))
367 t
= Twitter(auth
=authen())
370 id = int(g
['stuff'].split()[0])
372 printNicely(red('Sorry I can\'t understand.'))
374 tid
= c
['tweet_dict'][id]
375 # Get display num if exist
377 num
= int(g
['stuff'].split()[1])
379 num
= c
['RETWEETS_SHOW_NUM']
380 # Get result and display
381 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
383 printNicely(magenta('This tweet has no retweet.'))
385 for tweet
in reversed(rt_ary
):
394 t
= Twitter(auth
=authen())
396 id = int(g
['stuff'].split()[0])
398 printNicely(red('Sorry I can\'t understand.'))
400 tid
= c
['tweet_dict'][id]
401 t
.favorites
.create(_id
=tid
, include_entities
=False)
402 printNicely(green('Favorited.'))
403 draw(t
.statuses
.show(id=tid
))
411 t
= Twitter(auth
=authen())
413 id = int(g
['stuff'].split()[0])
415 printNicely(red('Sorry I can\'t understand.'))
417 tid
= c
['tweet_dict'][id]
418 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
419 status
= ' '.join(g
['stuff'].split()[1:])
420 status
= '@' + user
+ ' ' + status
.decode('utf-8')
421 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
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
.statuses
.destroy(id=tid
)
436 printNicely(green('Okay it\'s gone.'))
443 t
= Twitter(auth
=authen())
445 id = int(g
['stuff'].split()[0])
447 printNicely(red('Sorry I can\'t understand.'))
449 tid
= c
['tweet_dict'][id]
450 t
.favorites
.destroy(_id
=tid
)
451 printNicely(green('Okay it\'s unfavorited.'))
452 draw(t
.statuses
.show(id=tid
))
460 t
= Twitter(auth
=authen())
461 g
['stuff'] = g
['stuff'].strip()
462 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
464 printNicely('Newest tweets:')
465 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
470 printNicely(magenta('I\'m afraid there is no result'))
475 Send a direct message
477 t
= Twitter(auth
=authen())
478 user
= g
['stuff'].split()[0]
479 if user
[0].startswith('@'):
481 content
= g
['stuff'].split()[1]
483 printNicely(red('Sorry I can\'t understand.'))
484 t
.direct_messages
.new(
485 screen_name
=user
[1:],
488 printNicely(green('Message sent.'))
490 printNicely(red('A name should begin with a \'@\''))
497 t
= Twitter(auth
=authen())
499 target
= g
['stuff'].split()[0]
500 if target
!= 'image':
502 id = int(g
['stuff'].split()[1])
503 tid
= c
['tweet_dict'][id]
504 tweet
= t
.statuses
.show(id=tid
)
505 media
= tweet
['entities']['media']
507 res
= requests
.get(m
['media_url'])
508 img
= Image
.open(BytesIO(res
.content
))
511 printNicely(red('Sorry I can\'t show this image.'))
518 t
= Twitter(auth
=authen())
520 if not g
['stuff'].isdigit():
522 tid
= c
['tweet_dict'][int(g
['stuff'])]
523 tweet
= t
.statuses
.show(id=tid
)
525 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
527 printNicely(light_magenta('No url here @.@!'))
529 for link
in link_ary
:
530 webbrowser
.open(link
)
532 printNicely(red('Sorry I can\'t open url in this tweet.'))
537 List friends for followers
539 t
= Twitter(auth
=authen())
542 name
= g
['stuff'].split()[1]
543 if name
.startswith('@'):
546 printNicely(red('A name should begin with a \'@\''))
547 raise Exception('Invalid name')
549 name
= g
['original_name']
550 # Get list followers or friends
552 target
= g
['stuff'].split()[0]
554 printNicely(red('Omg some syntax is wrong.'))
556 d
= {'fl': 'followers', 'fr': 'friends'}
560 while next_cursor
!= 0:
561 list = getattr(t
, d
[target
]).list(
565 include_entities
=False,
567 for u
in list['users']:
568 rel
[u
['name']] = '@' + u
['screen_name']
569 next_cursor
= list['next_cursor']
571 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
573 user
= ' ' + cycle_color(name
)
574 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
580 Inbox direct messages
582 t
= Twitter(auth
=authen())
583 num
= c
['MESSAGES_DISPLAY']
585 if g
['stuff'].isdigit():
588 # Max message per page is 20 so we have to loop
590 rel
= rel
+ t
.direct_messages(
593 include_entities
=False,
598 rel
= rel
+ t
.direct_messages(
601 include_entities
=False,
605 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
606 for m
in reversed(rel
):
615 t
= Twitter(auth
=authen())
616 num
= c
['MESSAGES_DISPLAY']
618 if g
['stuff'].isdigit():
619 num
= int(g
['stuff'])
621 # Max message per page is 20 so we have to loop
623 rel
= rel
+ t
.direct_messages
.sent(
626 include_entities
=False,
631 rel
= rel
+ t
.direct_messages
.sent(
634 include_entities
=False,
638 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
639 for m
in reversed(rel
):
648 t
= Twitter(auth
=authen())
650 id = int(g
['stuff'].split()[0])
652 printNicely(red('Sorry I can\'t understand.'))
653 mid
= c
['message_dict'][id]
654 t
.direct_messages
.destroy(id=mid
)
655 printNicely(green('Message deleted.'))
660 Show profile of a specific user
662 t
= Twitter(auth
=authen())
663 screen_name
= g
['stuff'].split()[0]
664 if screen_name
.startswith('@'):
667 screen_name
=screen_name
[1:],
668 include_entities
=False)
671 printNicely(red('Omg no user.'))
673 printNicely(red('A name should begin with a \'@\''))
680 t
= Twitter(auth
=authen())
681 screen_name
= g
['stuff'].split()[0]
682 if screen_name
.startswith('@'):
683 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
684 printNicely(green('You are following ' + screen_name
+ ' now!'))
686 printNicely(red('A name should begin with a \'@\''))
693 t
= Twitter(auth
=authen())
694 screen_name
= g
['stuff'].split()[0]
695 if screen_name
.startswith('@'):
696 t
.friendships
.destroy(
697 screen_name
=screen_name
[1:],
698 include_entities
=False)
699 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
701 printNicely(red('A name should begin with a \'@\''))
708 t
= Twitter(auth
=authen())
710 screen_name
= g
['stuff'].split()[0]
712 printNicely(red('A name should be specified. '))
714 if screen_name
.startswith('@'):
715 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
716 if isinstance(rel
, dict):
717 printNicely(green(screen_name
+ ' is muted.'))
719 printNicely(red(rel
))
721 printNicely(red('A name should begin with a \'@\''))
728 t
= Twitter(auth
=authen())
730 screen_name
= g
['stuff'].split()[0]
732 printNicely(red('A name should be specified. '))
734 if screen_name
.startswith('@'):
735 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
736 if isinstance(rel
, dict):
737 printNicely(green(screen_name
+ ' is unmuted.'))
739 printNicely(red(rel
))
741 printNicely(red('A name should begin with a \'@\''))
748 t
= Twitter(auth
=authen())
753 while next_cursor
!= 0:
754 list = t
.mutes
.users
.list(
755 screen_name
=g
['original_name'],
758 include_entities
=False,
760 for u
in list['users']:
761 rel
[u
['name']] = '@' + u
['screen_name']
762 next_cursor
= list['next_cursor']
764 printNicely('All: ' + str(len(rel
)) + ' people.')
766 user
= ' ' + cycle_color(name
)
767 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
775 t
= Twitter(auth
=authen())
776 screen_name
= g
['stuff'].split()[0]
777 if screen_name
.startswith('@'):
779 screen_name
=screen_name
[1:],
780 include_entities
=False,
782 printNicely(green('You blocked ' + screen_name
+ '.'))
784 printNicely(red('A name should begin with a \'@\''))
791 t
= Twitter(auth
=authen())
792 screen_name
= g
['stuff'].split()[0]
793 if screen_name
.startswith('@'):
795 screen_name
=screen_name
[1:],
796 include_entities
=False,
798 printNicely(green('Unblock ' + screen_name
+ ' success!'))
800 printNicely(red('A name should begin with a \'@\''))
805 Report a user as a spam account
807 t
= Twitter(auth
=authen())
808 screen_name
= g
['stuff'].split()[0]
809 if screen_name
.startswith('@'):
811 screen_name
=screen_name
[1:])
812 printNicely(green('You reported ' + screen_name
+ '.'))
814 printNicely(red('Sorry I can\'t understand.'))
822 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
823 # Get list name and owner
825 owner
, slug
= list_name
.split('/')
826 if slug
.startswith('@'):
831 light_magenta('List name should follow "@owner/list_name" format.'))
832 raise Exception('Wrong list name')
839 rel
= t
.lists
.list(screen_name
=g
['original_name'])
843 printNicely(light_magenta('You belong to no lists :)'))
850 owner
, slug
= get_slug()
851 res
= t
.lists
.statuses(
853 owner_screen_name
=owner
,
855 include_entities
=False)
865 owner
, slug
= get_slug()
869 while next_cursor
!= 0:
872 owner_screen_name
=owner
,
874 include_entities
=False)
876 rel
[u
['name']] = '@' + u
['screen_name']
877 next_cursor
= m
['next_cursor']
878 printNicely('All: ' + str(len(rel
)) + ' members.')
880 user
= ' ' + cycle_color(name
)
881 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
885 def list_subscribers(t
):
889 owner
, slug
= get_slug()
893 while next_cursor
!= 0:
894 m
= t
.lists
.subscribers(
896 owner_screen_name
=owner
,
898 include_entities
=False)
900 rel
[u
['name']] = '@' + u
['screen_name']
901 next_cursor
= m
['next_cursor']
902 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
904 user
= ' ' + cycle_color(name
)
905 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
911 Add specific user to a list
913 owner
, slug
= get_slug()
915 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
916 if user_name
.startswith('@'):
917 user_name
= user_name
[1:]
919 t
.lists
.members
.create(
921 owner_screen_name
=owner
,
922 screen_name
=user_name
)
923 printNicely(green('Added.'))
925 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
930 Remove specific user from a list
932 owner
, slug
= get_slug()
934 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
935 if user_name
.startswith('@'):
936 user_name
= user_name
[1:]
938 t
.lists
.members
.destroy(
940 owner_screen_name
=owner
,
941 screen_name
=user_name
)
942 printNicely(green('Gone.'))
944 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
947 def list_subscribe(t
):
951 owner
, slug
= get_slug()
954 t
.lists
.subscribers
.create(
956 owner_screen_name
=owner
)
957 printNicely(green('Done.'))
960 light_magenta('I\'m sorry you can not subscribe to this list.'))
963 def list_unsubscribe(t
):
967 owner
, slug
= get_slug()
970 t
.lists
.subscribers
.destroy(
972 owner_screen_name
=owner
)
973 printNicely(green('Done.'))
976 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
985 while next_cursor
!= 0:
986 res
= t
.lists
.ownerships(
987 screen_name
=g
['original_name'],
990 next_cursor
= res
['next_cursor']
994 printNicely(light_magenta('You own no lists :)'))
1001 name
= raw_input(light_magenta('New list\'s name: '))
1002 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1003 description
= raw_input(light_magenta('New list\'s description: '))
1008 description
=description
)
1009 printNicely(green(name
+ ' list is created.'))
1011 printNicely(red('Oops something is wrong with Twitter :('))
1018 slug
= raw_input(light_magenta('Your list that you want to update: '))
1019 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1020 mode
= raw_input(light_magenta('Update mode (public/private): '))
1021 description
= raw_input(light_magenta('Update description: '))
1025 slug
='-'.join(slug
.split()),
1026 owner_screen_name
=g
['original_name'],
1029 description
=description
)
1033 owner_screen_name
=g
['original_name'],
1035 description
=description
)
1036 printNicely(green(slug
+ ' list is updated.'))
1038 printNicely(red('Oops something is wrong with Twitter :('))
1045 slug
= raw_input(light_magenta('Your list that you want to update: '))
1048 slug
='-'.join(slug
.split()),
1049 owner_screen_name
=g
['original_name'])
1050 printNicely(green(slug
+ ' list is deleted.'))
1052 printNicely(red('Oops something is wrong with Twitter :('))
1059 t
= Twitter(auth
=authen())
1060 # List all lists or base on action
1062 g
['list_action'] = g
['stuff'].split()[0]
1069 'all_mem': list_members
,
1070 'all_sub': list_subscribers
,
1073 'sub': list_subscribe
,
1074 'unsub': list_unsubscribe
,
1077 'update': list_update
,
1081 return action_ary
[g
['list_action']](t
)
1083 printNicely(red('Please try again.'))
1088 Unix's command `cal`
1091 rel
= os
.popen('cal').read().split('\n')
1094 show_calendar(month
, date
, rel
)
1099 Browse and change config
1101 all_config
= get_all_config()
1102 g
['stuff'] = g
['stuff'].strip()
1105 for k
in all_config
:
1107 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1109 guide
= 'Detailed explanation can be found at ' + \
1110 color_func(c
['TWEET']['link'])(
1111 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1113 # Print specific config
1114 elif len(g
['stuff'].split()) == 1:
1115 if g
['stuff'] in all_config
:
1118 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1121 printNicely(red('No such config key.'))
1122 # Print specific config's default value
1123 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1124 key
= g
['stuff'].split()[0]
1126 value
= get_default_config(key
)
1127 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1131 light_magenta('This config key does not exist in default.'))
1132 # Delete specific config key in config file
1133 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1134 key
= g
['stuff'].split()[0]
1137 printNicely(green('Config key is dropped.'))
1139 printNicely(red('No such config key.'))
1140 # Set specific config
1141 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1142 key
= g
['stuff'].split()[0]
1143 value
= g
['stuff'].split()[-1]
1144 if key
== 'THEME' and not validate_theme(value
):
1145 printNicely(red('Invalid theme\'s value.'))
1148 set_config(key
, value
)
1149 # Apply theme immediately
1151 c
['THEME'] = reload_theme(value
, c
['THEME'])
1152 g
['decorated_name'] = lambda x
: color_func(
1153 c
['DECORATED_NAME'])(
1155 printNicely(green('Updated successfully.'))
1157 printNicely(light_magenta('Not valid value.'))
1161 printNicely(light_magenta('Sorry I can\'s understand.'))
1166 List and change theme
1170 for theme
in g
['themes']:
1171 line
= light_magenta(theme
)
1172 if c
['THEME'] == theme
:
1173 line
= ' ' * 2 + light_yellow('* ') + line
1175 line
= ' ' * 4 + line
1181 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1182 # Redefine decorated_name
1183 g
['decorated_name'] = lambda x
: color_func(
1184 c
['DECORATED_NAME'])(
1186 printNicely(green('Theme changed.'))
1188 printNicely(red('No such theme exists.'))
1191 def help_discover():
1196 # Discover the world
1198 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1199 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1200 'You can try ' + light_green('trend US') + ' or ' + \
1201 light_green('trend JP Tokyo') + '.\n'
1202 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1203 light_green('home 7') + ' will show 7 tweets.\n'
1204 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1205 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1206 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1207 magenta('@mdo') + '.\n'
1208 usage
+= s
* 2 + light_green('view @mdo') + \
1209 ' will show ' + magenta('@mdo') + '\'s home.\n'
1210 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1211 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1212 'Search can be performed with or without hashtag.\n'
1223 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1224 usage
+= s
* 2 + light_green('t oops ') + \
1225 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1227 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1228 light_yellow('[id=12]') + '.\n'
1230 light_green('quote 12 ') + ' will quote the tweet with ' + \
1231 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1232 'the quote will be canceled.\n'
1234 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1235 light_yellow('[id=12]') + '.\n'
1236 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1237 light_yellow('oops') + '" to tweet with ' + \
1238 light_yellow('[id=12]') + '.\n'
1240 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1241 light_yellow('[id=12]') + '.\n'
1243 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1244 light_yellow('[id=12]') + '.\n'
1246 light_green('del 12 ') + ' will delete tweet with ' + \
1247 light_yellow('[id=12]') + '.\n'
1248 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1249 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1250 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1251 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1255 def help_messages():
1262 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1263 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1264 light_green('inbox 7') + ' will show newest 7 messages.\n'
1265 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1266 light_green('sent 7') + ' will show newest 7 messages.\n'
1267 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1268 magenta('@dtvd88') + '.\n'
1269 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1270 light_yellow('[message_id=5]') + '.\n'
1274 def help_friends_and_followers():
1276 Friends and Followers
1279 # Follower and following
1281 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1283 light_green('ls fl') + \
1284 ' will list all followers (people who are following you).\n'
1286 light_green('ls fr') + \
1287 ' will list all friends (people who you are following).\n'
1288 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1289 magenta('@dtvd88') + '.\n'
1290 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1291 magenta('@dtvd88') + '.\n'
1292 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1293 magenta('@dtvd88') + '.\n'
1294 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1295 magenta('@dtvd88') + '.\n'
1296 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1297 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1298 magenta('@dtvd88') + '.\n'
1299 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1300 magenta('@dtvd88') + '.\n'
1301 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1302 magenta('@dtvd88') + ' as a spam account.\n'
1313 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1314 usage
+= s
* 2 + light_green('list') + \
1315 ' will show all lists you are belong to.\n'
1316 usage
+= s
* 2 + light_green('list home') + \
1317 ' will show timeline of list. You will be asked for list\'s name.\n'
1318 usage
+= s
* 2 + light_green('list all_mem') + \
1319 ' will show list\'s all members.\n'
1320 usage
+= s
* 2 + light_green('list all_sub') + \
1321 ' will show list\'s all subscribers.\n'
1322 usage
+= s
* 2 + light_green('list add') + \
1323 ' will add specific person to a list owned by you.' + \
1324 ' You will be asked for list\'s name and person\'s name.\n'
1325 usage
+= s
* 2 + light_green('list rm') + \
1326 ' will remove specific person from a list owned by you.' + \
1327 ' You will be asked for list\'s name and person\'s name.\n'
1328 usage
+= s
* 2 + light_green('list sub') + \
1329 ' will subscribe you to a specific list.\n'
1330 usage
+= s
* 2 + light_green('list unsub') + \
1331 ' will unsubscribe you from a specific list.\n'
1332 usage
+= s
* 2 + light_green('list own') + \
1333 ' will show all list owned by you.\n'
1334 usage
+= s
* 2 + light_green('list new') + \
1335 ' will create a new list.\n'
1336 usage
+= s
* 2 + light_green('list update') + \
1337 ' will update a list owned by you.\n'
1338 usage
+= s
* 2 + light_green('list del') + \
1339 ' will delete a list owned by you.\n'
1350 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1351 usage
+= s
* 2 + light_green('switch public #AKB') + \
1352 ' will switch to public stream and follow "' + \
1353 light_yellow('AKB') + '" keyword.\n'
1354 usage
+= s
* 2 + light_green('switch mine') + \
1355 ' will switch to your personal stream.\n'
1356 usage
+= s
* 2 + light_green('switch mine -f ') + \
1357 ' will prompt to enter the filter.\n'
1358 usage
+= s
* 3 + light_yellow('Only nicks') + \
1359 ' filter will decide nicks will be INCLUDE ONLY.\n'
1360 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1361 ' filter will decide nicks will be EXCLUDE.\n'
1362 usage
+= s
* 2 + light_green('switch mine -d') + \
1363 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1372 h
, w
= os
.popen('stty size', 'r').read().split()
1375 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1376 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1377 usage
+= s
+ 'You are ' + \
1378 light_yellow('already') + ' on your personal stream.\n'
1379 usage
+= s
+ 'Any update from Twitter will show up ' + \
1380 light_yellow('immediately') + '.\n'
1381 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1382 # Twitter help section
1384 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1385 usage
+= s
* 2 + light_green('h discover') + \
1386 ' will show help for discover commands.\n'
1387 usage
+= s
* 2 + light_green('h tweets') + \
1388 ' will show help for tweets commands.\n'
1389 usage
+= s
* 2 + light_green('h messages') + \
1390 ' will show help for messages commands.\n'
1391 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1392 ' will show help for friends and followers commands.\n'
1393 usage
+= s
* 2 + light_green('h list') + \
1394 ' will show help for list commands.\n'
1395 usage
+= s
* 2 + light_green('h stream') + \
1396 ' will show help for stream commands.\n'
1399 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1400 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1401 'will be evaluate by Python interpreter.\n'
1402 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1403 ' for current month.\n'
1406 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1407 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1408 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1409 ' theme immediately.\n'
1410 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1412 light_green('config ASCII_ART') + ' will output current value of ' +\
1413 light_yellow('ASCII_ART') + ' config key.\n'
1415 light_green('config TREND_MAX default') + ' will output default value of ' + \
1416 light_yellow('TREND_MAX') + ' config key.\n'
1418 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1419 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1421 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1422 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1423 light_yellow('True') + '.\n'
1426 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1427 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1428 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1429 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1430 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1431 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1434 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1435 usage
+= s
+ 'Have fun and hang tight! \n'
1438 'discover': help_discover
,
1439 'tweets': help_tweets
,
1440 'messages': help_messages
,
1441 'friends_and_followers': help_friends_and_followers
,
1443 'stream': help_stream
,
1448 lambda: printNicely(red('No such command.'))
1456 Pause stream display
1459 printNicely(green('Stream is paused'))
1467 printNicely(green('Stream is running back now'))
1483 printNicely(green('See you next time :)'))
1491 Reset prefix of line
1494 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1497 printNicely(str(eval(g
['cmd'])))
1554 Listen to user's input
1559 ['public', 'mine'], # switch
1574 ['image'], # show image
1576 ['fl', 'fr'], # list
1603 [key
for key
in dict(get_all_config())], # config
1604 g
['themes'], # theme
1609 'friends_and_followers',
1619 init_interactive_shell(d
)
1625 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1628 # Save previous cmd in order to compare with readline buffer
1629 g
['previous_cmd'] = line
.strip()
1631 cmd
= line
.split()[0]
1634 # MacOSX readline bug (see "stream" function)
1635 if g
['OSX_readline_bug']:
1637 g
['OSX_readline_bug'] = False
1640 # Lock the semaphore
1642 # Save cmd to global variable and call process
1643 g
['stuff'] = ' '.join(line
.split()[1:])
1644 # Process the command
1647 if cmd
in ['switch', 't', 'rt', 'rep']:
1651 # Release the semaphore lock
1654 printNicely(red('OMG something is wrong with Twitter right now.'))
1657 def stream(domain
, args
, name
='Rainbow Stream'):
1663 c
['USER_DOMAIN']: name
,
1664 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1665 c
['SITE_DOMAIN']: name
,
1668 ascii_art(art_dict
[domain
])
1669 # These arguments are optional:
1671 timeout
=args
.timeout
,
1673 heartbeat_timeout
=args
.heartbeat_timeout
)
1676 if args
.track_keywords
:
1677 query_args
['track'] = args
.track_keywords
1679 stream
= TwitterStream(
1684 if domain
== c
['USER_DOMAIN']:
1685 tweet_iter
= stream
.user(**query_args
)
1686 elif domain
== c
['SITE_DOMAIN']:
1687 tweet_iter
= stream
.site(**query_args
)
1689 if args
.track_keywords
:
1690 tweet_iter
= stream
.statuses
.filter(**query_args
)
1692 tweet_iter
= stream
.statuses
.sample()
1693 # Block new stream until other one exits
1694 StreamLock
.acquire()
1695 g
['stream_stop'] = False
1696 for tweet
in tweet_iter
:
1697 if(g
['stream_stop']):
1698 StreamLock
.release()
1702 elif tweet
is Timeout
:
1703 printNicely("-- Timeout --")
1704 elif tweet
is HeartbeatTimeout
:
1705 printNicely("-- Heartbeat Timeout --")
1706 elif tweet
is Hangup
:
1707 printNicely("-- Hangup --")
1708 elif tweet
.get('text'):
1711 keyword
=args
.track_keywords
,
1712 check_semaphore
=True,
1716 # Current readline buffer
1717 current_buffer
= readline
.get_line_buffer().strip()
1718 # There is an unexpected behaviour in MacOSX readline
1719 # After completely delete a word after typing it
1720 # somehow readline buffer still contains the 1st character of that word
1721 if g
['previous_cmd'] != current_buffer
:
1722 if len(current_buffer
) == 1:
1724 g
['OSX_readline_bug'] = True
1725 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']) + current_buffer
)
1727 elif tweet
.get('direct_message'):
1728 print_message(tweet
['direct_message'], check_semaphore
=True)
1729 except TwitterHTTPError
:
1732 magenta("We have maximum connection problem with twitter'stream API right now :("))
1740 args
= parse_arguments()
1743 except TwitterHTTPError
:
1746 magenta("We have maximum connection problem with twitter'stream API right now :("))
1747 printNicely(magenta("Let's try again later."))
1750 # Spawn stream thread
1751 th
= threading
.Thread(
1756 g
['original_name']))
1759 # Start listen process