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
20 from StringIO
import StringIO
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
71 def parse_arguments():
75 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
79 help='Timeout for the stream (seconds).')
82 '--heartbeat-timeout',
83 help='Set heartbeat timeout.',
89 help='Set stream to non-blocking.')
93 help='Search the stream for specific text.')
97 help='Filter specific screen_name.')
101 help='Ignore specific screen_name.')
106 help='Display all image on terminal.')
107 return parser
.parse_args()
112 Authenticate with Twitter OAuth
114 # When using rainbow stream you must authorize.
115 twitter_credential
= os
.environ
.get(
119 '')) + os
.sep
+ '.rainbow_oauth'
120 if not os
.path
.exists(twitter_credential
):
121 oauth_dance("Rainbow Stream",
125 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
133 def get_decorated_name():
135 Beginning of every line
137 t
= Twitter(auth
=authen())
138 name
= '@' + t
.account
.verify_credentials()['screen_name']
139 g
['original_name'] = name
[1:]
140 g
['decorated_name'] = color_func(c
['DECORATED_NAME'])('[' + name
+ ']: ')
141 g
['ascii_art'] = True
143 files
= os
.listdir(os
.path
.dirname(__file__
)+'/colorset')
144 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
147 db
.theme_store(c
['theme'])
155 target
= g
['stuff'].split()[0]
158 args
= parse_arguments()
160 if g
['stuff'].split()[-1] == '-f':
161 only
= raw_input('Only nicks: ')
162 ignore
= raw_input('Ignore nicks: ')
163 args
.filter = filter(None, only
.split(','))
164 args
.ignore
= filter(None, ignore
.split(','))
165 elif g
['stuff'].split()[-1] == '-d':
166 args
.filter = c
['ONLY_LIST']
167 args
.ignore
= c
['IGNORE_LIST']
169 printNicely(red('Sorry, wrong format.'))
173 if target
== 'public':
174 keyword
= g
['stuff'].split()[1]
175 if keyword
[0] == '#':
176 keyword
= keyword
[1:]
178 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
179 args
.track_keywords
= keyword
187 g
['stream_pid'] = p
.pid
190 elif target
== 'mine':
192 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
201 g
['stream_pid'] = p
.pid
204 printNicely(cyan('Only: ' + str(args
.filter)))
206 printNicely(red('Ignore: ' + str(args
.ignore
)))
208 g
['ascii_art'] = True
210 printNicely(red('Sorry I can\'t understand.'))
217 t
= Twitter(auth
=authen())
218 # Get country and town
220 country
= g
['stuff'].split()[0]
224 town
= g
['stuff'].split()[1]
228 avail
= t
.trends
.available()
231 trends
= t
.trends
.place(_id
=1)[0]['trends']
234 for location
in avail
:
235 # Search for country and Town
237 if location
['countryCode'] == country \
238 and location
['placeType']['name'] == 'Town' \
239 and location
['name'] == town
:
240 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
242 # Search for country only
244 if location
['countryCode'] == country \
245 and location
['placeType']['name'] == 'Country':
246 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
254 t
= Twitter(auth
=authen())
255 num
= c
['HOME_TWEET_NUM']
256 if g
['stuff'].isdigit():
257 num
= int(g
['stuff'])
258 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
259 draw(t
=tweet
, iot
=g
['iot'])
267 t
= Twitter(auth
=authen())
268 user
= g
['stuff'].split()[0]
271 num
= int(g
['stuff'].split()[1])
273 num
= c
['HOME_TWEET_NUM']
274 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
275 draw(t
=tweet
, iot
=g
['iot'])
278 printNicely(red('A name should begin with a \'@\''))
285 t
= Twitter(auth
=authen())
286 num
= c
['HOME_TWEET_NUM']
287 if g
['stuff'].isdigit():
288 num
= int(g
['stuff'])
289 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
290 draw(t
=tweet
, iot
=g
['iot'])
298 t
= Twitter(auth
=authen())
299 t
.statuses
.update(status
=g
['stuff'])
306 t
= Twitter(auth
=authen())
308 id = int(g
['stuff'].split()[0])
310 printNicely(red('Sorry I can\'t understand.'))
312 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
313 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
320 t
= Twitter(auth
=authen())
322 id = int(g
['stuff'].split()[0])
324 printNicely(red('Sorry I can\'t understand.'))
326 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
327 tweet
= t
.statuses
.show(id=tid
)
328 screen_name
= tweet
['user']['screen_name']
330 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
331 quote
= quote
.encode('utf8')
332 printNicely(light_magenta('Compose mode:'))
333 extra
= raw_input(quote
)
335 t
.statuses
.update(status
=quote
+extra
)
337 printNicely(light_magenta('No text added.'))
344 t
= Twitter(auth
=authen())
347 id = int(g
['stuff'].split()[0])
349 printNicely(red('Sorry I can\'t understand.'))
351 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
352 # Get display num if exist
354 num
= int(g
['stuff'].split()[1])
356 num
= c
['RETWEETS_SHOW_NUM']
357 # Get result and display
358 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
360 printNicely(magenta('This tweet has no retweet.'))
362 for tweet
in reversed(rt_ary
):
363 draw(t
=tweet
, iot
=g
['iot'])
371 t
= Twitter(auth
=authen())
373 id = int(g
['stuff'].split()[0])
375 printNicely(red('Sorry I can\'t understand.'))
377 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
378 t
.favorites
.create(_id
=tid
, include_entities
=False)
379 printNicely(green('Favorited.'))
380 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
388 t
= Twitter(auth
=authen())
390 id = int(g
['stuff'].split()[0])
392 printNicely(red('Sorry I can\'t understand.'))
394 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
395 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
396 status
= ' '.join(g
['stuff'].split()[1:])
397 status
= '@' + user
+ ' ' + status
.decode('utf-8')
398 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
405 t
= Twitter(auth
=authen())
407 rid
= int(g
['stuff'].split()[0])
409 printNicely(red('Sorry I can\'t understand.'))
411 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
412 t
.statuses
.destroy(id=tid
)
413 printNicely(green('Okay it\'s gone.'))
420 t
= Twitter(auth
=authen())
422 id = int(g
['stuff'].split()[0])
424 printNicely(red('Sorry I can\'t understand.'))
426 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
427 t
.favorites
.destroy(_id
=tid
)
428 printNicely(green('Okay it\'s unfavorited.'))
429 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
437 t
= Twitter(auth
=authen())
438 if g
['stuff'].startswith('#'):
439 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
441 printNicely('Newest tweets:')
442 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
445 keyword
=g
['stuff'].strip()[1:])
448 printNicely(magenta('I\'m afraid there is no result'))
450 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
455 Send a direct message
457 t
= Twitter(auth
=authen())
458 user
= g
['stuff'].split()[0]
459 if user
[0].startswith('@'):
461 content
= g
['stuff'].split()[1]
463 printNicely(red('Sorry I can\'t understand.'))
464 t
.direct_messages
.new(
465 screen_name
=user
[1:],
468 printNicely(green('Message sent.'))
470 printNicely(red('A name should begin with a \'@\''))
477 t
= Twitter(auth
=authen())
479 target
= g
['stuff'].split()[0]
480 if target
!= 'image':
482 id = int(g
['stuff'].split()[1])
483 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
484 tweet
= t
.statuses
.show(id=tid
)
485 media
= tweet
['entities']['media']
487 res
= requests
.get(m
['media_url'])
488 img
= Image
.open(StringIO(res
.content
))
491 printNicely(red('Sorry I can\'t show this image.'))
498 t
= Twitter(auth
=authen())
500 if not g
['stuff'].isdigit():
502 tid
= db
.rainbow_to_tweet_query(g
['stuff'])[0].tweet_id
503 tweet
= t
.statuses
.show(id=tid
)
504 link_ary
= [u
for u
in tweet
['text'].split() if u
.startswith('http://')]
506 printNicely(light_magenta('No url here @.@!'))
508 for link
in link_ary
:
509 webbrowser
.open(link
)
511 printNicely(red('Sorry I can\'t open url in this tweet.'))
516 List friends for followers
518 t
= Twitter(auth
=authen())
521 name
= g
['stuff'].split()[1]
522 if name
.startswith('@'):
525 printNicely(red('A name should begin with a \'@\''))
526 raise Exception('Invalid name')
528 name
= g
['original_name']
529 # Get list followers or friends
531 target
= g
['stuff'].split()[0]
533 printNicely(red('Omg some syntax is wrong.'))
535 d
= {'fl': 'followers', 'fr': 'friends'}
539 while next_cursor
!= 0:
540 list = getattr(t
, d
[target
]).list(
544 include_entities
=False,
546 for u
in list['users']:
547 rel
[u
['name']] = '@' + u
['screen_name']
548 next_cursor
= list['next_cursor']
550 printNicely('All: ' + str(len(rel
)) + ' people.')
552 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
558 Inbox direct messages
560 t
= Twitter(auth
=authen())
561 num
= c
['MESSAGES_DISPLAY']
563 if g
['stuff'].isdigit():
566 # Max message per page is 20 so we have to loop
568 rel
= rel
+ t
.direct_messages(
571 include_entities
=False,
576 rel
= rel
+ t
.direct_messages(
579 include_entities
=False,
583 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
584 for m
in reversed(rel
):
593 t
= Twitter(auth
=authen())
594 num
= c
['MESSAGES_DISPLAY']
596 if g
['stuff'].isdigit():
597 num
= int(g
['stuff'])
599 # Max message per page is 20 so we have to loop
601 rel
= rel
+ t
.direct_messages
.sent(
604 include_entities
=False,
609 rel
= rel
+ t
.direct_messages
.sent(
612 include_entities
=False,
616 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
617 for m
in reversed(rel
):
626 t
= Twitter(auth
=authen())
628 rid
= int(g
['stuff'].split()[0])
630 printNicely(red('Sorry I can\'t understand.'))
631 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
632 t
.direct_messages
.destroy(id=mid
)
633 printNicely(green('Message deleted.'))
638 Show profile of a specific user
640 t
= Twitter(auth
=authen())
641 screen_name
= g
['stuff'].split()[0]
642 if screen_name
.startswith('@'):
645 screen_name
=screen_name
[1:],
646 include_entities
=False)
647 show_profile(user
, g
['iot'])
649 printNicely(red('Omg no user.'))
651 printNicely(red('A name should begin with a \'@\''))
658 t
= Twitter(auth
=authen())
659 screen_name
= g
['stuff'].split()[0]
660 if screen_name
.startswith('@'):
661 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
662 printNicely(green('You are following ' + screen_name
+ ' now!'))
664 printNicely(red('A name should begin with a \'@\''))
671 t
= Twitter(auth
=authen())
672 screen_name
= g
['stuff'].split()[0]
673 if screen_name
.startswith('@'):
674 t
.friendships
.destroy(
675 screen_name
=screen_name
[1:],
676 include_entities
=False)
677 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
679 printNicely(red('A name should begin with a \'@\''))
686 t
= Twitter(auth
=authen())
688 screen_name
= g
['stuff'].split()[0]
690 printNicely(red('A name should be specified. '))
692 if screen_name
.startswith('@'):
693 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
694 if isinstance(rel
, dict):
695 printNicely(green(screen_name
+ ' is muted.'))
697 printNicely(red(rel
))
699 printNicely(red('A name should begin with a \'@\''))
706 t
= Twitter(auth
=authen())
708 screen_name
= g
['stuff'].split()[0]
710 printNicely(red('A name should be specified. '))
712 if screen_name
.startswith('@'):
713 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
714 if isinstance(rel
, dict):
715 printNicely(green(screen_name
+ ' is unmuted.'))
717 printNicely(red(rel
))
719 printNicely(red('A name should begin with a \'@\''))
726 t
= Twitter(auth
=authen())
731 while next_cursor
!= 0:
732 list = t
.mutes
.users
.list(
733 screen_name
=g
['original_name'],
736 include_entities
=False,
738 for u
in list['users']:
739 rel
[u
['name']] = '@' + u
['screen_name']
740 next_cursor
= list['next_cursor']
742 printNicely('All: ' + str(len(rel
)) + ' people.')
744 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
752 t
= Twitter(auth
=authen())
753 screen_name
= g
['stuff'].split()[0]
754 if screen_name
.startswith('@'):
756 screen_name
=screen_name
[1:],
757 include_entities
=False,
759 printNicely(green('You blocked ' + screen_name
+ '.'))
761 printNicely(red('A name should begin with a \'@\''))
768 t
= Twitter(auth
=authen())
769 screen_name
= g
['stuff'].split()[0]
770 if screen_name
.startswith('@'):
772 screen_name
=screen_name
[1:],
773 include_entities
=False,
775 printNicely(green('Unblock ' + screen_name
+ ' success!'))
777 printNicely(red('A name should begin with a \'@\''))
782 Report a user as a spam account
784 t
= Twitter(auth
=authen())
785 screen_name
= g
['stuff'].split()[0]
786 if screen_name
.startswith('@'):
788 screen_name
=screen_name
[1:])
789 printNicely(green('You reported ' + screen_name
+ '.'))
791 printNicely(red('Sorry I can\'t understand.'))
799 rel
= os
.popen('cal').read().split('\n')
802 show_calendar(month
, date
, rel
)
807 List and change theme
811 for theme
in g
['themes']:
813 # Detect custom config
814 if theme
== 'custom':
815 line
+= light_magenta('custom')
816 custom_path
= os
.environ
.get(
818 os
.environ
.get('USERPROFILE',
819 '')) + os
.sep
+ '.rainbow_config.json'
820 if not os
.path
.exists(custom_path
):
821 line
+= light_magenta(' (create your own config file at ~/.rainbow_config.json)')
823 line
+= light_magenta(' (loaded)')
825 line
+= light_magenta(theme
)
826 if c
['theme'] == theme
:
827 line
= ' '*2 + light_yellow('* ') + line
831 elif g
['stuff'] == 'current_as_default':
833 path
= os
.path
.dirname(__file__
) + '/colorset/init'
837 printNicely(light_green('Okay it will be applied from next time :)'))
842 if g
['stuff'] != 'custom':
843 new_config
= os
.path
.dirname(__file__
) + '/colorset/' + g
['stuff'] + '.json'
845 new_config
= os
.environ
.get(
846 'HOME',os
.environ
.get(
848 '')) + os
.sep
+ '.rainbow_config.json'
849 new_config
= load_config(new_config
)
851 for nc
in new_config
:
852 c
[nc
] = new_config
[nc
]
853 # Update db and reset colors
854 db
.theme_update(g
['stuff'])
855 c
['theme'] = g
['stuff']
857 g
['decorated_name'] = color_func(
858 c
['DECORATED_NAME'])(
859 '[@' + g
['original_name'] + ']: ')
860 printNicely(green('Theme changed.'))
862 if g
['stuff'] == 'custom':
863 printNicely(red('~/.rainbow_config.json is not exists!'))
865 printNicely(red('No such theme exists.'))
873 h
, w
= os
.popen('stty size', 'r').read().split()
877 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
878 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
879 usage
+= s
+ 'You are ' + \
880 light_yellow('already') + ' on your personal stream.\n'
881 usage
+= s
+ 'Any update from Twitter will show up ' + \
882 light_yellow('immediately') + '.\n'
883 usage
+= s
+ 'In addtion, following commands are available right now:\n'
887 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
888 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
889 'You can try ' + light_green('trend US') + ' or ' + \
890 light_green('trend JP Tokyo') + '.\n'
891 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
892 light_green('home 7') + ' will show 7 tweets.\n'
893 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
894 light_green('mentions 7') + ' will show 7 mention tweets.\n'
895 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
896 magenta('@mdo') + '.\n'
897 usage
+= s
* 2 + light_green('view @mdo') + \
898 ' will show ' + magenta('@mdo') + '\'s home.\n'
899 usage
+= s
* 2 + light_green('s #AKB48') + ' will search for "' + \
900 light_yellow('AKB48') + '" and return 5 newest tweet.\n'
904 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
905 usage
+= s
* 2 + light_green('t oops ') + \
906 'will tweet "' + light_yellow('oops') + '" immediately.\n'
908 light_green('rt 12 ') + ' will retweet to tweet with ' + \
909 light_yellow('[id=12]') + '.\n'
911 light_green('quote 12 ') + ' will quote the tweet with ' + \
912 light_yellow('[id=12]') + '. If no extra text is added, ' + \
913 'the quote will be canceled.\n'
915 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
916 light_yellow('[id=12]') + '.\n'
917 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
918 light_yellow('oops') + '" to tweet with ' + \
919 light_yellow('[id=12]') + '.\n'
921 light_green('fav 12 ') + ' will favorite the tweet with ' + \
922 light_yellow('[id=12]') + '.\n'
924 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
925 light_yellow('[id=12]') + '.\n'
927 light_green('del 12 ') + ' will delete tweet with ' + \
928 light_yellow('[id=12]') + '.\n'
929 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
930 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
931 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
932 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
936 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
937 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
938 light_green('inbox 7') + ' will show newest 7 messages.\n'
939 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
940 light_green('sent 7') + ' will show newest 7 messages.\n'
941 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
942 magenta('@dtvd88') + '.\n'
943 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
944 light_yellow('[message_id=5]') + '.\n'
946 # Follower and following
948 usage
+= s
+ grey(u
'\u266A' + ' Fiends and followers \n')
950 light_green('ls fl') + \
951 ' will list all followers (people who are following you).\n'
953 light_green('ls fr') + \
954 ' will list all friends (people who you are following).\n'
955 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
956 magenta('@dtvd88') + '.\n'
957 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
958 magenta('@dtvd88') + '.\n'
959 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
960 magenta('@dtvd88') + '.\n'
961 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
962 magenta('@dtvd88') + '.\n'
963 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
964 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
965 magenta('@dtvd88') + '.\n'
966 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
967 magenta('@dtvd88') + '.\n'
968 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
969 magenta('@dtvd88') + ' as a spam account.\n'
973 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
974 usage
+= s
* 2 + light_green('switch public #AKB') + \
975 ' will switch to public stream and follow "' + \
976 light_yellow('AKB') + '" keyword.\n'
977 usage
+= s
* 2 + light_green('switch mine') + \
978 ' will switch to your personal stream.\n'
979 usage
+= s
* 2 + light_green('switch mine -f ') + \
980 ' will prompt to enter the filter.\n'
981 usage
+= s
* 3 + light_yellow('Only nicks') + \
982 ' filter will decide nicks will be INCLUDE ONLY.\n'
983 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
984 ' filter will decide nicks will be EXCLUDE.\n'
985 usage
+= s
* 2 + light_green('switch mine -d') + \
986 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
990 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
991 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
992 'will be evaluate by Python interpreter.\n'
993 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
994 ' for current month.\n'
998 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
999 usage
+= s
* 2 + light_green('theme') + ' will list available theme.' + \
1000 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1001 ' theme immediately.\n'
1002 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1003 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1004 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1008 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1009 usage
+= s
+ 'Have fun and hang tight! \n'
1025 os
.system('rm -rf rainbow.db')
1026 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
1032 Reset prefix of line
1035 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1038 printNicely(str(eval(g
['cmd'])))
1091 Listen to user's input
1096 ['public', 'mine'], # switch
1111 ['image'], # show image
1113 ['fl', 'fr'], # list
1127 g
['themes'] + ['current_as_default'], # theme
1133 init_interactive_shell(d
)
1138 line
= raw_input(g
['decorated_name'])
1142 cmd
= line
.split()[0]
1146 # Save cmd to global variable and call process
1148 g
['stuff'] = ' '.join(line
.split()[1:])
1150 except Exception,e
:
1152 printNicely(red('OMG something is wrong with Twitter right now.'))
1153 # Not redisplay prefix
1154 if cmd
in ['switch', 't', 'rt', 'rep']:
1160 def stream(domain
, args
, name
='Rainbow Stream'):
1167 c
['USER_DOMAIN']: name
,
1168 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1169 c
['SITE_DOMAIN']: 'Site Stream',
1172 ascii_art(art_dict
[domain
])
1174 # These arguments are optional:
1176 timeout
=args
.timeout
,
1177 block
=not args
.no_block
,
1178 heartbeat_timeout
=args
.heartbeat_timeout
)
1182 if args
.track_keywords
:
1183 query_args
['track'] = args
.track_keywords
1186 stream
= TwitterStream(
1192 if domain
== c
['USER_DOMAIN']:
1193 tweet_iter
= stream
.user(**query_args
)
1194 elif domain
== c
['SITE_DOMAIN']:
1195 tweet_iter
= stream
.site(**query_args
)
1197 if args
.track_keywords
:
1198 tweet_iter
= stream
.statuses
.filter(**query_args
)
1200 tweet_iter
= stream
.statuses
.sample()
1202 # Iterate over the stream.
1203 for tweet
in tweet_iter
:
1205 printNicely("-- None --")
1206 elif tweet
is Timeout
:
1207 printNicely("-- Timeout --")
1208 elif tweet
is HeartbeatTimeout
:
1209 printNicely("-- Heartbeat Timeout --")
1210 elif tweet
is Hangup
:
1211 printNicely("-- Hangup --")
1212 elif tweet
.get('text'):
1215 iot
=args
.image_on_term
,
1216 keyword
=args
.track_keywords
,
1220 except TwitterHTTPError
:
1223 magenta("We have maximum connection problem with twitter'stream API right now :("))
1230 # Spawn stream process
1231 args
= parse_arguments()
1233 get_decorated_name()
1235 except TwitterHTTPError
:
1238 magenta("I'm afraid we have maximum connection problem with twitter right now :("))
1239 printNicely(magenta("Let's try again later."))
1241 os
.system('rm -rf rainbow.db')
1249 g
['original_name']))
1252 # Start listen process
1256 g
['stream_pid'] = p
.pid
1257 g
['iot'] = args
.image_on_term