2 Colorful user's timeline stream
4 from multiprocessing
import Process
15 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
16 from twitter
.api
import *
17 from twitter
.oauth
import OAuth
, read_token_file
18 from twitter
.oauth_dance
import oauth_dance
19 from twitter
.util
import printNicely
24 from .consumer
import *
25 from .interactive
import *
27 from .c_image
import *
28 from .py3patch
import *
80 def parse_arguments():
84 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
88 help='Timeout for the stream (seconds).')
91 '--heartbeat-timeout',
92 help='Set heartbeat timeout.',
98 help='Set stream to non-blocking.')
102 help='Search the stream for specific text.')
106 help='Filter specific screen_name.')
110 help='Ignore specific screen_name.')
115 help='Display all image on terminal.')
116 return parser
.parse_args()
121 Authenticate with Twitter OAuth
123 # When using rainbow stream you must authorize.
124 twitter_credential
= os
.environ
.get(
128 '')) + os
.sep
+ '.rainbow_oauth'
129 if not os
.path
.exists(twitter_credential
):
130 oauth_dance("Rainbow Stream",
134 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
147 ctrl_c_handler
= lambda signum
, frame
: quit()
148 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
150 t
= Twitter(auth
=authen())
151 name
= '@' + t
.account
.verify_credentials()['screen_name']
152 if not get_config('PREFIX'):
153 set_config('PREFIX', name
)
154 g
['original_name'] = name
[1:]
155 g
['decorated_name'] = lambda x
: color_func(
156 c
['DECORATED_NAME'])(
159 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
160 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
162 db
.theme_store(c
['THEME'])
164 db
.semaphore_store(False, False)
166 c
['IMAGE_ON_TERM'] = args
.image_on_term
174 target
= g
['stuff'].split()[0]
176 args
= parse_arguments()
178 if g
['stuff'].split()[-1] == '-f':
179 guide
= 'To ignore an option, just hit Enter key.'
180 printNicely(light_magenta(guide
))
181 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
182 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
183 args
.filter = filter(None, only
.split(','))
184 args
.ignore
= filter(None, ignore
.split(','))
185 elif g
['stuff'].split()[-1] == '-d':
186 args
.filter = c
['ONLY_LIST']
187 args
.ignore
= c
['IGNORE_LIST']
189 printNicely(red('Sorry, wrong format.'))
192 if target
== 'public':
193 keyword
= g
['stuff'].split()[1]
194 if keyword
[0] == '#':
195 keyword
= keyword
[1:]
197 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
198 args
.track_keywords
= keyword
206 g
['stream_pid'] = p
.pid
208 elif target
== 'mine':
210 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
219 g
['stream_pid'] = p
.pid
222 printNicely(cyan('Only: ' + str(args
.filter)))
224 printNicely(red('Ignore: ' + str(args
.ignore
)))
227 printNicely(red('Sorry I can\'t understand.'))
234 t
= Twitter(auth
=authen())
235 # Get country and town
237 country
= g
['stuff'].split()[0]
241 town
= g
['stuff'].split()[1]
244 avail
= t
.trends
.available()
247 trends
= t
.trends
.place(_id
=1)[0]['trends']
250 for location
in avail
:
251 # Search for country and Town
253 if location
['countryCode'] == country \
254 and location
['placeType']['name'] == 'Town' \
255 and location
['name'] == town
:
256 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
258 # Search for country only
260 if location
['countryCode'] == country \
261 and location
['placeType']['name'] == 'Country':
262 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
270 t
= Twitter(auth
=authen())
271 num
= c
['HOME_TWEET_NUM']
272 if g
['stuff'].isdigit():
273 num
= int(g
['stuff'])
274 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
283 t
= Twitter(auth
=authen())
284 user
= g
['stuff'].split()[0]
287 num
= int(g
['stuff'].split()[1])
289 num
= c
['HOME_TWEET_NUM']
290 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
294 printNicely(red('A name should begin with a \'@\''))
301 t
= Twitter(auth
=authen())
302 num
= c
['HOME_TWEET_NUM']
303 if g
['stuff'].isdigit():
304 num
= int(g
['stuff'])
305 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
314 t
= Twitter(auth
=authen())
315 t
.statuses
.update(status
=g
['stuff'])
322 t
= Twitter(auth
=authen())
324 id = int(g
['stuff'].split()[0])
326 printNicely(red('Sorry I can\'t understand.'))
328 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
329 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
336 t
= Twitter(auth
=authen())
338 id = int(g
['stuff'].split()[0])
340 printNicely(red('Sorry I can\'t understand.'))
342 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
343 tweet
= t
.statuses
.show(id=tid
)
344 screen_name
= tweet
['user']['screen_name']
346 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
347 quote
= quote
.encode('utf8')
348 notice
= light_magenta('Compose mode ')
349 notice
+= light_yellow('(Enter nothing will cancel the quote)')
350 notice
+= light_magenta(':')
352 extra
= raw_input(quote
)
354 t
.statuses
.update(status
=quote
+ extra
)
356 printNicely(light_magenta('No text added.'))
363 t
= Twitter(auth
=authen())
366 id = int(g
['stuff'].split()[0])
368 printNicely(red('Sorry I can\'t understand.'))
370 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
371 # Get display num if exist
373 num
= int(g
['stuff'].split()[1])
375 num
= c
['RETWEETS_SHOW_NUM']
376 # Get result and display
377 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
379 printNicely(magenta('This tweet has no retweet.'))
381 for tweet
in reversed(rt_ary
):
390 t
= Twitter(auth
=authen())
392 id = int(g
['stuff'].split()[0])
394 printNicely(red('Sorry I can\'t understand.'))
396 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
397 t
.favorites
.create(_id
=tid
, include_entities
=False)
398 printNicely(green('Favorited.'))
399 draw(t
.statuses
.show(id=tid
))
407 t
= Twitter(auth
=authen())
409 id = int(g
['stuff'].split()[0])
411 printNicely(red('Sorry I can\'t understand.'))
413 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
414 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
415 status
= ' '.join(g
['stuff'].split()[1:])
416 status
= '@' + user
+ ' ' + status
.decode('utf-8')
417 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
424 t
= Twitter(auth
=authen())
426 rid
= int(g
['stuff'].split()[0])
428 printNicely(red('Sorry I can\'t understand.'))
430 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
431 t
.statuses
.destroy(id=tid
)
432 printNicely(green('Okay it\'s gone.'))
439 t
= Twitter(auth
=authen())
441 id = int(g
['stuff'].split()[0])
443 printNicely(red('Sorry I can\'t understand.'))
445 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
446 t
.favorites
.destroy(_id
=tid
)
447 printNicely(green('Okay it\'s unfavorited.'))
448 draw(t
.statuses
.show(id=tid
))
456 t
= Twitter(auth
=authen())
457 g
['stuff'] = g
['stuff'].strip()
458 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
460 printNicely('Newest tweets:')
461 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
466 printNicely(magenta('I\'m afraid there is no result'))
471 Send a direct message
473 t
= Twitter(auth
=authen())
474 user
= g
['stuff'].split()[0]
475 if user
[0].startswith('@'):
477 content
= g
['stuff'].split()[1]
479 printNicely(red('Sorry I can\'t understand.'))
480 t
.direct_messages
.new(
481 screen_name
=user
[1:],
484 printNicely(green('Message sent.'))
486 printNicely(red('A name should begin with a \'@\''))
493 t
= Twitter(auth
=authen())
495 target
= g
['stuff'].split()[0]
496 if target
!= 'image':
498 id = int(g
['stuff'].split()[1])
499 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
500 tweet
= t
.statuses
.show(id=tid
)
501 media
= tweet
['entities']['media']
503 res
= requests
.get(m
['media_url'])
504 img
= Image
.open(BytesIO(res
.content
))
507 printNicely(red('Sorry I can\'t show this image.'))
514 t
= Twitter(auth
=authen())
516 if not g
['stuff'].isdigit():
518 tid
= db
.rainbow_to_tweet_query(g
['stuff'])[0].tweet_id
519 tweet
= t
.statuses
.show(id=tid
)
521 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
523 printNicely(light_magenta('No url here @.@!'))
525 for link
in link_ary
:
526 webbrowser
.open(link
)
528 printNicely(red('Sorry I can\'t open url in this tweet.'))
533 List friends for followers
535 t
= Twitter(auth
=authen())
538 name
= g
['stuff'].split()[1]
539 if name
.startswith('@'):
542 printNicely(red('A name should begin with a \'@\''))
543 raise Exception('Invalid name')
545 name
= g
['original_name']
546 # Get list followers or friends
548 target
= g
['stuff'].split()[0]
550 printNicely(red('Omg some syntax is wrong.'))
552 d
= {'fl': 'followers', 'fr': 'friends'}
556 while next_cursor
!= 0:
557 list = getattr(t
, d
[target
]).list(
561 include_entities
=False,
563 for u
in list['users']:
564 rel
[u
['name']] = '@' + u
['screen_name']
565 next_cursor
= list['next_cursor']
567 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
569 user
= ' ' + cycle_color(name
)
570 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
576 Inbox direct messages
578 t
= Twitter(auth
=authen())
579 num
= c
['MESSAGES_DISPLAY']
581 if g
['stuff'].isdigit():
584 # Max message per page is 20 so we have to loop
586 rel
= rel
+ t
.direct_messages(
589 include_entities
=False,
594 rel
= rel
+ t
.direct_messages(
597 include_entities
=False,
601 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
602 for m
in reversed(rel
):
611 t
= Twitter(auth
=authen())
612 num
= c
['MESSAGES_DISPLAY']
614 if g
['stuff'].isdigit():
615 num
= int(g
['stuff'])
617 # Max message per page is 20 so we have to loop
619 rel
= rel
+ t
.direct_messages
.sent(
622 include_entities
=False,
627 rel
= rel
+ t
.direct_messages
.sent(
630 include_entities
=False,
634 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
635 for m
in reversed(rel
):
644 t
= Twitter(auth
=authen())
646 rid
= int(g
['stuff'].split()[0])
648 printNicely(red('Sorry I can\'t understand.'))
649 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
650 t
.direct_messages
.destroy(id=mid
)
651 printNicely(green('Message deleted.'))
656 Show profile of a specific user
658 t
= Twitter(auth
=authen())
659 screen_name
= g
['stuff'].split()[0]
660 if screen_name
.startswith('@'):
663 screen_name
=screen_name
[1:],
664 include_entities
=False)
667 printNicely(red('Omg no user.'))
669 printNicely(red('A name should begin with a \'@\''))
676 t
= Twitter(auth
=authen())
677 screen_name
= g
['stuff'].split()[0]
678 if screen_name
.startswith('@'):
679 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
680 printNicely(green('You are following ' + screen_name
+ ' now!'))
682 printNicely(red('A name should begin with a \'@\''))
689 t
= Twitter(auth
=authen())
690 screen_name
= g
['stuff'].split()[0]
691 if screen_name
.startswith('@'):
692 t
.friendships
.destroy(
693 screen_name
=screen_name
[1:],
694 include_entities
=False)
695 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
697 printNicely(red('A name should begin with a \'@\''))
704 t
= Twitter(auth
=authen())
706 screen_name
= g
['stuff'].split()[0]
708 printNicely(red('A name should be specified. '))
710 if screen_name
.startswith('@'):
711 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
712 if isinstance(rel
, dict):
713 printNicely(green(screen_name
+ ' is muted.'))
715 printNicely(red(rel
))
717 printNicely(red('A name should begin with a \'@\''))
724 t
= Twitter(auth
=authen())
726 screen_name
= g
['stuff'].split()[0]
728 printNicely(red('A name should be specified. '))
730 if screen_name
.startswith('@'):
731 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
732 if isinstance(rel
, dict):
733 printNicely(green(screen_name
+ ' is unmuted.'))
735 printNicely(red(rel
))
737 printNicely(red('A name should begin with a \'@\''))
744 t
= Twitter(auth
=authen())
749 while next_cursor
!= 0:
750 list = t
.mutes
.users
.list(
751 screen_name
=g
['original_name'],
754 include_entities
=False,
756 for u
in list['users']:
757 rel
[u
['name']] = '@' + u
['screen_name']
758 next_cursor
= list['next_cursor']
760 printNicely('All: ' + str(len(rel
)) + ' people.')
762 user
= ' ' + cycle_color(name
)
763 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
771 t
= Twitter(auth
=authen())
772 screen_name
= g
['stuff'].split()[0]
773 if screen_name
.startswith('@'):
775 screen_name
=screen_name
[1:],
776 include_entities
=False,
778 printNicely(green('You blocked ' + screen_name
+ '.'))
780 printNicely(red('A name should begin with a \'@\''))
787 t
= Twitter(auth
=authen())
788 screen_name
= g
['stuff'].split()[0]
789 if screen_name
.startswith('@'):
791 screen_name
=screen_name
[1:],
792 include_entities
=False,
794 printNicely(green('Unblock ' + screen_name
+ ' success!'))
796 printNicely(red('A name should begin with a \'@\''))
801 Report a user as a spam account
803 t
= Twitter(auth
=authen())
804 screen_name
= g
['stuff'].split()[0]
805 if screen_name
.startswith('@'):
807 screen_name
=screen_name
[1:])
808 printNicely(green('You reported ' + screen_name
+ '.'))
810 printNicely(red('Sorry I can\'t understand.'))
818 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
819 # Get list name and owner
821 owner
, slug
= list_name
.split('/')
822 if slug
.startswith('@'):
827 light_magenta('List name should follow "@owner/list_name" format.'))
828 raise Exception('Wrong list name')
835 rel
= t
.lists
.list(screen_name
=g
['original_name'])
839 printNicely(light_magenta('You belong to no lists :)'))
846 owner
, slug
= get_slug()
847 res
= t
.lists
.statuses(
849 owner_screen_name
=owner
,
851 include_entities
=False)
861 owner
, slug
= get_slug()
865 while next_cursor
!= 0:
868 owner_screen_name
=owner
,
870 include_entities
=False)
872 rel
[u
['name']] = '@' + u
['screen_name']
873 next_cursor
= m
['next_cursor']
874 printNicely('All: ' + str(len(rel
)) + ' members.')
876 user
= ' ' + cycle_color(name
)
877 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
881 def list_subscribers(t
):
885 owner
, slug
= get_slug()
889 while next_cursor
!= 0:
890 m
= t
.lists
.subscribers(
892 owner_screen_name
=owner
,
894 include_entities
=False)
896 rel
[u
['name']] = '@' + u
['screen_name']
897 next_cursor
= m
['next_cursor']
898 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
900 user
= ' ' + cycle_color(name
)
901 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
907 Add specific user to a list
909 owner
, slug
= get_slug()
911 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
912 if user_name
.startswith('@'):
913 user_name
= user_name
[1:]
915 t
.lists
.members
.create(
917 owner_screen_name
=owner
,
918 screen_name
=user_name
)
919 printNicely(green('Added.'))
921 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
926 Remove specific user from a list
928 owner
, slug
= get_slug()
930 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
931 if user_name
.startswith('@'):
932 user_name
= user_name
[1:]
934 t
.lists
.members
.destroy(
936 owner_screen_name
=owner
,
937 screen_name
=user_name
)
938 printNicely(green('Gone.'))
940 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
943 def list_subscribe(t
):
947 owner
, slug
= get_slug()
950 t
.lists
.subscribers
.create(
952 owner_screen_name
=owner
)
953 printNicely(green('Done.'))
956 light_magenta('I\'m sorry you can not subscribe to this list.'))
959 def list_unsubscribe(t
):
963 owner
, slug
= get_slug()
966 t
.lists
.subscribers
.destroy(
968 owner_screen_name
=owner
)
969 printNicely(green('Done.'))
972 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
981 while next_cursor
!= 0:
982 res
= t
.lists
.ownerships(
983 screen_name
=g
['original_name'],
986 next_cursor
= res
['next_cursor']
990 printNicely(light_magenta('You own no lists :)'))
997 name
= raw_input(light_magenta('New list\'s name: '))
998 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
999 description
= raw_input(light_magenta('New list\'s description: '))
1004 description
=description
)
1005 printNicely(green(name
+ ' list is created.'))
1007 printNicely(red('Oops something is wrong with Twitter :('))
1014 slug
= raw_input(light_magenta('Your list that you want to update: '))
1015 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1016 mode
= raw_input(light_magenta('Update mode (public/private): '))
1017 description
= raw_input(light_magenta('Update description: '))
1021 slug
='-'.join(slug
.split()),
1022 owner_screen_name
=g
['original_name'],
1025 description
=description
)
1029 owner_screen_name
=g
['original_name'],
1031 description
=description
)
1032 printNicely(green(slug
+ ' list is updated.'))
1034 printNicely(red('Oops something is wrong with Twitter :('))
1041 slug
= raw_input(light_magenta('Your list that you want to update: '))
1044 slug
='-'.join(slug
.split()),
1045 owner_screen_name
=g
['original_name'])
1046 printNicely(green(slug
+ ' list is deleted.'))
1048 printNicely(red('Oops something is wrong with Twitter :('))
1055 t
= Twitter(auth
=authen())
1056 # List all lists or base on action
1058 g
['list_action'] = g
['stuff'].split()[0]
1065 'all_mem': list_members
,
1066 'all_sub': list_subscribers
,
1069 'sub': list_subscribe
,
1070 'unsub': list_unsubscribe
,
1073 'update': list_update
,
1077 return action_ary
[g
['list_action']](t
)
1079 printNicely(red('Please try again.'))
1084 Unix's command `cal`
1087 rel
= os
.popen('cal').read().split('\n')
1090 show_calendar(month
, date
, rel
)
1095 Browse and change config
1097 all_config
= get_all_config()
1098 g
['stuff'] = g
['stuff'].strip()
1101 for k
in all_config
:
1103 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1105 guide
= 'Detailed explanation can be found at ' + \
1106 color_func(c
['TWEET']['link'])(
1107 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1109 # Print specific config
1110 elif len(g
['stuff'].split()) == 1:
1111 if g
['stuff'] in all_config
:
1114 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1117 printNicely(red('No such config key.'))
1118 # Print specific config's default value
1119 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1120 key
= g
['stuff'].split()[0]
1122 value
= get_default_config(key
)
1123 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1127 light_magenta('This config key does not exist in default.'))
1128 # Delete specific config key in config file
1129 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1130 key
= g
['stuff'].split()[0]
1133 printNicely(green('Config key is dropped.'))
1135 printNicely(red('No such config key.'))
1136 # Set specific config
1137 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1138 key
= g
['stuff'].split()[0]
1139 value
= g
['stuff'].split()[-1]
1140 if key
== 'THEME' and not validate_theme(value
):
1141 printNicely(red('Invalid theme\'s value.'))
1144 set_config(key
, value
)
1145 # Apply theme immediately
1148 g
['decorated_name'] = lambda x
: color_func(
1149 c
['DECORATED_NAME'])(
1151 printNicely(green('Updated successfully.'))
1153 printNicely(light_magenta('Not valid value.'))
1157 printNicely(light_magenta('Sorry I can\'s understand.'))
1162 List and change theme
1166 for theme
in g
['themes']:
1167 line
= light_magenta(theme
)
1168 if c
['THEME'] == theme
:
1169 line
= ' ' * 2 + light_yellow('* ') + line
1171 line
= ' ' * 4 + line
1177 reload_theme(g
['stuff'])
1178 # Redefine decorated_name
1179 g
['decorated_name'] = lambda x
: color_func(
1180 c
['DECORATED_NAME'])(
1182 printNicely(green('Theme changed.'))
1184 printNicely(red('No such theme exists.'))
1187 def help_discover():
1192 # Discover the world
1194 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1195 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1196 'You can try ' + light_green('trend US') + ' or ' + \
1197 light_green('trend JP Tokyo') + '.\n'
1198 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1199 light_green('home 7') + ' will show 7 tweets.\n'
1200 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1201 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1202 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1203 magenta('@mdo') + '.\n'
1204 usage
+= s
* 2 + light_green('view @mdo') + \
1205 ' will show ' + magenta('@mdo') + '\'s home.\n'
1206 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1207 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1208 'Search can be performed with or without hashtag.\n'
1219 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1220 usage
+= s
* 2 + light_green('t oops ') + \
1221 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1223 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1224 light_yellow('[id=12]') + '.\n'
1226 light_green('quote 12 ') + ' will quote the tweet with ' + \
1227 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1228 'the quote will be canceled.\n'
1230 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1231 light_yellow('[id=12]') + '.\n'
1232 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1233 light_yellow('oops') + '" to tweet with ' + \
1234 light_yellow('[id=12]') + '.\n'
1236 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1237 light_yellow('[id=12]') + '.\n'
1239 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1240 light_yellow('[id=12]') + '.\n'
1242 light_green('del 12 ') + ' will delete tweet with ' + \
1243 light_yellow('[id=12]') + '.\n'
1244 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1245 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1246 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1247 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1251 def help_messages():
1258 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1259 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1260 light_green('inbox 7') + ' will show newest 7 messages.\n'
1261 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1262 light_green('sent 7') + ' will show newest 7 messages.\n'
1263 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1264 magenta('@dtvd88') + '.\n'
1265 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1266 light_yellow('[message_id=5]') + '.\n'
1270 def help_friends_and_followers():
1272 Friends and Followers
1275 # Follower and following
1277 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1279 light_green('ls fl') + \
1280 ' will list all followers (people who are following you).\n'
1282 light_green('ls fr') + \
1283 ' will list all friends (people who you are following).\n'
1284 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1285 magenta('@dtvd88') + '.\n'
1286 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1289 magenta('@dtvd88') + '.\n'
1290 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1291 magenta('@dtvd88') + '.\n'
1292 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1293 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1294 magenta('@dtvd88') + '.\n'
1295 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1296 magenta('@dtvd88') + '.\n'
1297 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1298 magenta('@dtvd88') + ' as a spam account.\n'
1309 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1310 usage
+= s
* 2 + light_green('list') + \
1311 ' will show all lists you are belong to.\n'
1312 usage
+= s
* 2 + light_green('list home') + \
1313 ' will show timeline of list. You will be asked for list\'s name.\n'
1314 usage
+= s
* 2 + light_green('list all_mem') + \
1315 ' will show list\'s all members.\n'
1316 usage
+= s
* 2 + light_green('list all_sub') + \
1317 ' will show list\'s all subscribers.\n'
1318 usage
+= s
* 2 + light_green('list add') + \
1319 ' will add specific person to a list owned by you.' + \
1320 ' You will be asked for list\'s name and person\'s name.\n'
1321 usage
+= s
* 2 + light_green('list rm') + \
1322 ' will remove specific person from a list owned by you.' + \
1323 ' You will be asked for list\'s name and person\'s name.\n'
1324 usage
+= s
* 2 + light_green('list sub') + \
1325 ' will subscribe you to a specific list.\n'
1326 usage
+= s
* 2 + light_green('list unsub') + \
1327 ' will unsubscribe you from a specific list.\n'
1328 usage
+= s
* 2 + light_green('list own') + \
1329 ' will show all list owned by you.\n'
1330 usage
+= s
* 2 + light_green('list new') + \
1331 ' will create a new list.\n'
1332 usage
+= s
* 2 + light_green('list update') + \
1333 ' will update a list owned by you.\n'
1334 usage
+= s
* 2 + light_green('list del') + \
1335 ' will delete a list owned by you.\n'
1346 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1347 usage
+= s
* 2 + light_green('switch public #AKB') + \
1348 ' will switch to public stream and follow "' + \
1349 light_yellow('AKB') + '" keyword.\n'
1350 usage
+= s
* 2 + light_green('switch mine') + \
1351 ' will switch to your personal stream.\n'
1352 usage
+= s
* 2 + light_green('switch mine -f ') + \
1353 ' will prompt to enter the filter.\n'
1354 usage
+= s
* 3 + light_yellow('Only nicks') + \
1355 ' filter will decide nicks will be INCLUDE ONLY.\n'
1356 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1357 ' filter will decide nicks will be EXCLUDE.\n'
1358 usage
+= s
* 2 + light_green('switch mine -d') + \
1359 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1368 h
, w
= os
.popen('stty size', 'r').read().split()
1371 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1372 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1373 usage
+= s
+ 'You are ' + \
1374 light_yellow('already') + ' on your personal stream.\n'
1375 usage
+= s
+ 'Any update from Twitter will show up ' + \
1376 light_yellow('immediately') + '.\n'
1377 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1378 # Twitter help section
1380 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1381 usage
+= s
* 2 + light_green('h discover') + \
1382 ' will show help for discover commands.\n'
1383 usage
+= s
* 2 + light_green('h tweets') + \
1384 ' will show help for tweets commands.\n'
1385 usage
+= s
* 2 + light_green('h messages') + \
1386 ' will show help for messages commands.\n'
1387 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1388 ' will show help for friends and followers commands.\n'
1389 usage
+= s
* 2 + light_green('h list') + \
1390 ' will show help for list commands.\n'
1391 usage
+= s
* 2 + light_green('h stream') + \
1392 ' will show help for stream commands.\n'
1395 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1396 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1397 'will be evaluate by Python interpreter.\n'
1398 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1399 ' for current month.\n'
1402 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1403 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1404 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1405 ' theme immediately.\n'
1406 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1408 light_green('config ASCII_ART') + ' will output current value of ' +\
1409 light_yellow('ASCII_ART') + ' config key.\n'
1411 light_green('config TREND_MAX default') + ' will output default value of ' + \
1412 light_yellow('TREND_MAX') + ' config key.\n'
1414 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1415 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1417 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1418 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1419 light_yellow('True') + '.\n'
1422 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1423 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1424 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1425 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1426 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1427 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1430 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1431 usage
+= s
+ 'Have fun and hang tight! \n'
1434 'discover': help_discover
,
1435 'tweets': help_tweets
,
1436 'messages': help_messages
,
1437 'friends_and_followers': help_friends_and_followers
,
1439 'stream': help_stream
,
1442 d
[g
['stuff'].strip()]()
1449 Pause stream display
1451 db
.semaphore_update_pause(True)
1452 printNicely(green('Stream is paused'))
1459 db
.semaphore_update_pause(False)
1460 printNicely(green('Stream is running back now'))
1476 os
.system('rm -rf rainbow.db')
1477 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
1478 printNicely(green('See you next time :)'))
1486 Reset prefix of line
1489 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1492 printNicely(str(eval(g
['cmd'])))
1549 Listen to user's input
1554 ['public', 'mine'], # switch
1569 ['image'], # show image
1571 ['fl', 'fr'], # list
1598 [key
for key
in dict(get_all_config())], # config
1599 g
['themes'], # theme
1604 'friends_and_followers',
1614 init_interactive_shell(d
)
1619 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1623 cmd
= line
.split()[0]
1628 # Lock the semaphore
1629 db
.semaphore_update_lock(True)
1630 # Save cmd to global variable and call process
1631 g
['stuff'] = ' '.join(line
.split()[1:])
1632 # Process the command
1635 if cmd
in ['switch', 't', 'rt', 'rep']:
1639 # Release the semaphore lock
1640 db
.semaphore_update_lock(False)
1642 printNicely(red('OMG something is wrong with Twitter right now.'))
1645 def stream(domain
, args
, name
='Rainbow Stream'):
1651 c
['USER_DOMAIN']: name
,
1652 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1653 c
['SITE_DOMAIN']: name
,
1656 ascii_art(art_dict
[domain
])
1657 # These arguments are optional:
1659 timeout
=args
.timeout
,
1660 block
=not args
.no_block
,
1661 heartbeat_timeout
=args
.heartbeat_timeout
)
1664 if args
.track_keywords
:
1665 query_args
['track'] = args
.track_keywords
1667 stream
= TwitterStream(
1672 if domain
== c
['USER_DOMAIN']:
1673 tweet_iter
= stream
.user(**query_args
)
1674 elif domain
== c
['SITE_DOMAIN']:
1675 tweet_iter
= stream
.site(**query_args
)
1677 if args
.track_keywords
:
1678 tweet_iter
= stream
.statuses
.filter(**query_args
)
1680 tweet_iter
= stream
.statuses
.sample()
1681 for tweet
in tweet_iter
:
1683 printNicely("-- None --")
1684 elif tweet
is Timeout
:
1685 printNicely("-- Timeout --")
1686 elif tweet
is HeartbeatTimeout
:
1687 printNicely("-- Heartbeat Timeout --")
1688 elif tweet
is Hangup
:
1689 printNicely("-- Hangup --")
1690 elif tweet
.get('text'):
1693 keyword
=args
.track_keywords
,
1694 check_semaphore
=True,
1698 elif tweet
.get('direct_message'):
1699 print_message(tweet
['direct_message'], check_semaphore
=True)
1700 except TwitterHTTPError
:
1703 magenta("We have maximum connection problem with twitter'stream API right now :("))
1711 args
= parse_arguments()
1714 except TwitterHTTPError
:
1717 magenta("We have maximum connection problem with twitter'stream API right now :("))
1718 printNicely(magenta("Let's try again later."))
1720 os
.system('rm -rf rainbow.db')
1722 # Spawn stream process
1728 g
['original_name']))
1730 # Start listen process
1734 g
['stream_pid'] = p
.pid