2 Colorful user's timeline stream
4 from multiprocessing
import Process
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
29 from .py3patch
import *
39 StreamLock
= threading
.Lock()
85 def parse_arguments():
89 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
93 help='Timeout for the stream (seconds).')
96 '--heartbeat-timeout',
97 help='Set heartbeat timeout.',
103 help='Set stream to non-blocking.')
107 help='Search the stream for specific text.')
111 help='Filter specific screen_name.')
115 help='Ignore specific screen_name.')
120 help='Display all image on terminal.')
121 return parser
.parse_args()
126 Authenticate with Twitter OAuth
128 # When using rainbow stream you must authorize.
129 twitter_credential
= os
.environ
.get(
133 '')) + os
.sep
+ '.rainbow_oauth'
134 if not os
.path
.exists(twitter_credential
):
135 oauth_dance("Rainbow Stream",
139 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
152 ctrl_c_handler
= lambda signum
, frame
: quit()
153 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
155 t
= Twitter(auth
=authen())
156 name
= '@' + t
.account
.verify_credentials()['screen_name']
157 if not get_config('PREFIX'):
158 set_config('PREFIX', name
)
159 g
['original_name'] = name
[1:]
160 g
['decorated_name'] = lambda x
: color_func(
161 c
['DECORATED_NAME'])(
164 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
165 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
167 db
.theme_store(c
['THEME'])
169 db
.semaphore_store(False, False)
171 c
['IMAGE_ON_TERM'] = args
.image_on_term
179 target
= g
['stuff'].split()[0]
181 args
= parse_arguments()
183 if g
['stuff'].split()[-1] == '-f':
184 guide
= 'To ignore an option, just hit Enter key.'
185 printNicely(light_magenta(guide
))
186 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
187 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
188 args
.filter = filter(None, only
.split(','))
189 args
.ignore
= filter(None, ignore
.split(','))
190 elif g
['stuff'].split()[-1] == '-d':
191 args
.filter = c
['ONLY_LIST']
192 args
.ignore
= c
['IGNORE_LIST']
194 printNicely(red('Sorry, wrong format.'))
197 if target
== 'public':
198 keyword
= g
['stuff'].split()[1]
199 if keyword
[0] == '#':
200 keyword
= keyword
[1:]
202 g
['stream_stop'] = True
203 args
.track_keywords
= keyword
205 th
= threading
.Thread(target
=stream
, args
=(c
['PUBLIC_DOMAIN'], args
))
209 elif target
== 'mine':
211 g
['stream_stop'] = True
213 th
= threading
.Thread(target
=stream
, args
=(c
['USER_DOMAIN'], args
, g
['original_name']))
218 printNicely(cyan('Only: ' + str(args
.filter)))
220 printNicely(red('Ignore: ' + str(args
.ignore
)))
223 printNicely(red('Sorry I can\'t understand.'))
230 t
= Twitter(auth
=authen())
231 # Get country and town
233 country
= g
['stuff'].split()[0]
237 town
= g
['stuff'].split()[1]
240 avail
= t
.trends
.available()
243 trends
= t
.trends
.place(_id
=1)[0]['trends']
246 for location
in avail
:
247 # Search for country and Town
249 if location
['countryCode'] == country \
250 and location
['placeType']['name'] == 'Town' \
251 and location
['name'] == town
:
252 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
254 # Search for country only
256 if location
['countryCode'] == country \
257 and location
['placeType']['name'] == 'Country':
258 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
266 t
= Twitter(auth
=authen())
267 num
= c
['HOME_TWEET_NUM']
268 if g
['stuff'].isdigit():
269 num
= int(g
['stuff'])
270 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
279 t
= Twitter(auth
=authen())
280 user
= g
['stuff'].split()[0]
283 num
= int(g
['stuff'].split()[1])
285 num
= c
['HOME_TWEET_NUM']
286 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
290 printNicely(red('A name should begin with a \'@\''))
297 t
= Twitter(auth
=authen())
298 num
= c
['HOME_TWEET_NUM']
299 if g
['stuff'].isdigit():
300 num
= int(g
['stuff'])
301 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
310 t
= Twitter(auth
=authen())
311 t
.statuses
.update(status
=g
['stuff'])
318 t
= Twitter(auth
=authen())
320 id = int(g
['stuff'].split()[0])
322 printNicely(red('Sorry I can\'t understand.'))
324 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
325 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
332 t
= Twitter(auth
=authen())
334 id = int(g
['stuff'].split()[0])
336 printNicely(red('Sorry I can\'t understand.'))
338 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
339 tweet
= t
.statuses
.show(id=tid
)
340 screen_name
= tweet
['user']['screen_name']
342 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
343 quote
= quote
.encode('utf8')
344 notice
= light_magenta('Compose mode ')
345 notice
+= light_yellow('(Enter nothing will cancel the quote)')
346 notice
+= light_magenta(':')
348 extra
= raw_input(quote
)
350 t
.statuses
.update(status
=quote
+ extra
)
352 printNicely(light_magenta('No text added.'))
359 t
= Twitter(auth
=authen())
362 id = int(g
['stuff'].split()[0])
364 printNicely(red('Sorry I can\'t understand.'))
366 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
367 # Get display num if exist
369 num
= int(g
['stuff'].split()[1])
371 num
= c
['RETWEETS_SHOW_NUM']
372 # Get result and display
373 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
375 printNicely(magenta('This tweet has no retweet.'))
377 for tweet
in reversed(rt_ary
):
386 t
= Twitter(auth
=authen())
388 id = int(g
['stuff'].split()[0])
390 printNicely(red('Sorry I can\'t understand.'))
392 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
393 t
.favorites
.create(_id
=tid
, include_entities
=False)
394 printNicely(green('Favorited.'))
395 draw(t
.statuses
.show(id=tid
))
403 t
= Twitter(auth
=authen())
405 id = int(g
['stuff'].split()[0])
407 printNicely(red('Sorry I can\'t understand.'))
409 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
410 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
411 status
= ' '.join(g
['stuff'].split()[1:])
412 status
= '@' + user
+ ' ' + status
.decode('utf-8')
413 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
420 t
= Twitter(auth
=authen())
422 rid
= int(g
['stuff'].split()[0])
424 printNicely(red('Sorry I can\'t understand.'))
426 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
427 t
.statuses
.destroy(id=tid
)
428 printNicely(green('Okay it\'s gone.'))
435 t
= Twitter(auth
=authen())
437 id = int(g
['stuff'].split()[0])
439 printNicely(red('Sorry I can\'t understand.'))
441 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
442 t
.favorites
.destroy(_id
=tid
)
443 printNicely(green('Okay it\'s unfavorited.'))
444 draw(t
.statuses
.show(id=tid
))
452 t
= Twitter(auth
=authen())
453 g
['stuff'] = g
['stuff'].strip()
454 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
456 printNicely('Newest tweets:')
457 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
462 printNicely(magenta('I\'m afraid there is no result'))
467 Send a direct message
469 t
= Twitter(auth
=authen())
470 user
= g
['stuff'].split()[0]
471 if user
[0].startswith('@'):
473 content
= g
['stuff'].split()[1]
475 printNicely(red('Sorry I can\'t understand.'))
476 t
.direct_messages
.new(
477 screen_name
=user
[1:],
480 printNicely(green('Message sent.'))
482 printNicely(red('A name should begin with a \'@\''))
489 t
= Twitter(auth
=authen())
491 target
= g
['stuff'].split()[0]
492 if target
!= 'image':
494 id = int(g
['stuff'].split()[1])
495 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
496 tweet
= t
.statuses
.show(id=tid
)
497 media
= tweet
['entities']['media']
499 res
= requests
.get(m
['media_url'])
500 img
= Image
.open(BytesIO(res
.content
))
503 printNicely(red('Sorry I can\'t show this image.'))
510 t
= Twitter(auth
=authen())
512 if not g
['stuff'].isdigit():
514 tid
= db
.rainbow_to_tweet_query(g
['stuff'])[0].tweet_id
515 tweet
= t
.statuses
.show(id=tid
)
517 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
519 printNicely(light_magenta('No url here @.@!'))
521 for link
in link_ary
:
522 webbrowser
.open(link
)
524 printNicely(red('Sorry I can\'t open url in this tweet.'))
529 List friends for followers
531 t
= Twitter(auth
=authen())
534 name
= g
['stuff'].split()[1]
535 if name
.startswith('@'):
538 printNicely(red('A name should begin with a \'@\''))
539 raise Exception('Invalid name')
541 name
= g
['original_name']
542 # Get list followers or friends
544 target
= g
['stuff'].split()[0]
546 printNicely(red('Omg some syntax is wrong.'))
548 d
= {'fl': 'followers', 'fr': 'friends'}
552 while next_cursor
!= 0:
553 list = getattr(t
, d
[target
]).list(
557 include_entities
=False,
559 for u
in list['users']:
560 rel
[u
['name']] = '@' + u
['screen_name']
561 next_cursor
= list['next_cursor']
563 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
565 user
= ' ' + cycle_color(name
)
566 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
572 Inbox direct messages
574 t
= Twitter(auth
=authen())
575 num
= c
['MESSAGES_DISPLAY']
577 if g
['stuff'].isdigit():
580 # Max message per page is 20 so we have to loop
582 rel
= rel
+ t
.direct_messages(
585 include_entities
=False,
590 rel
= rel
+ t
.direct_messages(
593 include_entities
=False,
597 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
598 for m
in reversed(rel
):
607 t
= Twitter(auth
=authen())
608 num
= c
['MESSAGES_DISPLAY']
610 if g
['stuff'].isdigit():
611 num
= int(g
['stuff'])
613 # Max message per page is 20 so we have to loop
615 rel
= rel
+ t
.direct_messages
.sent(
618 include_entities
=False,
623 rel
= rel
+ t
.direct_messages
.sent(
626 include_entities
=False,
630 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
631 for m
in reversed(rel
):
640 t
= Twitter(auth
=authen())
642 rid
= int(g
['stuff'].split()[0])
644 printNicely(red('Sorry I can\'t understand.'))
645 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
646 t
.direct_messages
.destroy(id=mid
)
647 printNicely(green('Message deleted.'))
652 Show profile of a specific user
654 t
= Twitter(auth
=authen())
655 screen_name
= g
['stuff'].split()[0]
656 if screen_name
.startswith('@'):
659 screen_name
=screen_name
[1:],
660 include_entities
=False)
663 printNicely(red('Omg no user.'))
665 printNicely(red('A name should begin with a \'@\''))
672 t
= Twitter(auth
=authen())
673 screen_name
= g
['stuff'].split()[0]
674 if screen_name
.startswith('@'):
675 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
676 printNicely(green('You are following ' + screen_name
+ ' now!'))
678 printNicely(red('A name should begin with a \'@\''))
685 t
= Twitter(auth
=authen())
686 screen_name
= g
['stuff'].split()[0]
687 if screen_name
.startswith('@'):
688 t
.friendships
.destroy(
689 screen_name
=screen_name
[1:],
690 include_entities
=False)
691 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
693 printNicely(red('A name should begin with a \'@\''))
700 t
= Twitter(auth
=authen())
702 screen_name
= g
['stuff'].split()[0]
704 printNicely(red('A name should be specified. '))
706 if screen_name
.startswith('@'):
707 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
708 if isinstance(rel
, dict):
709 printNicely(green(screen_name
+ ' is muted.'))
711 printNicely(red(rel
))
713 printNicely(red('A name should begin with a \'@\''))
720 t
= Twitter(auth
=authen())
722 screen_name
= g
['stuff'].split()[0]
724 printNicely(red('A name should be specified. '))
726 if screen_name
.startswith('@'):
727 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
728 if isinstance(rel
, dict):
729 printNicely(green(screen_name
+ ' is unmuted.'))
731 printNicely(red(rel
))
733 printNicely(red('A name should begin with a \'@\''))
740 t
= Twitter(auth
=authen())
745 while next_cursor
!= 0:
746 list = t
.mutes
.users
.list(
747 screen_name
=g
['original_name'],
750 include_entities
=False,
752 for u
in list['users']:
753 rel
[u
['name']] = '@' + u
['screen_name']
754 next_cursor
= list['next_cursor']
756 printNicely('All: ' + str(len(rel
)) + ' people.')
758 user
= ' ' + cycle_color(name
)
759 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
767 t
= Twitter(auth
=authen())
768 screen_name
= g
['stuff'].split()[0]
769 if screen_name
.startswith('@'):
771 screen_name
=screen_name
[1:],
772 include_entities
=False,
774 printNicely(green('You blocked ' + screen_name
+ '.'))
776 printNicely(red('A name should begin with a \'@\''))
783 t
= Twitter(auth
=authen())
784 screen_name
= g
['stuff'].split()[0]
785 if screen_name
.startswith('@'):
787 screen_name
=screen_name
[1:],
788 include_entities
=False,
790 printNicely(green('Unblock ' + screen_name
+ ' success!'))
792 printNicely(red('A name should begin with a \'@\''))
797 Report a user as a spam account
799 t
= Twitter(auth
=authen())
800 screen_name
= g
['stuff'].split()[0]
801 if screen_name
.startswith('@'):
803 screen_name
=screen_name
[1:])
804 printNicely(green('You reported ' + screen_name
+ '.'))
806 printNicely(red('Sorry I can\'t understand.'))
814 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
815 # Get list name and owner
817 owner
, slug
= list_name
.split('/')
818 if slug
.startswith('@'):
823 light_magenta('List name should follow "@owner/list_name" format.'))
824 raise Exception('Wrong list name')
831 rel
= t
.lists
.list(screen_name
=g
['original_name'])
835 printNicely(light_magenta('You belong to no lists :)'))
842 owner
, slug
= get_slug()
843 res
= t
.lists
.statuses(
845 owner_screen_name
=owner
,
847 include_entities
=False)
857 owner
, slug
= get_slug()
861 while next_cursor
!= 0:
864 owner_screen_name
=owner
,
866 include_entities
=False)
868 rel
[u
['name']] = '@' + u
['screen_name']
869 next_cursor
= m
['next_cursor']
870 printNicely('All: ' + str(len(rel
)) + ' members.')
872 user
= ' ' + cycle_color(name
)
873 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
877 def list_subscribers(t
):
881 owner
, slug
= get_slug()
885 while next_cursor
!= 0:
886 m
= t
.lists
.subscribers(
888 owner_screen_name
=owner
,
890 include_entities
=False)
892 rel
[u
['name']] = '@' + u
['screen_name']
893 next_cursor
= m
['next_cursor']
894 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
896 user
= ' ' + cycle_color(name
)
897 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
903 Add specific user to a list
905 owner
, slug
= get_slug()
907 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
908 if user_name
.startswith('@'):
909 user_name
= user_name
[1:]
911 t
.lists
.members
.create(
913 owner_screen_name
=owner
,
914 screen_name
=user_name
)
915 printNicely(green('Added.'))
917 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
922 Remove specific user from a list
924 owner
, slug
= get_slug()
926 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
927 if user_name
.startswith('@'):
928 user_name
= user_name
[1:]
930 t
.lists
.members
.destroy(
932 owner_screen_name
=owner
,
933 screen_name
=user_name
)
934 printNicely(green('Gone.'))
936 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
939 def list_subscribe(t
):
943 owner
, slug
= get_slug()
946 t
.lists
.subscribers
.create(
948 owner_screen_name
=owner
)
949 printNicely(green('Done.'))
952 light_magenta('I\'m sorry you can not subscribe to this list.'))
955 def list_unsubscribe(t
):
959 owner
, slug
= get_slug()
962 t
.lists
.subscribers
.destroy(
964 owner_screen_name
=owner
)
965 printNicely(green('Done.'))
968 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
977 while next_cursor
!= 0:
978 res
= t
.lists
.ownerships(
979 screen_name
=g
['original_name'],
982 next_cursor
= res
['next_cursor']
986 printNicely(light_magenta('You own no lists :)'))
993 name
= raw_input(light_magenta('New list\'s name: '))
994 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
995 description
= raw_input(light_magenta('New list\'s description: '))
1000 description
=description
)
1001 printNicely(green(name
+ ' list is created.'))
1003 printNicely(red('Oops something is wrong with Twitter :('))
1010 slug
= raw_input(light_magenta('Your list that you want to update: '))
1011 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1012 mode
= raw_input(light_magenta('Update mode (public/private): '))
1013 description
= raw_input(light_magenta('Update description: '))
1017 slug
='-'.join(slug
.split()),
1018 owner_screen_name
=g
['original_name'],
1021 description
=description
)
1025 owner_screen_name
=g
['original_name'],
1027 description
=description
)
1028 printNicely(green(slug
+ ' list is updated.'))
1030 printNicely(red('Oops something is wrong with Twitter :('))
1037 slug
= raw_input(light_magenta('Your list that you want to update: '))
1040 slug
='-'.join(slug
.split()),
1041 owner_screen_name
=g
['original_name'])
1042 printNicely(green(slug
+ ' list is deleted.'))
1044 printNicely(red('Oops something is wrong with Twitter :('))
1051 t
= Twitter(auth
=authen())
1052 # List all lists or base on action
1054 g
['list_action'] = g
['stuff'].split()[0]
1061 'all_mem': list_members
,
1062 'all_sub': list_subscribers
,
1065 'sub': list_subscribe
,
1066 'unsub': list_unsubscribe
,
1069 'update': list_update
,
1073 return action_ary
[g
['list_action']](t
)
1075 printNicely(red('Please try again.'))
1080 Unix's command `cal`
1083 rel
= os
.popen('cal').read().split('\n')
1086 show_calendar(month
, date
, rel
)
1091 Browse and change config
1093 all_config
= get_all_config()
1094 g
['stuff'] = g
['stuff'].strip()
1097 for k
in all_config
:
1099 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1101 guide
= 'Detailed explanation can be found at ' + \
1102 color_func(c
['TWEET']['link'])(
1103 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1105 # Print specific config
1106 elif len(g
['stuff'].split()) == 1:
1107 if g
['stuff'] in all_config
:
1110 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1113 printNicely(red('No such config key.'))
1114 # Print specific config's default value
1115 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1116 key
= g
['stuff'].split()[0]
1118 value
= get_default_config(key
)
1119 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1123 light_magenta('This config key does not exist in default.'))
1124 # Delete specific config key in config file
1125 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1126 key
= g
['stuff'].split()[0]
1129 printNicely(green('Config key is dropped.'))
1131 printNicely(red('No such config key.'))
1132 # Set specific config
1133 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1134 key
= g
['stuff'].split()[0]
1135 value
= g
['stuff'].split()[-1]
1136 if key
== 'THEME' and not validate_theme(value
):
1137 printNicely(red('Invalid theme\'s value.'))
1140 set_config(key
, value
)
1141 # Apply theme immediately
1144 g
['decorated_name'] = lambda x
: color_func(
1145 c
['DECORATED_NAME'])(
1147 printNicely(green('Updated successfully.'))
1149 printNicely(light_magenta('Not valid value.'))
1153 printNicely(light_magenta('Sorry I can\'s understand.'))
1158 List and change theme
1162 for theme
in g
['themes']:
1163 line
= light_magenta(theme
)
1164 if c
['THEME'] == theme
:
1165 line
= ' ' * 2 + light_yellow('* ') + line
1167 line
= ' ' * 4 + line
1173 reload_theme(g
['stuff'])
1174 # Redefine decorated_name
1175 g
['decorated_name'] = lambda x
: color_func(
1176 c
['DECORATED_NAME'])(
1178 printNicely(green('Theme changed.'))
1180 printNicely(red('No such theme exists.'))
1183 def help_discover():
1188 # Discover the world
1190 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1191 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1192 'You can try ' + light_green('trend US') + ' or ' + \
1193 light_green('trend JP Tokyo') + '.\n'
1194 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1195 light_green('home 7') + ' will show 7 tweets.\n'
1196 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1197 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1198 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1199 magenta('@mdo') + '.\n'
1200 usage
+= s
* 2 + light_green('view @mdo') + \
1201 ' will show ' + magenta('@mdo') + '\'s home.\n'
1202 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1203 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1204 'Search can be performed with or without hashtag.\n'
1215 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1216 usage
+= s
* 2 + light_green('t oops ') + \
1217 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1219 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1220 light_yellow('[id=12]') + '.\n'
1222 light_green('quote 12 ') + ' will quote the tweet with ' + \
1223 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1224 'the quote will be canceled.\n'
1226 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1227 light_yellow('[id=12]') + '.\n'
1228 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1229 light_yellow('oops') + '" to tweet with ' + \
1230 light_yellow('[id=12]') + '.\n'
1232 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1233 light_yellow('[id=12]') + '.\n'
1235 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1236 light_yellow('[id=12]') + '.\n'
1238 light_green('del 12 ') + ' will delete tweet with ' + \
1239 light_yellow('[id=12]') + '.\n'
1240 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1241 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1242 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1243 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1247 def help_messages():
1254 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1255 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1256 light_green('inbox 7') + ' will show newest 7 messages.\n'
1257 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1258 light_green('sent 7') + ' will show newest 7 messages.\n'
1259 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1260 magenta('@dtvd88') + '.\n'
1261 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1262 light_yellow('[message_id=5]') + '.\n'
1266 def help_friends_and_followers():
1268 Friends and Followers
1271 # Follower and following
1273 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1275 light_green('ls fl') + \
1276 ' will list all followers (people who are following you).\n'
1278 light_green('ls fr') + \
1279 ' will list all friends (people who you are following).\n'
1280 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1281 magenta('@dtvd88') + '.\n'
1282 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1283 magenta('@dtvd88') + '.\n'
1284 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1285 magenta('@dtvd88') + '.\n'
1286 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1289 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1290 magenta('@dtvd88') + '.\n'
1291 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1292 magenta('@dtvd88') + '.\n'
1293 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1294 magenta('@dtvd88') + ' as a spam account.\n'
1305 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1306 usage
+= s
* 2 + light_green('list') + \
1307 ' will show all lists you are belong to.\n'
1308 usage
+= s
* 2 + light_green('list home') + \
1309 ' will show timeline of list. You will be asked for list\'s name.\n'
1310 usage
+= s
* 2 + light_green('list all_mem') + \
1311 ' will show list\'s all members.\n'
1312 usage
+= s
* 2 + light_green('list all_sub') + \
1313 ' will show list\'s all subscribers.\n'
1314 usage
+= s
* 2 + light_green('list add') + \
1315 ' will add specific person to a list owned by you.' + \
1316 ' You will be asked for list\'s name and person\'s name.\n'
1317 usage
+= s
* 2 + light_green('list rm') + \
1318 ' will remove specific person from a list owned by you.' + \
1319 ' You will be asked for list\'s name and person\'s name.\n'
1320 usage
+= s
* 2 + light_green('list sub') + \
1321 ' will subscribe you to a specific list.\n'
1322 usage
+= s
* 2 + light_green('list unsub') + \
1323 ' will unsubscribe you from a specific list.\n'
1324 usage
+= s
* 2 + light_green('list own') + \
1325 ' will show all list owned by you.\n'
1326 usage
+= s
* 2 + light_green('list new') + \
1327 ' will create a new list.\n'
1328 usage
+= s
* 2 + light_green('list update') + \
1329 ' will update a list owned by you.\n'
1330 usage
+= s
* 2 + light_green('list del') + \
1331 ' will delete a list owned by you.\n'
1342 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1343 usage
+= s
* 2 + light_green('switch public #AKB') + \
1344 ' will switch to public stream and follow "' + \
1345 light_yellow('AKB') + '" keyword.\n'
1346 usage
+= s
* 2 + light_green('switch mine') + \
1347 ' will switch to your personal stream.\n'
1348 usage
+= s
* 2 + light_green('switch mine -f ') + \
1349 ' will prompt to enter the filter.\n'
1350 usage
+= s
* 3 + light_yellow('Only nicks') + \
1351 ' filter will decide nicks will be INCLUDE ONLY.\n'
1352 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1353 ' filter will decide nicks will be EXCLUDE.\n'
1354 usage
+= s
* 2 + light_green('switch mine -d') + \
1355 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1364 h
, w
= os
.popen('stty size', 'r').read().split()
1367 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1368 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1369 usage
+= s
+ 'You are ' + \
1370 light_yellow('already') + ' on your personal stream.\n'
1371 usage
+= s
+ 'Any update from Twitter will show up ' + \
1372 light_yellow('immediately') + '.\n'
1373 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1374 # Twitter help section
1376 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1377 usage
+= s
* 2 + light_green('h discover') + \
1378 ' will show help for discover commands.\n'
1379 usage
+= s
* 2 + light_green('h tweets') + \
1380 ' will show help for tweets commands.\n'
1381 usage
+= s
* 2 + light_green('h messages') + \
1382 ' will show help for messages commands.\n'
1383 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1384 ' will show help for friends and followers commands.\n'
1385 usage
+= s
* 2 + light_green('h list') + \
1386 ' will show help for list commands.\n'
1387 usage
+= s
* 2 + light_green('h stream') + \
1388 ' will show help for stream commands.\n'
1391 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1392 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1393 'will be evaluate by Python interpreter.\n'
1394 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1395 ' for current month.\n'
1398 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1399 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1400 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1401 ' theme immediately.\n'
1402 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1404 light_green('config ASCII_ART') + ' will output current value of ' +\
1405 light_yellow('ASCII_ART') + ' config key.\n'
1407 light_green('config TREND_MAX default') + ' will output default value of ' + \
1408 light_yellow('TREND_MAX') + ' config key.\n'
1410 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1411 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1413 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1414 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1415 light_yellow('True') + '.\n'
1418 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1419 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1420 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1421 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1422 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1423 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1426 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1427 usage
+= s
+ 'Have fun and hang tight! \n'
1430 'discover': help_discover
,
1431 'tweets': help_tweets
,
1432 'messages': help_messages
,
1433 'friends_and_followers': help_friends_and_followers
,
1435 'stream': help_stream
,
1438 d
[g
['stuff'].strip()]()
1445 Pause stream display
1447 db
.semaphore_update_pause(True)
1448 printNicely(green('Stream is paused'))
1455 db
.semaphore_update_pause(False)
1456 printNicely(green('Stream is running back now'))
1472 os
.system('rm -rf rainbow.db')
1473 printNicely(green('See you next time :)'))
1481 Reset prefix of line
1484 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1487 printNicely(str(eval(g
['cmd'])))
1544 Listen to user's input
1549 ['public', 'mine'], # switch
1564 ['image'], # show image
1566 ['fl', 'fr'], # list
1593 [key
for key
in dict(get_all_config())], # config
1594 g
['themes'], # theme
1599 'friends_and_followers',
1609 init_interactive_shell(d
)
1614 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1618 cmd
= line
.split()[0]
1623 # Lock the semaphore
1624 db
.semaphore_update_lock(True)
1625 # Save cmd to global variable and call process
1626 g
['stuff'] = ' '.join(line
.split()[1:])
1627 # Process the command
1630 if cmd
in ['t', 'rt', 'rep']:
1634 # Release the semaphore lock
1635 db
.semaphore_update_lock(False)
1637 printNicely(red('OMG something is wrong with Twitter right now.'))
1640 def stream(domain
, args
, name
='Rainbow Stream'):
1646 c
['USER_DOMAIN']: name
,
1647 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1648 c
['SITE_DOMAIN']: name
,
1651 ascii_art(art_dict
[domain
])
1652 # These arguments are optional:
1654 timeout
=args
.timeout
,
1656 heartbeat_timeout
=args
.heartbeat_timeout
)
1659 if args
.track_keywords
:
1660 query_args
['track'] = args
.track_keywords
1662 stream
= TwitterStream(
1667 if domain
== c
['USER_DOMAIN']:
1668 tweet_iter
= stream
.user(**query_args
)
1669 elif domain
== c
['SITE_DOMAIN']:
1670 tweet_iter
= stream
.site(**query_args
)
1672 if args
.track_keywords
:
1673 tweet_iter
= stream
.statuses
.filter(**query_args
)
1675 tweet_iter
= stream
.statuses
.sample()
1676 # Block new stream until other one exits
1677 StreamLock
.acquire()
1678 g
['stream_stop'] = False
1679 for tweet
in tweet_iter
:
1680 if(g
['stream_stop'] == True):
1681 StreamLock
.release()
1685 elif tweet
is Timeout
:
1686 printNicely("-- Timeout --")
1687 elif tweet
is HeartbeatTimeout
:
1688 printNicely("-- Heartbeat Timeout --")
1689 elif tweet
is Hangup
:
1690 printNicely("-- Hangup --")
1691 elif tweet
.get('text'):
1694 keyword
=args
.track_keywords
,
1695 check_semaphore
=True,
1699 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']) + readline
.get_line_buffer())
1701 elif tweet
.get('direct_message'):
1702 print_message(tweet
['direct_message'], check_semaphore
=True)
1703 except TwitterHTTPError
:
1706 magenta("We have maximum connection problem with twitter'stream API right now :("))
1714 args
= parse_arguments()
1717 except TwitterHTTPError
:
1720 magenta("We have maximum connection problem with twitter'stream API right now :("))
1721 printNicely(magenta("Let's try again later."))
1723 os
.system('rm -rf rainbow.db')
1725 # Spawn stream thread
1726 th
= threading
.Thread(target
=stream
, args
=(c
['USER_DOMAIN'], args
, g
['original_name']))
1729 # Start listen process