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
['previous_cmd'] = ''
165 # Init tweet dict and message dict
167 c
['message_dict'] = []
169 c
['IMAGE_ON_TERM'] = args
.image_on_term
170 # Dictionary of muted users key:screen name, value:name
174 def build_mute_dict(t
):
178 while next_cursor
!= 0:
179 list = t
.mutes
.users
.list(
180 screen_name
=g
['original_name'],
183 include_entities
=False,
185 for u
in list['users']:
186 rel
[u
['screen_name'].encode('ascii', 'ignore')] = u
['name'].encode('ascii', 'ignore')
187 next_cursor
= list['next_cursor']
188 if(rel
!= g
['mute_dict']):
197 target
= g
['stuff'].split()[0]
199 args
= parse_arguments()
201 if g
['stuff'].split()[-1] == '-f':
202 guide
= 'To ignore an option, just hit Enter key.'
203 printNicely(light_magenta(guide
))
204 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
205 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
206 args
.filter = filter(None, only
.split(','))
207 args
.ignore
= filter(None, ignore
.split(','))
208 elif g
['stuff'].split()[-1] == '-d':
209 args
.filter = c
['ONLY_LIST']
210 args
.ignore
= c
['IGNORE_LIST']
212 printNicely(red('Sorry, wrong format.'))
215 if target
== 'public':
216 keyword
= g
['stuff'].split()[1]
217 if keyword
[0] == '#':
218 keyword
= keyword
[1:]
220 g
['stream_stop'] = True
221 args
.track_keywords
= keyword
223 th
= threading
.Thread(
231 elif target
== 'mine':
233 g
['stream_stop'] = True
235 th
= threading
.Thread(
245 printNicely(cyan('Only: ' + str(args
.filter)))
247 printNicely(red('Ignore: ' + str(args
.ignore
)))
250 printNicely(red('Sorry I can\'t understand.'))
257 t
= Twitter(auth
=authen())
258 # Get country and town
260 country
= g
['stuff'].split()[0]
264 town
= g
['stuff'].split()[1]
267 avail
= t
.trends
.available()
270 trends
= t
.trends
.place(_id
=1)[0]['trends']
273 for location
in avail
:
274 # Search for country and Town
276 if location
['countryCode'] == country \
277 and location
['placeType']['name'] == 'Town' \
278 and location
['name'] == town
:
279 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
281 # Search for country only
283 if location
['countryCode'] == country \
284 and location
['placeType']['name'] == 'Country':
285 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
293 t
= Twitter(auth
=authen())
294 num
= c
['HOME_TWEET_NUM']
295 if g
['stuff'].isdigit():
296 num
= int(g
['stuff'])
297 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
306 t
= Twitter(auth
=authen())
307 user
= g
['stuff'].split()[0]
310 num
= int(g
['stuff'].split()[1])
312 num
= c
['HOME_TWEET_NUM']
313 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
317 printNicely(red('A name should begin with a \'@\''))
324 t
= Twitter(auth
=authen())
325 num
= c
['HOME_TWEET_NUM']
326 if g
['stuff'].isdigit():
327 num
= int(g
['stuff'])
328 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
337 t
= Twitter(auth
=authen())
338 t
.statuses
.update(status
=g
['stuff'])
345 t
= Twitter(auth
=authen())
347 id = int(g
['stuff'].split()[0])
349 printNicely(red('Sorry I can\'t understand.'))
351 tid
= c
['tweet_dict'][id]
352 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
359 t
= Twitter(auth
=authen())
361 id = int(g
['stuff'].split()[0])
363 printNicely(red('Sorry I can\'t understand.'))
365 tid
= c
['tweet_dict'][id]
366 tweet
= t
.statuses
.show(id=tid
)
367 screen_name
= tweet
['user']['screen_name']
369 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
370 quote
= quote
.encode('utf8')
371 notice
= light_magenta('Compose mode ')
372 notice
+= light_yellow('(Enter nothing will cancel the quote)')
373 notice
+= light_magenta(':')
375 extra
= raw_input(quote
)
377 t
.statuses
.update(status
=quote
+ extra
)
379 printNicely(light_magenta('No text added.'))
386 t
= Twitter(auth
=authen())
389 id = int(g
['stuff'].split()[0])
391 printNicely(red('Sorry I can\'t understand.'))
393 tid
= c
['tweet_dict'][id]
394 # Get display num if exist
396 num
= int(g
['stuff'].split()[1])
398 num
= c
['RETWEETS_SHOW_NUM']
399 # Get result and display
400 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
402 printNicely(magenta('This tweet has no retweet.'))
404 for tweet
in reversed(rt_ary
):
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
.favorites
.create(_id
=tid
, include_entities
=False)
421 printNicely(green('Favorited.'))
422 draw(t
.statuses
.show(id=tid
))
430 t
= Twitter(auth
=authen())
432 id = int(g
['stuff'].split()[0])
434 printNicely(red('Sorry I can\'t understand.'))
436 tid
= c
['tweet_dict'][id]
437 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
438 status
= ' '.join(g
['stuff'].split()[1:])
439 status
= '@' + user
+ ' ' + status
.decode('utf-8')
440 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
447 t
= Twitter(auth
=authen())
449 id = int(g
['stuff'].split()[0])
451 printNicely(red('Sorry I can\'t understand.'))
453 tid
= c
['tweet_dict'][id]
454 t
.statuses
.destroy(id=tid
)
455 printNicely(green('Okay it\'s gone.'))
462 t
= Twitter(auth
=authen())
464 id = int(g
['stuff'].split()[0])
466 printNicely(red('Sorry I can\'t understand.'))
468 tid
= c
['tweet_dict'][id]
469 t
.favorites
.destroy(_id
=tid
)
470 printNicely(green('Okay it\'s unfavorited.'))
471 draw(t
.statuses
.show(id=tid
))
479 t
= Twitter(auth
=authen())
480 g
['stuff'] = g
['stuff'].strip()
481 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
483 printNicely('Newest tweets:')
484 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
489 printNicely(magenta('I\'m afraid there is no result'))
494 Send a direct message
496 t
= Twitter(auth
=authen())
497 user
= g
['stuff'].split()[0]
498 if user
[0].startswith('@'):
500 content
= g
['stuff'].split()[1]
502 printNicely(red('Sorry I can\'t understand.'))
503 t
.direct_messages
.new(
504 screen_name
=user
[1:],
507 printNicely(green('Message sent.'))
509 printNicely(red('A name should begin with a \'@\''))
516 t
= Twitter(auth
=authen())
518 target
= g
['stuff'].split()[0]
519 if target
!= 'image':
521 id = int(g
['stuff'].split()[1])
522 tid
= c
['tweet_dict'][id]
523 tweet
= t
.statuses
.show(id=tid
)
524 media
= tweet
['entities']['media']
526 res
= requests
.get(m
['media_url'])
527 img
= Image
.open(BytesIO(res
.content
))
530 printNicely(red('Sorry I can\'t show this image.'))
537 t
= Twitter(auth
=authen())
539 if not g
['stuff'].isdigit():
541 tid
= c
['tweet_dict'][int(g
['stuff'])]
542 tweet
= t
.statuses
.show(id=tid
)
544 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
546 printNicely(light_magenta('No url here @.@!'))
548 for link
in link_ary
:
549 webbrowser
.open(link
)
551 printNicely(red('Sorry I can\'t open url in this tweet.'))
556 List friends for followers
558 t
= Twitter(auth
=authen())
561 name
= g
['stuff'].split()[1]
562 if name
.startswith('@'):
565 printNicely(red('A name should begin with a \'@\''))
566 raise Exception('Invalid name')
568 name
= g
['original_name']
569 # Get list followers or friends
571 target
= g
['stuff'].split()[0]
573 printNicely(red('Omg some syntax is wrong.'))
575 d
= {'fl': 'followers', 'fr': 'friends'}
579 while next_cursor
!= 0:
580 list = getattr(t
, d
[target
]).list(
584 include_entities
=False,
586 for u
in list['users']:
587 rel
[u
['name']] = '@' + u
['screen_name']
588 next_cursor
= list['next_cursor']
590 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
592 user
= ' ' + cycle_color(name
)
593 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
599 Inbox direct messages
601 t
= Twitter(auth
=authen())
602 num
= c
['MESSAGES_DISPLAY']
604 if g
['stuff'].isdigit():
607 # Max message per page is 20 so we have to loop
609 rel
= rel
+ t
.direct_messages(
612 include_entities
=False,
617 rel
= rel
+ t
.direct_messages(
620 include_entities
=False,
624 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
625 for m
in reversed(rel
):
634 t
= Twitter(auth
=authen())
635 num
= c
['MESSAGES_DISPLAY']
637 if g
['stuff'].isdigit():
638 num
= int(g
['stuff'])
640 # Max message per page is 20 so we have to loop
642 rel
= rel
+ t
.direct_messages
.sent(
645 include_entities
=False,
650 rel
= rel
+ t
.direct_messages
.sent(
653 include_entities
=False,
657 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
658 for m
in reversed(rel
):
667 t
= Twitter(auth
=authen())
669 id = int(g
['stuff'].split()[0])
671 printNicely(red('Sorry I can\'t understand.'))
672 mid
= c
['message_dict'][id]
673 t
.direct_messages
.destroy(id=mid
)
674 printNicely(green('Message deleted.'))
679 Show profile of a specific user
681 t
= Twitter(auth
=authen())
682 screen_name
= g
['stuff'].split()[0]
683 if screen_name
.startswith('@'):
686 screen_name
=screen_name
[1:],
687 include_entities
=False)
690 printNicely(red('Omg no user.'))
692 printNicely(red('A name should begin with a \'@\''))
699 t
= Twitter(auth
=authen())
700 screen_name
= g
['stuff'].split()[0]
701 if screen_name
.startswith('@'):
702 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
703 printNicely(green('You are following ' + screen_name
+ ' now!'))
705 printNicely(red('A name should begin with a \'@\''))
712 t
= Twitter(auth
=authen())
713 screen_name
= g
['stuff'].split()[0]
714 if screen_name
.startswith('@'):
715 t
.friendships
.destroy(
716 screen_name
=screen_name
[1:],
717 include_entities
=False)
718 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
720 printNicely(red('A name should begin with a \'@\''))
727 t
= Twitter(auth
=authen())
729 screen_name
= g
['stuff'].split()[0]
731 printNicely(red('A name should be specified. '))
733 if screen_name
.startswith('@'):
734 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
735 if isinstance(rel
, dict):
736 printNicely(green(screen_name
+ ' is muted.'))
739 printNicely(red(rel
))
741 printNicely(red('A name should begin with a \'@\''))
748 t
= Twitter(auth
=authen())
750 screen_name
= g
['stuff'].split()[0]
752 printNicely(red('A name should be specified. '))
754 if screen_name
.startswith('@'):
755 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
756 if isinstance(rel
, dict):
757 printNicely(green(screen_name
+ ' is unmuted.'))
760 printNicely(red(rel
))
762 printNicely(red('A name should begin with a \'@\''))
771 printNicely('All: ' + str(len(rel
)) + ' people.')
773 user
= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
774 user
+= cycle_color('@'+ name
)
782 t
= Twitter(auth
=authen())
783 screen_name
= g
['stuff'].split()[0]
784 if screen_name
.startswith('@'):
786 screen_name
=screen_name
[1:],
787 include_entities
=False,
789 printNicely(green('You blocked ' + screen_name
+ '.'))
791 printNicely(red('A name should begin with a \'@\''))
798 t
= Twitter(auth
=authen())
799 screen_name
= g
['stuff'].split()[0]
800 if screen_name
.startswith('@'):
802 screen_name
=screen_name
[1:],
803 include_entities
=False,
805 printNicely(green('Unblock ' + screen_name
+ ' success!'))
807 printNicely(red('A name should begin with a \'@\''))
812 Report a user as a spam account
814 t
= Twitter(auth
=authen())
815 screen_name
= g
['stuff'].split()[0]
816 if screen_name
.startswith('@'):
818 screen_name
=screen_name
[1:])
819 printNicely(green('You reported ' + screen_name
+ '.'))
821 printNicely(red('Sorry I can\'t understand.'))
829 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
830 # Get list name and owner
832 owner
, slug
= list_name
.split('/')
833 if slug
.startswith('@'):
838 light_magenta('List name should follow "@owner/list_name" format.'))
839 raise Exception('Wrong list name')
846 rel
= t
.lists
.list(screen_name
=g
['original_name'])
850 printNicely(light_magenta('You belong to no lists :)'))
857 owner
, slug
= get_slug()
858 res
= t
.lists
.statuses(
860 owner_screen_name
=owner
,
862 include_entities
=False)
872 owner
, slug
= get_slug()
876 while next_cursor
!= 0:
879 owner_screen_name
=owner
,
881 include_entities
=False)
883 rel
[u
['name']] = '@' + u
['screen_name']
884 next_cursor
= m
['next_cursor']
885 printNicely('All: ' + str(len(rel
)) + ' members.')
887 user
= ' ' + cycle_color(name
)
888 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
892 def list_subscribers(t
):
896 owner
, slug
= get_slug()
900 while next_cursor
!= 0:
901 m
= t
.lists
.subscribers(
903 owner_screen_name
=owner
,
905 include_entities
=False)
907 rel
[u
['name']] = '@' + u
['screen_name']
908 next_cursor
= m
['next_cursor']
909 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
911 user
= ' ' + cycle_color(name
)
912 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
918 Add specific user to a list
920 owner
, slug
= get_slug()
922 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
923 if user_name
.startswith('@'):
924 user_name
= user_name
[1:]
926 t
.lists
.members
.create(
928 owner_screen_name
=owner
,
929 screen_name
=user_name
)
930 printNicely(green('Added.'))
932 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
937 Remove specific user from a list
939 owner
, slug
= get_slug()
941 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
942 if user_name
.startswith('@'):
943 user_name
= user_name
[1:]
945 t
.lists
.members
.destroy(
947 owner_screen_name
=owner
,
948 screen_name
=user_name
)
949 printNicely(green('Gone.'))
951 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
954 def list_subscribe(t
):
958 owner
, slug
= get_slug()
961 t
.lists
.subscribers
.create(
963 owner_screen_name
=owner
)
964 printNicely(green('Done.'))
967 light_magenta('I\'m sorry you can not subscribe to this list.'))
970 def list_unsubscribe(t
):
974 owner
, slug
= get_slug()
977 t
.lists
.subscribers
.destroy(
979 owner_screen_name
=owner
)
980 printNicely(green('Done.'))
983 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
992 while next_cursor
!= 0:
993 res
= t
.lists
.ownerships(
994 screen_name
=g
['original_name'],
997 next_cursor
= res
['next_cursor']
1001 printNicely(light_magenta('You own no lists :)'))
1008 name
= raw_input(light_magenta('New list\'s name: '))
1009 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1010 description
= raw_input(light_magenta('New list\'s description: '))
1015 description
=description
)
1016 printNicely(green(name
+ ' list is created.'))
1018 printNicely(red('Oops something is wrong with Twitter :('))
1025 slug
= raw_input(light_magenta('Your list that you want to update: '))
1026 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1027 mode
= raw_input(light_magenta('Update mode (public/private): '))
1028 description
= raw_input(light_magenta('Update description: '))
1032 slug
='-'.join(slug
.split()),
1033 owner_screen_name
=g
['original_name'],
1036 description
=description
)
1040 owner_screen_name
=g
['original_name'],
1042 description
=description
)
1043 printNicely(green(slug
+ ' list is updated.'))
1045 printNicely(red('Oops something is wrong with Twitter :('))
1052 slug
= raw_input(light_magenta('Your list that you want to update: '))
1055 slug
='-'.join(slug
.split()),
1056 owner_screen_name
=g
['original_name'])
1057 printNicely(green(slug
+ ' list is deleted.'))
1059 printNicely(red('Oops something is wrong with Twitter :('))
1066 t
= Twitter(auth
=authen())
1067 # List all lists or base on action
1069 g
['list_action'] = g
['stuff'].split()[0]
1076 'all_mem': list_members
,
1077 'all_sub': list_subscribers
,
1080 'sub': list_subscribe
,
1081 'unsub': list_unsubscribe
,
1084 'update': list_update
,
1088 return action_ary
[g
['list_action']](t
)
1090 printNicely(red('Please try again.'))
1095 Unix's command `cal`
1098 rel
= os
.popen('cal').read().split('\n')
1101 show_calendar(month
, date
, rel
)
1106 Browse and change config
1108 all_config
= get_all_config()
1109 g
['stuff'] = g
['stuff'].strip()
1112 for k
in all_config
:
1114 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1116 guide
= 'Detailed explanation can be found at ' + \
1117 color_func(c
['TWEET']['link'])(
1118 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1120 # Print specific config
1121 elif len(g
['stuff'].split()) == 1:
1122 if g
['stuff'] in all_config
:
1125 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1128 printNicely(red('No such config key.'))
1129 # Print specific config's default value
1130 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1131 key
= g
['stuff'].split()[0]
1133 value
= get_default_config(key
)
1134 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1138 light_magenta('This config key does not exist in default.'))
1139 # Delete specific config key in config file
1140 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1141 key
= g
['stuff'].split()[0]
1144 printNicely(green('Config key is dropped.'))
1146 printNicely(red('No such config key.'))
1147 # Set specific config
1148 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1149 key
= g
['stuff'].split()[0]
1150 value
= g
['stuff'].split()[-1]
1151 if key
== 'THEME' and not validate_theme(value
):
1152 printNicely(red('Invalid theme\'s value.'))
1155 set_config(key
, value
)
1156 # Apply theme immediately
1158 c
['THEME'] = reload_theme(value
, c
['THEME'])
1159 g
['decorated_name'] = lambda x
: color_func(
1160 c
['DECORATED_NAME'])(
1162 printNicely(green('Updated successfully.'))
1164 printNicely(light_magenta('Not valid value.'))
1168 printNicely(light_magenta('Sorry I can\'s understand.'))
1173 List and change theme
1177 for theme
in g
['themes']:
1178 line
= light_magenta(theme
)
1179 if c
['THEME'] == theme
:
1180 line
= ' ' * 2 + light_yellow('* ') + line
1182 line
= ' ' * 4 + line
1188 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1189 # Redefine decorated_name
1190 g
['decorated_name'] = lambda x
: color_func(
1191 c
['DECORATED_NAME'])(
1193 printNicely(green('Theme changed.'))
1195 printNicely(red('No such theme exists.'))
1198 def help_discover():
1203 # Discover the world
1205 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1206 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1207 'You can try ' + light_green('trend US') + ' or ' + \
1208 light_green('trend JP Tokyo') + '.\n'
1209 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1210 light_green('home 7') + ' will show 7 tweets.\n'
1211 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1212 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1213 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1214 magenta('@mdo') + '.\n'
1215 usage
+= s
* 2 + light_green('view @mdo') + \
1216 ' will show ' + magenta('@mdo') + '\'s home.\n'
1217 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1218 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1219 'Search can be performed with or without hashtag.\n'
1230 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1231 usage
+= s
* 2 + light_green('t oops ') + \
1232 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1234 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1235 light_yellow('[id=12]') + '.\n'
1237 light_green('quote 12 ') + ' will quote the tweet with ' + \
1238 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1239 'the quote will be canceled.\n'
1241 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1242 light_yellow('[id=12]') + '.\n'
1243 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1244 light_yellow('oops') + '" to tweet with ' + \
1245 light_yellow('[id=12]') + '.\n'
1247 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1248 light_yellow('[id=12]') + '.\n'
1250 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1251 light_yellow('[id=12]') + '.\n'
1253 light_green('del 12 ') + ' will delete tweet with ' + \
1254 light_yellow('[id=12]') + '.\n'
1255 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1256 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1257 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1258 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1262 def help_messages():
1269 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1270 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1271 light_green('inbox 7') + ' will show newest 7 messages.\n'
1272 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1273 light_green('sent 7') + ' will show newest 7 messages.\n'
1274 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1275 magenta('@dtvd88') + '.\n'
1276 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1277 light_yellow('[message_id=5]') + '.\n'
1281 def help_friends_and_followers():
1283 Friends and Followers
1286 # Follower and following
1288 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1290 light_green('ls fl') + \
1291 ' will list all followers (people who are following you).\n'
1293 light_green('ls fr') + \
1294 ' will list all friends (people who you are following).\n'
1295 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1296 magenta('@dtvd88') + '.\n'
1297 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1298 magenta('@dtvd88') + '.\n'
1299 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1300 magenta('@dtvd88') + '.\n'
1301 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1302 magenta('@dtvd88') + '.\n'
1303 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1304 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1305 magenta('@dtvd88') + '.\n'
1306 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1307 magenta('@dtvd88') + '.\n'
1308 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1309 magenta('@dtvd88') + ' as a spam account.\n'
1320 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1321 usage
+= s
* 2 + light_green('list') + \
1322 ' will show all lists you are belong to.\n'
1323 usage
+= s
* 2 + light_green('list home') + \
1324 ' will show timeline of list. You will be asked for list\'s name.\n'
1325 usage
+= s
* 2 + light_green('list all_mem') + \
1326 ' will show list\'s all members.\n'
1327 usage
+= s
* 2 + light_green('list all_sub') + \
1328 ' will show list\'s all subscribers.\n'
1329 usage
+= s
* 2 + light_green('list add') + \
1330 ' will add specific person to a list owned by you.' + \
1331 ' You will be asked for list\'s name and person\'s name.\n'
1332 usage
+= s
* 2 + light_green('list rm') + \
1333 ' will remove specific person from a list owned by you.' + \
1334 ' You will be asked for list\'s name and person\'s name.\n'
1335 usage
+= s
* 2 + light_green('list sub') + \
1336 ' will subscribe you to a specific list.\n'
1337 usage
+= s
* 2 + light_green('list unsub') + \
1338 ' will unsubscribe you from a specific list.\n'
1339 usage
+= s
* 2 + light_green('list own') + \
1340 ' will show all list owned by you.\n'
1341 usage
+= s
* 2 + light_green('list new') + \
1342 ' will create a new list.\n'
1343 usage
+= s
* 2 + light_green('list update') + \
1344 ' will update a list owned by you.\n'
1345 usage
+= s
* 2 + light_green('list del') + \
1346 ' will delete a list owned by you.\n'
1357 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1358 usage
+= s
* 2 + light_green('switch public #AKB') + \
1359 ' will switch to public stream and follow "' + \
1360 light_yellow('AKB') + '" keyword.\n'
1361 usage
+= s
* 2 + light_green('switch mine') + \
1362 ' will switch to your personal stream.\n'
1363 usage
+= s
* 2 + light_green('switch mine -f ') + \
1364 ' will prompt to enter the filter.\n'
1365 usage
+= s
* 3 + light_yellow('Only nicks') + \
1366 ' filter will decide nicks will be INCLUDE ONLY.\n'
1367 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1368 ' filter will decide nicks will be EXCLUDE.\n'
1369 usage
+= s
* 2 + light_green('switch mine -d') + \
1370 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1379 h
, w
= os
.popen('stty size', 'r').read().split()
1382 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1383 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1384 usage
+= s
+ 'You are ' + \
1385 light_yellow('already') + ' on your personal stream.\n'
1386 usage
+= s
+ 'Any update from Twitter will show up ' + \
1387 light_yellow('immediately') + '.\n'
1388 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1389 # Twitter help section
1391 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1392 usage
+= s
* 2 + light_green('h discover') + \
1393 ' will show help for discover commands.\n'
1394 usage
+= s
* 2 + light_green('h tweets') + \
1395 ' will show help for tweets commands.\n'
1396 usage
+= s
* 2 + light_green('h messages') + \
1397 ' will show help for messages commands.\n'
1398 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1399 ' will show help for friends and followers commands.\n'
1400 usage
+= s
* 2 + light_green('h list') + \
1401 ' will show help for list commands.\n'
1402 usage
+= s
* 2 + light_green('h stream') + \
1403 ' will show help for stream commands.\n'
1406 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1407 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1408 'will be evaluate by Python interpreter.\n'
1409 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1410 ' for current month.\n'
1413 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1414 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1415 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1416 ' theme immediately.\n'
1417 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1419 light_green('config ASCII_ART') + ' will output current value of ' +\
1420 light_yellow('ASCII_ART') + ' config key.\n'
1422 light_green('config TREND_MAX default') + ' will output default value of ' + \
1423 light_yellow('TREND_MAX') + ' config key.\n'
1425 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1426 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1428 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1429 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1430 light_yellow('True') + '.\n'
1433 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1434 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1435 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1436 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1437 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1438 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1441 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1442 usage
+= s
+ 'Have fun and hang tight! \n'
1445 'discover': help_discover
,
1446 'tweets': help_tweets
,
1447 'messages': help_messages
,
1448 'friends_and_followers': help_friends_and_followers
,
1450 'stream': help_stream
,
1455 lambda: printNicely(red('No such command.'))
1463 Pause stream display
1466 printNicely(green('Stream is paused'))
1474 printNicely(green('Stream is running back now'))
1490 printNicely(green('See you next time :)'))
1498 Reset prefix of line
1501 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1504 printNicely(str(eval(g
['cmd'])))
1561 Listen to user's input
1566 ['public', 'mine'], # switch
1581 ['image'], # show image
1583 ['fl', 'fr'], # list
1610 [key
for key
in dict(get_all_config())], # config
1611 g
['themes'], # theme
1616 'friends_and_followers',
1626 init_interactive_shell(d
)
1632 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1635 # Save previous cmd in order to compare with readline buffer
1636 g
['previous_cmd'] = line
.strip()
1638 cmd
= line
.split()[0]
1643 # Lock the semaphore
1645 # Save cmd to global variable and call process
1646 g
['stuff'] = ' '.join(line
.split()[1:])
1647 # Process the command
1650 if cmd
in ['switch', 't', 'rt', 'rep']:
1654 # Release the semaphore lock
1657 printNicely(red('OMG something is wrong with Twitter right now.'))
1660 def stream(domain
, args
, name
='Rainbow Stream'):
1666 c
['USER_DOMAIN']: name
,
1667 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1668 c
['SITE_DOMAIN']: name
,
1671 ascii_art(art_dict
[domain
])
1672 # These arguments are optional:
1674 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1675 block
=not args
.no_block
,
1676 heartbeat_timeout
=args
.heartbeat_timeout
)
1679 if args
.track_keywords
:
1680 query_args
['track'] = args
.track_keywords
1682 stream
= TwitterStream(
1687 if domain
== c
['USER_DOMAIN']:
1688 tweet_iter
= stream
.user(**query_args
)
1689 elif domain
== c
['SITE_DOMAIN']:
1690 tweet_iter
= stream
.site(**query_args
)
1692 if args
.track_keywords
:
1693 tweet_iter
= stream
.statuses
.filter(**query_args
)
1695 tweet_iter
= stream
.statuses
.sample()
1696 # Block new stream until other one exits
1697 StreamLock
.acquire()
1698 g
['stream_stop'] = False
1699 for tweet
in tweet_iter
:
1701 printNicely("-- None --")
1702 elif tweet
is Timeout
:
1703 if(g
['stream_stop']):
1704 StreamLock
.release()
1706 elif tweet
is HeartbeatTimeout
:
1707 printNicely("-- Heartbeat Timeout --")
1708 elif tweet
is Hangup
:
1709 printNicely("-- Hangup --")
1710 elif tweet
.get('text') and (tweet
['user']['screen_name'] not in g
['mute_dict']):
1713 keyword
=args
.track_keywords
,
1714 check_semaphore
=True,
1718 # Current readline buffer
1719 current_buffer
= readline
.get_line_buffer().strip()
1720 # There is an unexpected behaviour in MacOSX readline + Python 2:
1721 # after completely delete a word after typing it,
1722 # somehow readline buffer still contains
1723 # the 1st character of that word
1724 if current_buffer
and g
['previous_cmd'] != current_buffer
:
1726 g
['decorated_name'](c
['PREFIX']) + current_buffer
)
1728 elif not c
['HIDE_PROMPT']:
1729 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1731 elif tweet
.get('direct_message'):
1732 print_message(tweet
['direct_message'], check_semaphore
=True)
1733 except TwitterHTTPError
:
1736 magenta("We have maximum connection problem with twitter'stream API right now :("))
1744 args
= parse_arguments()
1747 except TwitterHTTPError
as error
:
1750 magenta("We have maximum connection problem with twitter'stream API right now :("))
1751 printNicely(magenta("Let's try again later."))
1755 # Spawn stream thread
1756 th
= threading
.Thread(
1761 g
['original_name']))
1764 # Start listen process