2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 from dateutil
import parser
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
21 from StringIO
import StringIO
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
68 def draw(t
, iot
=False, keyword
=None, fil
=[], ig
=[]):
76 screen_name
= t
['user']['screen_name']
77 name
= t
['user']['name']
78 created_at
= t
['created_at']
79 favorited
= t
['favorited']
80 date
= parser
.parse(created_at
)
81 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
82 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
88 urls
= t
['entities']['urls']
90 expanded_url
.append(u
['expanded_url'])
99 media
= t
['entities']['media']
101 media_url
.append(m
['media_url'])
106 screen_name
= '@' + screen_name
107 if fil
and screen_name
not in fil
:
109 if ig
and screen_name
in ig
:
113 res
= db
.tweet_to_rainbow_query(tid
)
116 res
= db
.tweet_to_rainbow_query(tid
)
117 rid
= res
[0].rainbow_id
120 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
121 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
123 meta
= meta
+ green(u
'\u2605')
127 for index
in range(len(expanded_url
)):
129 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
132 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
133 # Highlight screen_name
134 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
136 tweet
= map(lambda x
: cyan(x
) if x
[0:4] == 'http' else x
, tweet
)
137 # Highlight search keyword
140 lambda x
: on_yellow(x
) if
141 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
146 tweet
= ' '.join(tweet
)
149 line1
= u
"{u:>{uw}}:".format(
153 line2
= u
"{c:>{cw}}".format(
165 if iot
and media_url
:
167 response
= requests
.get(mu
)
168 image_to_display(StringIO(response
.content
))
171 def print_message(m
):
175 sender_screen_name
= '@' + m
['sender_screen_name']
176 sender_name
= m
['sender']['name']
178 recipient_screen_name
= '@' + m
['recipient_screen_name']
179 recipient_name
= m
['recipient']['name']
181 date
= parser
.parse(m
['created_at'])
182 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
183 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
186 res
= db
.message_to_rainbow_query(mid
)
188 db
.message_store(mid
)
189 res
= db
.message_to_rainbow_query(mid
)
190 rid
= res
[0].rainbow_id
192 sender
= cycle_color(sender_name
) + grey(' ' + sender_screen_name
+ ' ')
193 recipient
= cycle_color(
194 recipient_name
) + grey(' ' + recipient_screen_name
+ ' ')
195 user
= sender
+ magenta(' >>> ') + recipient
196 meta
= grey('[' + clock
+ '] [message_id=' + str(rid
) + '] ')
197 text
= ''.join(map(lambda x
: x
+ ' ' if x
== '\n' else x
, text
))
199 line1
= u
"{u:>{uw}}:".format(
203 line2
= u
"{c:>{cw}}".format(
222 screen_name
= u
['screen_name']
223 description
= u
['description']
224 profile_image_url
= u
['profile_image_url']
225 location
= u
['location']
227 created_at
= u
['created_at']
228 statuses_count
= u
['statuses_count']
229 friends_count
= u
['friends_count']
230 followers_count
= u
['followers_count']
232 statuses_count
= green(str(statuses_count
) + ' tweets')
233 friends_count
= green(str(friends_count
) + ' following')
234 followers_count
= green(str(followers_count
) + ' followers')
235 count
= statuses_count
+ ' ' + friends_count
+ ' ' + followers_count
236 user
= cycle_color(name
) + grey(' @' + screen_name
+ ' : ') + count
237 profile_image_raw_url
= 'Profile photo: ' + cyan(profile_image_url
)
238 description
= ''.join(
239 map(lambda x
: x
+ ' ' * 4 if x
== '\n' else x
, description
))
240 description
= yellow(description
)
241 location
= 'Location : ' + magenta(location
)
242 url
= 'URL : ' + (cyan(url
) if url
else '')
243 date
= parser
.parse(created_at
)
244 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
245 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
246 clock
= 'Join at ' + white(clock
)
248 line1
= u
"{u:>{uw}}".format(
252 line2
= u
"{p:>{pw}}".format(
253 p
=profile_image_raw_url
,
254 pw
=len(profile_image_raw_url
) + 4,
256 line3
= u
"{d:>{dw}}".format(
258 dw
=len(description
) + 4,
260 line4
= u
"{l:>{lw}}".format(
262 lw
=len(location
) + 4,
264 line5
= u
"{u:>{uw}}".format(
268 line6
= u
"{c:>{cw}}".format(
276 response
= requests
.get(profile_image_url
)
277 image_to_display(StringIO(response
.content
), 2, 20)
280 for line
in [line3
, line4
, line5
, line6
]:
285 def print_trends(trends
):
289 for topic
in trends
[:TREND_MAX
]:
292 line
= cycle_color(name
) + ': ' + cyan(url
)
297 def parse_arguments():
301 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
305 help='Timeout for the stream (seconds).')
308 '--heartbeat-timeout',
309 help='Set heartbeat timeout.',
315 help='Set stream to non-blocking.')
319 help='Search the stream for specific text.')
323 help='Filter specific screen_name.')
327 help='Ignore specific screen_name.')
332 help='Display all image on terminal.')
333 return parser
.parse_args()
338 Authenticate with Twitter OAuth
340 # When using rainbow stream you must authorize.
341 twitter_credential
= os
.environ
.get(
345 '')) + os
.sep
+ '.rainbow_oauth'
346 if not os
.path
.exists(twitter_credential
):
347 oauth_dance("Rainbow Stream",
351 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
359 def get_decorated_name():
361 Beginning of every line
363 t
= Twitter(auth
=authen())
364 name
= '@' + t
.account
.verify_credentials()['screen_name']
365 g
['original_name'] = name
[1:]
366 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
374 target
= g
['stuff'].split()[0]
377 args
= parse_arguments()
379 if g
['stuff'].split()[-1] == '-f':
380 only
= raw_input('Only nicks: ')
381 ignore
= raw_input('Ignore nicks: ')
382 args
.filter = filter(None, only
.split(','))
383 args
.ignore
= filter(None, ignore
.split(','))
384 elif g
['stuff'].split()[-1] == '-d':
385 args
.filter = ONLY_LIST
386 args
.ignore
= IGNORE_LIST
388 printNicely(red('Sorry, wrong format.'))
392 if target
== 'public':
393 keyword
= g
['stuff'].split()[1]
394 if keyword
[0] == '#':
395 keyword
= keyword
[1:]
397 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
398 args
.track_keywords
= keyword
406 g
['stream_pid'] = p
.pid
409 elif target
== 'mine':
411 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
420 g
['stream_pid'] = p
.pid
422 printNicely(green('Stream switched.'))
424 printNicely(cyan('Only: ' + str(args
.filter)))
426 printNicely(red('Ignore: ' + str(args
.ignore
)))
429 printNicely(red('Sorry I can\'t understand.'))
436 t
= Twitter(auth
=authen())
437 # Get country and town
439 country
= g
['stuff'].split()[0]
443 town
= g
['stuff'].split()[1]
447 avail
= t
.trends
.available()
450 trends
= t
.trends
.place(_id
=1)[0]['trends']
453 for location
in avail
:
454 # Search for country and Town
456 if location
['countryCode'] == country \
457 and location
['placeType']['name'] == 'Town' \
458 and location
['name'] == town
:
459 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
461 # Search for country only
463 if location
['countryCode'] == country \
464 and location
['placeType']['name'] == 'Country':
465 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
473 t
= Twitter(auth
=authen())
475 if g
['stuff'].isdigit():
476 num
= int(g
['stuff'])
477 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
478 draw(t
=tweet
, iot
=g
['iot'])
486 t
= Twitter(auth
=authen())
487 user
= g
['stuff'].split()[0]
490 num
= int(g
['stuff'].split()[1])
493 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
494 draw(t
=tweet
, iot
=g
['iot'])
497 printNicely(red('A name should begin with a \'@\''))
504 t
= Twitter(auth
=authen())
506 if g
['stuff'].isdigit():
507 num
= int(g
['stuff'])
508 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
509 draw(t
=tweet
, iot
=g
['iot'])
517 t
= Twitter(auth
=authen())
518 t
.statuses
.update(status
=g
['stuff'])
525 t
= Twitter(auth
=authen())
527 id = int(g
['stuff'].split()[0])
529 printNicely(red('Sorry I can\'t understand.'))
531 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
532 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
539 t
= Twitter(auth
=authen())
542 id = int(g
['stuff'].split()[0])
544 printNicely(red('Sorry I can\'t understand.'))
546 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
547 # Get display num if exist
549 num
= int(g
['stuff'].split()[1])
551 num
= RETWEETS_SHOW_NUM
552 # Get result and display
553 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
555 printNicely(magenta('This tweet has no retweet.'))
557 for tweet
in reversed(rt_ary
):
558 draw(t
=tweet
, iot
=g
['iot'])
566 t
= Twitter(auth
=authen())
568 id = int(g
['stuff'].split()[0])
570 printNicely(red('Sorry I can\'t understand.'))
572 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
573 t
.favorites
.create(_id
=tid
, include_entities
=False)
574 printNicely(green('Favorited.'))
575 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
583 t
= Twitter(auth
=authen())
585 id = int(g
['stuff'].split()[0])
587 printNicely(red('Sorry I can\'t understand.'))
589 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
590 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
591 status
= ' '.join(g
['stuff'].split()[1:])
592 status
= '@' + user
+ ' ' + status
.decode('utf-8')
593 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
600 t
= Twitter(auth
=authen())
602 rid
= int(g
['stuff'].split()[0])
604 printNicely(red('Sorry I can\'t understand.'))
606 tid
= db
.rainbow_to_tweet_query(rid
)[0].tweet_id
607 t
.statuses
.destroy(id=tid
)
608 printNicely(green('Okay it\'s gone.'))
615 t
= Twitter(auth
=authen())
617 id = int(g
['stuff'].split()[0])
619 printNicely(red('Sorry I can\'t understand.'))
621 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
622 t
.favorites
.destroy(_id
=tid
)
623 printNicely(green('Okay it\'s unfavorited.'))
624 draw(t
.statuses
.show(id=tid
), iot
=g
['iot'])
632 t
= Twitter(auth
=authen())
633 if g
['stuff'].startswith('#'):
634 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
636 printNicely('Newest tweets:')
637 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
640 keyword
=g
['stuff'].strip()[1:])
643 printNicely(magenta('I\'m afraid there is no result'))
645 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
650 Send a direct message
652 t
= Twitter(auth
=authen())
653 user
= g
['stuff'].split()[0]
654 if user
[0].startswith('@'):
656 content
= g
['stuff'].split()[1]
658 printNicely(red('Sorry I can\'t understand.'))
659 t
.direct_messages
.new(
660 screen_name
=user
[1:],
663 printNicely(green('Message sent.'))
665 printNicely(red('A name should begin with a \'@\''))
672 t
= Twitter(auth
=authen())
674 target
= g
['stuff'].split()[0]
675 if target
!= 'image':
677 id = int(g
['stuff'].split()[1])
678 tid
= db
.rainbow_to_tweet_query(id)[0].tweet_id
679 tweet
= t
.statuses
.show(id=tid
)
680 media
= tweet
['entities']['media']
682 res
= requests
.get(m
['media_url'])
683 img
= Image
.open(StringIO(res
.content
))
686 printNicely(red('Sorry I can\'t show this image.'))
691 List friends for followers
693 t
= Twitter(auth
=authen())
696 name
= g
['stuff'].split()[1]
697 if name
.startswith('@'):
700 printNicely(red('A name should begin with a \'@\''))
701 raise Exception('Invalid name')
703 name
= g
['original_name']
704 # Get list followers or friends
706 target
= g
['stuff'].split()[0]
708 printNicely(red('Omg some syntax is wrong.'))
710 d
= {'fl': 'followers', 'fr': 'friends'}
714 while next_cursor
!= 0:
715 list = getattr(t
, d
[target
]).list(
719 include_entities
=False,
721 for u
in list['users']:
722 rel
[u
['name']] = '@' + u
['screen_name']
723 next_cursor
= list['next_cursor']
725 printNicely('All: ' + str(len(rel
)) + ' people.')
727 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
733 Inbox direct messages
735 t
= Twitter(auth
=authen())
736 num
= MESSAGES_DISPLAY
738 if g
['stuff'].isdigit():
741 # Max message per page is 20 so we have to loop
743 rel
= rel
+ t
.direct_messages(
746 include_entities
=False,
751 rel
= rel
+ t
.direct_messages(
754 include_entities
=False,
758 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
759 for m
in reversed(rel
):
768 t
= Twitter(auth
=authen())
769 num
= MESSAGES_DISPLAY
771 if g
['stuff'].isdigit():
772 num
= int(g
['stuff'])
774 # Max message per page is 20 so we have to loop
776 rel
= rel
+ t
.direct_messages
.sent(
779 include_entities
=False,
784 rel
= rel
+ t
.direct_messages
.sent(
787 include_entities
=False,
791 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
792 for m
in reversed(rel
):
801 t
= Twitter(auth
=authen())
803 rid
= int(g
['stuff'].split()[0])
805 printNicely(red('Sorry I can\'t understand.'))
806 mid
= db
.rainbow_to_message_query(rid
)[0].message_id
807 t
.direct_messages
.destroy(id=mid
)
808 printNicely(green('Message deleted.'))
813 Show profile of a specific user
815 t
= Twitter(auth
=authen())
816 screen_name
= g
['stuff'].split()[0]
817 if screen_name
.startswith('@'):
820 screen_name
=screen_name
[1:],
821 include_entities
=False)
824 printNicely(red('Omg no user.'))
826 printNicely(red('A name should begin with a \'@\''))
833 t
= Twitter(auth
=authen())
834 screen_name
= g
['stuff'].split()[0]
835 if screen_name
.startswith('@'):
836 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
837 printNicely(green('You are following ' + screen_name
+ ' now!'))
839 printNicely(red('A name should begin with a \'@\''))
846 t
= Twitter(auth
=authen())
847 screen_name
= g
['stuff'].split()[0]
848 if screen_name
.startswith('@'):
849 t
.friendships
.destroy(
850 screen_name
=screen_name
[1:],
851 include_entities
=False)
852 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
854 printNicely(red('A name should begin with a \'@\''))
861 t
= Twitter(auth
=authen())
863 screen_name
= g
['stuff'].split()[0]
865 printNicely(red('A name should be specified. '))
867 if screen_name
.startswith('@'):
868 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
869 if isinstance(rel
, dict):
870 printNicely(green(screen_name
+ ' is muted.'))
872 printNicely(red(rel
))
874 printNicely(red('A name should begin with a \'@\''))
881 t
= Twitter(auth
=authen())
883 screen_name
= g
['stuff'].split()[0]
885 printNicely(red('A name should be specified. '))
887 if screen_name
.startswith('@'):
888 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
889 if isinstance(rel
, dict):
890 printNicely(green(screen_name
+ ' is unmuted.'))
892 printNicely(red(rel
))
894 printNicely(red('A name should begin with a \'@\''))
901 t
= Twitter(auth
=authen())
903 d
= {'fl': 'followers', 'fr': 'friends'}
907 while next_cursor
!= 0:
908 list = t
.mutes
.users
.list(
909 screen_name
=g
['original_name'],
912 include_entities
=False,
914 for u
in list['users']:
915 rel
[u
['name']] = '@' + u
['screen_name']
916 next_cursor
= list['next_cursor']
918 printNicely('All: ' + str(len(rel
)) + ' people.')
920 user
= ' ' + cycle_color(name
) + grey(' ' + rel
[name
] + ' ')
928 t
= Twitter(auth
=authen())
929 screen_name
= g
['stuff'].split()[0]
930 if screen_name
.startswith('@'):
932 screen_name
=screen_name
[1:],
933 include_entities
=False,
935 printNicely(green('You blocked ' + screen_name
+ '.'))
937 printNicely(red('A name should begin with a \'@\''))
944 t
= Twitter(auth
=authen())
945 screen_name
= g
['stuff'].split()[0]
946 if screen_name
.startswith('@'):
948 screen_name
=screen_name
[1:],
949 include_entities
=False,
951 printNicely(green('Unblock ' + screen_name
+ ' success!'))
953 printNicely(red('A name should begin with a \'@\''))
958 Report a user as a spam account
960 t
= Twitter(auth
=authen())
961 screen_name
= g
['stuff'].split()[0]
962 if screen_name
.startswith('@'):
964 screen_name
=screen_name
[1:])
965 printNicely(green('You reported ' + screen_name
+ '.'))
967 printNicely(red('Sorry I can\'t understand.'))
975 rel
= os
.popen('cal').read().split('\n')
977 month
= random_rainbow(month
)
979 date
= ' '.join([cycle_color(i
) for i
in date
.split(' ')])
980 today
= os
.popen('date +\'%d\'').read().strip()
985 ary
= line
.split(' ')
986 ary
= map(lambda x
: on_grey(x
) if x
== today
else grey(x
), ary
)
995 h
, w
= os
.popen('stty size', 'r').read().split()
999 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1000 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1001 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
1002 usage
+= s
+ 'Any update from Twitter will show up ' + \
1003 yellow('immediately') + '.\n'
1004 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1006 # Discover the world
1008 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1009 usage
+= s
* 2 + green('trend') + ' will show global trending topics. ' + \
1010 'You can try ' + green('trend US') + ' or ' + \
1011 green('trend JP Tokyo') + '.\n'
1012 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
1013 green('home 7') + ' will show 7 tweets.\n'
1014 usage
+= s
* 2 + green('mentions') + ' will show mentions timeline. ' + \
1015 green('mentions 7') + ' will show 7 mention tweets.\n'
1016 usage
+= s
* 2 + green('whois @mdo') + ' will show profile of ' + \
1017 magenta('@mdo') + '.\n'
1018 usage
+= s
* 2 + green('view @mdo') + \
1019 ' will show ' + magenta('@mdo') + '\'s home.\n'
1020 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
1021 yellow('AKB48') + '" and return 5 newest tweet.\n'
1025 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1026 usage
+= s
* 2 + green('t oops ') + \
1027 'will tweet "' + yellow('oops') + '" immediately.\n'
1029 green('rt 12 ') + ' will retweet to tweet with ' + \
1030 yellow('[id=12]') + '.\n'
1032 green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1033 yellow('[id=12]') + '.\n'
1034 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
1035 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
1037 green('fav 12 ') + ' will favorite the tweet with ' + \
1038 yellow('[id=12]') + '.\n'
1040 green('ufav 12 ') + ' will unfavorite tweet with ' + \
1041 yellow('[id=12]') + '.\n'
1043 green('del 12 ') + ' will delete tweet with ' + \
1044 yellow('[id=12]') + '.\n'
1045 usage
+= s
* 2 + green('show image 12') + ' will show image in tweet with ' + \
1046 yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1050 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1051 usage
+= s
* 2 + green('inbox') + ' will show inbox messages. ' + \
1052 green('inbox 7') + ' will show newest 7 messages.\n'
1053 usage
+= s
* 2 + green('sent') + ' will show sent messages. ' + \
1054 green('sent 7') + ' will show newest 7 messages.\n'
1055 usage
+= s
* 2 + green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1056 magenta('@dtvd88') + '.\n'
1057 usage
+= s
* 2 + green('trash 5') + ' will remove message with ' + \
1058 yellow('[message_id=5]') + '.\n'
1060 # Follower and following
1062 usage
+= s
+ grey(u
'\u266A' + ' Fiends and followers \n')
1065 ' will list all followers (people who are following you).\n'
1068 ' will list all friends (people who you are following).\n'
1069 usage
+= s
* 2 + green('fl @dtvd88') + ' will follow ' + \
1070 magenta('@dtvd88') + '.\n'
1071 usage
+= s
* 2 + green('ufl @dtvd88') + ' will unfollow ' + \
1072 magenta('@dtvd88') + '.\n'
1073 usage
+= s
* 2 + green('mute @dtvd88') + ' will mute ' + \
1074 magenta('@dtvd88') + '.\n'
1075 usage
+= s
* 2 + green('unmute @dtvd88') + ' will unmute ' + \
1076 magenta('@dtvd88') + '.\n'
1077 usage
+= s
* 2 + green('muting') + ' will list muting users.\n'
1078 usage
+= s
* 2 + green('block @dtvd88') + ' will block ' + \
1079 magenta('@dtvd88') + '.\n'
1080 usage
+= s
* 2 + green('unblock @dtvd88') + ' will unblock ' + \
1081 magenta('@dtvd88') + '.\n'
1082 usage
+= s
* 2 + green('report @dtvd88') + ' will report ' + \
1083 magenta('@dtvd88') + ' as a spam account.\n'
1087 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1088 usage
+= s
* 2 + green('switch public #AKB') + \
1089 ' will switch to public stream and follow "' + \
1090 yellow('AKB') + '" keyword.\n'
1091 usage
+= s
* 2 + green('switch mine') + \
1092 ' will switch to your personal stream.\n'
1093 usage
+= s
* 2 + green('switch mine -f ') + \
1094 ' will prompt to enter the filter.\n'
1095 usage
+= s
* 3 + yellow('Only nicks') + \
1096 ' filter will decide nicks will be INCLUDE ONLY.\n'
1097 usage
+= s
* 3 + yellow('Ignore nicks') + \
1098 ' filter will decide nicks will be EXCLUDE.\n'
1099 usage
+= s
* 2 + green('switch mine -d') + \
1100 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1101 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
1105 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1106 usage
+= s
* 2 + green('111111 * 9 / 7') + ' or any math expression ' + \
1107 'will be evaluate by Python interpreter.\n'
1108 usage
+= s
* 2 + 'Even ' + green('cal') + ' will show the calendar' + \
1109 ' for current month.\n'
1113 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1114 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
1115 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
1116 usage
+= s
* 2 + green('q') + ' will quit.\n'
1120 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1121 usage
+= s
+ 'Have fun and hang tight! \n'
1137 os
.system('rm -rf rainbow.db')
1138 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
1144 Reset prefix of line
1147 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1150 print eval(g
['cmd'])
1200 Listen to user's input
1205 ['public', 'mine'], # switch
1219 ['image'], # show image
1220 ['fl', 'fr'], # list
1239 init_interactive_shell(d
)
1244 line
= raw_input(g
['decorated_name'])
1248 cmd
= line
.split()[0]
1252 # Save cmd to global variable and call process
1254 g
['stuff'] = ' '.join(line
.split()[1:])
1257 printNicely(red('OMG something is wrong with Twitter right now.'))
1258 # Not redisplay prefix
1259 if cmd
in ['switch', 't', 'rt', 'rep']:
1265 def stream(domain
, args
, name
='Rainbow Stream'):
1273 PUBLIC_DOMAIN
: args
.track_keywords
,
1274 SITE_DOMAIN
: 'Site Stream',
1276 ascii_art(art_dict
[domain
])
1278 # These arguments are optional:
1280 timeout
=args
.timeout
,
1281 block
=not args
.no_block
,
1282 heartbeat_timeout
=args
.heartbeat_timeout
)
1286 if args
.track_keywords
:
1287 query_args
['track'] = args
.track_keywords
1290 stream
= TwitterStream(
1295 if domain
== USER_DOMAIN
:
1296 tweet_iter
= stream
.user(**query_args
)
1297 elif domain
== SITE_DOMAIN
:
1298 tweet_iter
= stream
.site(**query_args
)
1300 if args
.track_keywords
:
1301 tweet_iter
= stream
.statuses
.filter(**query_args
)
1303 tweet_iter
= stream
.statuses
.sample()
1305 # Iterate over the stream.
1306 for tweet
in tweet_iter
:
1308 printNicely("-- None --")
1309 elif tweet
is Timeout
:
1310 printNicely("-- Timeout --")
1311 elif tweet
is HeartbeatTimeout
:
1312 printNicely("-- Heartbeat Timeout --")
1313 elif tweet
is Hangup
:
1314 printNicely("-- Hangup --")
1315 elif tweet
.get('text'):
1318 iot
=args
.image_on_term
,
1319 keyword
=args
.track_keywords
,
1329 # Spawn stream process
1330 args
= parse_arguments()
1331 get_decorated_name()
1332 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
1335 # Start listen process
1339 g
['stream_pid'] = p
.pid
1340 g
['iot'] = args
.image_on_term