16 from io
import BytesIO
17 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
18 from twitter
.api
import *
19 from twitter
.oauth
import OAuth
, read_token_file
20 from twitter
.oauth_dance
import oauth_dance
21 from twitter
.util
import printNicely
23 from pocket
import Pocket
28 from .consumer
import *
29 from .interactive
import *
30 from .c_image
import *
31 from .py3patch
import *
39 StreamLock
= threading
.Lock()
42 def parse_arguments():
46 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
51 help='Default stream after program start. (Default: mine)')
55 help='Timeout for the stream (seconds).')
59 help='Search the stream for specific text.')
63 help='Filter specific screen_name.')
67 help='Ignore specific screen_name.')
72 help='Display all image on terminal.')
77 help='Display images using 24bit color codes.')
81 help='Use HTTP/SOCKS proxy for network connections.')
86 help='HTTP/SOCKS proxy port (Default: 8080).')
91 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
92 return parser
.parse_args()
95 def proxy_connect(args
):
97 Connect to specified proxy
100 # Setup proxy by monkeypatching the standard lib
101 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
102 socks
.set_default_proxy(
103 socks
.SOCKS5
, args
.proxy_host
,
104 int(args
.proxy_port
))
105 elif args
.proxy_type
.lower() == "http":
106 socks
.set_default_proxy(
107 socks
.HTTP
, args
.proxy_host
,
108 int(args
.proxy_port
))
109 elif args
.proxy_type
.lower() == "socks4":
110 socks
.set_default_proxy(
111 socks
.SOCKS4
, args
.proxy_host
,
112 int(args
.proxy_port
))
115 magenta('Sorry, wrong proxy type specified! Aborting...'))
117 socket
.socket
= socks
.socksocket
122 Authenticate with Twitter OAuth
124 # When using rainbow stream you must authorize.
125 twitter_credential
= os
.environ
.get(
129 '')) + os
.sep
+ '.rainbow_oauth'
130 if not os
.path
.exists(twitter_credential
):
131 oauth_dance('Rainbow Stream',
135 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
145 Authenticate with Pocket OAuth
147 pocket_credential
= os
.environ
.get(
151 '')) + os
.sep
+ '.rainbow_pckt_oauth'
153 if not os
.path
.exists(pocket_credential
):
154 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
155 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
156 webbrowser
.open(auth_url
)
157 printNicely(green("*** Press [ENTER] after authorization ***"))
159 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
160 access_token
= user_credentials
['access_token']
161 f
= open(pocket_credential
, 'w')
162 f
.write(access_token
)
165 with
open(pocket_credential
, 'r') as f
:
166 access_token
= str(f
.readlines()[0])
169 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
172 def build_mute_dict(dict_data
=False):
176 t
= Twitter(auth
=authen())
179 screen_name_list
= []
182 while next_cursor
!= 0:
183 list = t
.mutes
.users
.list(
184 screen_name
=g
['original_name'],
187 include_entities
=False,
189 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
190 name_list
+= [u
['name'] for u
in list['users']]
191 next_cursor
= list['next_cursor']
192 # Return dict or list
194 return dict(zip(screen_name_list
, name_list
))
196 return screen_name_list
201 Save traceback when run in debug mode
204 g
['traceback'].append(traceback
.format_exc())
207 def upgrade_center():
209 Check latest and notify to upgrade
212 current
= pkg_resources
.get_distribution('rainbowstream').version
213 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
214 readme
= requests
.get(url
).text
215 latest
= readme
.split('version = \'')[1].split('\'')[0]
216 g
['using_latest'] = current
== latest
217 if not g
['using_latest']:
218 notice
= light_magenta('RainbowStream latest version is ')
219 notice
+= light_green(latest
)
220 notice
+= light_magenta(' while your current version is ')
221 notice
+= light_yellow(current
) + '\n'
222 notice
+= light_magenta('You should upgrade with ')
223 notice
+= light_green('pip install -U rainbowstream')
225 notice
= light_yellow('You are running latest version (')
226 notice
+= light_green(current
)
227 notice
+= light_yellow(')')
239 ctrl_c_handler
= lambda signum
, frame
: quit()
240 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
244 t
= Twitter(auth
=authen())
245 credential
= t
.account
.verify_credentials()
246 screen_name
= '@' + credential
['screen_name']
247 name
= credential
['name']
248 c
['original_name'] = g
['original_name'] = screen_name
[1:]
249 g
['listname'] = g
['keyword'] = ''
250 g
['PREFIX'] = u2str(emojize(format_prefix()))
251 g
['full_name'] = name
252 g
['decorated_name'] = lambda x
: color_func(
253 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
255 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
256 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
259 g
['message_threads'] = {}
262 # Debug option default = True
269 # Init tweet dict and message dict
271 c
['message_dict'] = []
273 c
['IMAGE_ON_TERM'] = args
.image_on_term
275 c
['24BIT'] = args
.color_24bit
276 # Check type of ONLY_LIST and IGNORE_LIST
277 if not isinstance(c
['ONLY_LIST'], list):
278 printNicely(red('ONLY_LIST is not a valid list value.'))
280 if not isinstance(c
['IGNORE_LIST'], list):
281 printNicely(red('IGNORE_LIST is not a valid list value.'))
282 c
['IGNORE_LIST'] = []
284 c
['IGNORE_LIST'] += build_mute_dict()
286 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
293 t
= Twitter(auth
=authen())
294 # Get country and town
296 country
= g
['stuff'].split()[0]
300 town
= g
['stuff'].split()[1]
303 avail
= t
.trends
.available()
306 trends
= t
.trends
.place(_id
=1)[0]['trends']
309 for location
in avail
:
310 # Search for country and Town
312 if location
['countryCode'] == country \
313 and location
['placeType']['name'] == 'Town' \
314 and location
['name'] == town
:
315 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
317 # Search for country only
319 if location
['countryCode'] == country \
320 and location
['placeType']['name'] == 'Country':
321 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
329 t
= Twitter(auth
=authen())
330 num
= c
['HOME_TWEET_NUM']
331 if g
['stuff'].isdigit():
332 num
= int(g
['stuff'])
333 kwargs
= {'count': num
}
334 if not c
.get('DISABLE_EXTENDED_TWEETS'):
335 kwargs
['tweet_mode'] = 'extended'
336 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
346 for e
in c
['events']:
350 printNicely(magenta('Nothing at this time.'))
357 t
= Twitter(auth
=authen())
358 num
= c
['HOME_TWEET_NUM']
359 if g
['stuff'].isdigit():
360 num
= int(g
['stuff'])
361 kwargs
= {'count': num
}
362 if not c
.get('DISABLE_EXTENDED_TWEETS'):
363 kwargs
['tweet_mode'] = 'extended'
364 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
371 Show profile of a specific user
373 t
= Twitter(auth
=authen())
375 screen_name
= g
['stuff'].split()[0]
377 printNicely(red('Sorry I can\'t understand.'))
379 if screen_name
.startswith('@'):
382 screen_name
=screen_name
[1:],
383 include_entities
=False)
387 printNicely(red('No user.'))
389 printNicely(red('A name should begin with a \'@\''))
396 t
= Twitter(auth
=authen())
398 user
= g
['stuff'].split()[0]
400 printNicely(red('Sorry I can\'t understand.'))
404 num
= int(g
['stuff'].split()[1])
406 num
= c
['HOME_TWEET_NUM']
407 kwargs
= {'count': num
, 'screen_name': user
[1:]}
408 if not c
.get('DISABLE_EXTENDED_TWEETS'):
409 kwargs
['tweet_mode'] = 'extended'
410 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
414 printNicely(red('A name should begin with a \'@\''))
417 def view_my_tweets():
419 Display user's recent tweets.
421 t
= Twitter(auth
=authen())
423 num
= int(g
['stuff'])
425 num
= c
['HOME_TWEET_NUM']
426 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
427 if not c
.get('DISABLE_EXTENDED_TWEETS'):
428 kwargs
['tweet_mode'] = 'extended'
429 for tweet
in reversed(
430 t
.statuses
.user_timeline(**kwargs
)):
439 t
= Twitter(auth
=authen())
441 query
= g
['stuff'].strip()
443 printNicely(red('Sorry I can\'t understand.'))
445 type = c
['SEARCH_TYPE']
446 if type not in ['mixed', 'recent', 'popular']:
448 max_record
= c
['SEARCH_MAX_RECORD']
449 count
= min(max_record
, 100)
455 if not c
.get('DISABLE_EXTENDED_TWEETS'):
456 kwargs
['tweet_mode'] = 'extended'
458 rel
= t
.search
.tweets(**kwargs
)['statuses']
461 printNicely('Newest tweets:')
462 for i
in reversed(xrange(count
)):
463 draw(t
=rel
[i
], keyword
=query
)
466 printNicely(magenta('I\'m afraid there is no result'))
473 t
= Twitter(auth
=authen())
474 t
.statuses
.update(status
=g
['stuff'])
479 Add new link to Pocket along with tweet id
481 if not c
['POCKET_SUPPORT']:
482 printNicely(yellow('Pocket isn\'t enabled.'))
483 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
489 t
= Twitter(auth
=authen())
491 id = int(g
['stuff'].split()[0])
492 tid
= c
['tweet_dict'][id]
494 printNicely(red('Sorry I can\'t understand.'))
497 tweet
= t
.statuses
.show(id=tid
)
499 if len(tweet
['entities']['urls']) > 0:
500 url
= tweet
['entities']['urls'][0]['expanded_url']
502 url
= "https://twitter.com/" + \
503 tweet
['user']['screen_name'] + '/status/' + str(tid
)
507 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
511 printNicely(red('Something is wrong about your Pocket account,'+ \
512 ' please restart Rainbowstream.'))
513 pocket_credential
= os
.environ
.get(
517 '')) + os
.sep
+ '.rainbow_pckt_oauth'
518 if os
.path
.exists(pocket_credential
):
519 os
.remove(pocket_credential
)
522 printNicely(green('Pocketed !'))
530 t
= Twitter(auth
=authen())
532 id = int(g
['stuff'].split()[0])
534 printNicely(red('Sorry I can\'t understand.'))
536 tid
= c
['tweet_dict'][id]
537 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
545 t
= Twitter(auth
=authen())
547 id = int(g
['stuff'].split()[0])
549 printNicely(red('Sorry I can\'t understand.'))
551 tid
= c
['tweet_dict'][id]
553 if not c
.get('DISABLE_EXTENDED_TWEETS'):
554 kwargs
['tweet_mode'] = 'extended'
555 tweet
= t
.statuses
.show(**kwargs
)
557 formater
= format_quote(tweet
)
561 prefix
= light_magenta('Compose your ', rl
=True) + \
562 light_green('#comment: ', rl
=True)
563 comment
= raw_input(prefix
)
565 quote
= comment
.join(formater
.split('#comment'))
566 t
.statuses
.update(status
=quote
)
568 printNicely(light_magenta('No text added.'))
575 t
= Twitter(auth
=authen())
578 id = int(g
['stuff'].split()[0])
580 printNicely(red('Sorry I can\'t understand.'))
582 tid
= c
['tweet_dict'][id]
583 # Get display num if exist
585 num
= int(g
['stuff'].split()[1])
587 num
= c
['RETWEETS_SHOW_NUM']
588 # Get result and display
589 kwargs
= {'id': tid
, 'count': num
}
590 if not c
.get('DISABLE_EXTENDED_TWEETS'):
591 kwargs
['tweet_mode'] = 'extended'
592 rt_ary
= t
.statuses
.retweets(**kwargs
)
594 printNicely(magenta('This tweet has no retweet.'))
596 for tweet
in reversed(rt_ary
):
605 t
= Twitter(auth
=authen())
607 id = int(g
['stuff'].split()[0])
609 printNicely(red('Sorry I can\'t understand.'))
611 tid
= c
['tweet_dict'][id]
613 if not c
.get('DISABLE_EXTENDED_TWEETS'):
614 kwargs
['tweet_mode'] = 'extended'
615 tweet
= t
.statuses
.show(**kwargs
)
616 limit
= c
['CONVERSATION_MAX']
618 thread_ref
.append(tweet
)
619 prev_tid
= tweet
['in_reply_to_status_id']
620 while prev_tid
and limit
:
622 kwargs
['id'] = prev_tid
623 tweet
= t
.statuses
.show(**kwargs
)
624 prev_tid
= tweet
['in_reply_to_status_id']
625 thread_ref
.append(tweet
)
627 for tweet
in reversed(thread_ref
):
636 t
= Twitter(auth
=authen())
638 id = int(g
['stuff'].split()[0])
640 printNicely(red('Sorry I can\'t understand.'))
642 tid
= c
['tweet_dict'][id]
643 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
644 status
= ' '.join(g
['stuff'].split()[1:])
645 # don't include own username for tweet chains
646 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
647 if user
== g
['original_name']:
648 status
= str2u(status
)
650 status
= '@' + user
+ ' ' + str2u(status
)
651 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
658 t
= Twitter(auth
=authen())
660 id = int(g
['stuff'].split()[0])
662 printNicely(red('Sorry I can\'t understand.'))
664 tid
= c
['tweet_dict'][id]
665 original_tweet
= t
.statuses
.show(id=tid
)
666 text
= original_tweet
['text']
667 nick_ary
= [original_tweet
['user']['screen_name']]
668 for user
in list(original_tweet
['entities']['user_mentions']):
669 if user
['screen_name'] not in nick_ary \
670 and user
['screen_name'] != g
['original_name']:
671 nick_ary
.append(user
['screen_name'])
672 status
= ' '.join(g
['stuff'].split()[1:])
673 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
674 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
681 t
= Twitter(auth
=authen())
683 id = int(g
['stuff'].split()[0])
685 printNicely(red('Sorry I can\'t understand.'))
687 tid
= c
['tweet_dict'][id]
688 t
.favorites
.create(_id
=tid
, include_entities
=False)
689 printNicely(green('Favorited.'))
691 if not c
.get('DISABLE_EXTENDED_TWEETS'):
692 kwargs
['tweet_mode'] = 'extended'
693 draw(t
.statuses
.show(**kwargs
))
701 t
= Twitter(auth
=authen())
703 id = int(g
['stuff'].split()[0])
705 printNicely(red('Sorry I can\'t understand.'))
707 tid
= c
['tweet_dict'][id]
708 t
.favorites
.destroy(_id
=tid
)
709 printNicely(green('Okay it\'s unfavorited.'))
711 if not c
.get('DISABLE_EXTENDED_TWEETS'):
712 kwargs
['tweet_mode'] = 'extended'
713 draw(t
.statuses
.show(**kwargs
))
719 Copy url of a tweet to clipboard
721 t
= Twitter(auth
=authen())
723 id = int(g
['stuff'].split()[0])
724 tid
= c
['tweet_dict'][id]
726 printNicely(red('Tweet id is not valid.'))
729 if not c
.get('DISABLE_EXTENDED_TWEETS'):
730 kwargs
['tweet_mode'] = 'extended'
731 tweet
= t
.statuses
.show(**kwargs
)
732 url
= 'https://twitter.com/' + \
733 tweet
['user']['screen_name'] + '/status/' + str(tid
)
735 if platform
.system().lower() == 'darwin':
736 os
.system("echo '%s' | pbcopy" % url
)
737 printNicely(green('Copied tweet\'s url to clipboard.'))
739 printNicely('Direct link: ' + yellow(url
))
746 t
= Twitter(auth
=authen())
748 id = int(g
['stuff'].split()[0])
750 printNicely(red('Sorry I can\'t understand.'))
752 tid
= c
['tweet_dict'][id]
753 t
.statuses
.destroy(id=tid
)
754 printNicely(green('Okay it\'s gone.'))
761 t
= Twitter(auth
=authen())
763 target
= g
['stuff'].split()[0]
764 if target
!= 'image':
766 id = int(g
['stuff'].split()[1])
767 tid
= c
['tweet_dict'][id]
768 tweet
= t
.statuses
.show(id=tid
)
769 media
= tweet
['entities']['media']
771 res
= requests
.get(m
['media_url'])
772 img
= Image
.open(BytesIO(res
.content
))
776 printNicely(red('Sorry I can\'t show this image.'))
783 t
= Twitter(auth
=authen())
785 if not g
['stuff'].isdigit():
787 tid
= c
['tweet_dict'][int(g
['stuff'])]
788 tweet
= t
.statuses
.show(id=tid
)
789 urls
= tweet
['entities']['urls']
791 printNicely(light_magenta('No url here @.@!'))
795 expanded_url
= url
['expanded_url']
796 webbrowser
.open(expanded_url
)
799 printNicely(red('Sorry I can\'t open url in this tweet.'))
806 t
= Twitter(auth
=authen())
807 num
= c
['MESSAGES_DISPLAY']
808 if g
['stuff'].isdigit():
814 inbox
= inbox
+ t
.direct_messages(
817 include_entities
=False,
822 inbox
= inbox
+ t
.direct_messages(
825 include_entities
=False,
829 num
= c
['MESSAGES_DISPLAY']
830 if g
['stuff'].isdigit():
835 sent
= sent
+ t
.direct_messages
.sent(
838 include_entities
=False,
843 sent
= sent
+ t
.direct_messages
.sent(
846 include_entities
=False,
851 uniq_inbox
= list(set(
852 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
854 uniq_sent
= list(set(
855 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
857 for partner
in uniq_inbox
:
858 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
860 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
861 d
[partner
] = inbox_ary
+ sent_ary
862 for partner
in uniq_sent
:
865 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
866 g
['message_threads'] = print_threads(d
)
871 View a thread of message
874 thread_id
= int(g
['stuff'])
876 g
['message_threads'][thread_id
],
881 printNicely(red('No such thread.'))
886 Send a direct message
888 t
= Twitter(auth
=authen())
890 user
= g
['stuff'].split()[0]
891 if user
[0].startswith('@'):
892 content
= ' '.join(g
['stuff'].split()[1:])
893 t
.direct_messages
.new(
894 screen_name
=user
[1:],
897 printNicely(green('Message sent.'))
899 printNicely(red('A name should begin with a \'@\''))
902 printNicely(red('Sorry I can\'t understand.'))
909 t
= Twitter(auth
=authen())
911 id = int(g
['stuff'].split()[0])
913 printNicely(red('Sorry I can\'t understand.'))
914 mid
= c
['message_dict'][id]
915 t
.direct_messages
.destroy(id=mid
)
916 printNicely(green('Message deleted.'))
921 List friends for followers
923 t
= Twitter(auth
=authen())
926 name
= g
['stuff'].split()[1]
927 if name
.startswith('@'):
930 printNicely(red('A name should begin with a \'@\''))
931 raise Exception('Invalid name')
933 name
= g
['original_name']
934 # Get list followers or friends
936 target
= g
['stuff'].split()[0]
938 printNicely(red('Omg some syntax is wrong.'))
941 d
= {'fl': 'followers', 'fr': 'friends'}
945 printNicely('All ' + d
[target
] + ':')
949 while next_cursor
!= 0:
951 list = getattr(t
, d
[target
]).list(
955 include_entities
=False,
958 for u
in list['users']:
964 + cycle_color( u
['name'] ) \
965 + color_func(c
['TWEET']['nick'])( ' @' \
969 next_cursor
= list['next_cursor']
971 # 300 users means 15 calls to the related API. The rate limit is 15
972 # calls per 15mn periods (see Twitter documentation).
973 if ( number_of_users
% 300 == 0 ):
974 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
975 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
978 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
984 t
= Twitter(auth
=authen())
985 screen_name
= g
['stuff'].split()[0]
986 if screen_name
.startswith('@'):
987 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
988 printNicely(green('You are following ' + screen_name
+ ' now!'))
990 printNicely(red('A name should begin with a \'@\''))
997 t
= Twitter(auth
=authen())
998 screen_name
= g
['stuff'].split()[0]
999 if screen_name
.startswith('@'):
1000 t
.friendships
.destroy(
1001 screen_name
=screen_name
[1:],
1002 include_entities
=False)
1003 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
1005 printNicely(red('A name should begin with a \'@\''))
1012 t
= Twitter(auth
=authen())
1014 screen_name
= g
['stuff'].split()[0]
1016 printNicely(red('A name should be specified. '))
1018 if screen_name
.startswith('@'):
1020 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1021 if isinstance(rel
, dict):
1022 printNicely(green(screen_name
+ ' is muted.'))
1023 c
['IGNORE_LIST'] += [screen_name
]
1024 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1026 printNicely(red(rel
))
1029 printNicely(red('Something is wrong, can not mute now :('))
1031 printNicely(red('A name should begin with a \'@\''))
1038 t
= Twitter(auth
=authen())
1040 screen_name
= g
['stuff'].split()[0]
1042 printNicely(red('A name should be specified. '))
1044 if screen_name
.startswith('@'):
1046 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1047 if isinstance(rel
, dict):
1048 printNicely(green(screen_name
+ ' is unmuted.'))
1049 c
['IGNORE_LIST'].remove(screen_name
)
1051 printNicely(red(rel
))
1053 printNicely(red('Maybe you are not muting this person ?'))
1055 printNicely(red('A name should begin with a \'@\''))
1062 # Get dict of muting users
1063 md
= build_mute_dict(dict_data
=True)
1064 printNicely('All: ' + str(len(md
)) + ' people.')
1066 user
= ' ' + cycle_color(md
[name
])
1067 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1069 # Update from Twitter
1070 c
['IGNORE_LIST'] = [n
for n
in md
]
1077 t
= Twitter(auth
=authen())
1078 screen_name
= g
['stuff'].split()[0]
1079 if screen_name
.startswith('@'):
1081 screen_name
=screen_name
[1:],
1082 include_entities
=False,
1084 printNicely(green('You blocked ' + screen_name
+ '.'))
1086 printNicely(red('A name should begin with a \'@\''))
1093 t
= Twitter(auth
=authen())
1094 screen_name
= g
['stuff'].split()[0]
1095 if screen_name
.startswith('@'):
1097 screen_name
=screen_name
[1:],
1098 include_entities
=False,
1100 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1102 printNicely(red('A name should begin with a \'@\''))
1107 Report a user as a spam account
1109 t
= Twitter(auth
=authen())
1110 screen_name
= g
['stuff'].split()[0]
1111 if screen_name
.startswith('@'):
1112 t
.users
.report_spam(
1113 screen_name
=screen_name
[1:])
1114 printNicely(green('You reported ' + screen_name
+ '.'))
1116 printNicely(red('Sorry I can\'t understand.'))
1124 list_name
= raw_input(
1125 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1126 # Get list name and owner
1128 owner
, slug
= list_name
.split('/')
1129 if slug
.startswith('@'):
1134 light_magenta('List name should follow "@owner/list_name" format.'))
1135 raise Exception('Wrong list name')
1138 def check_slug(list_name
):
1142 # Get list name and owner
1144 owner
, slug
= list_name
.split('/')
1145 if slug
.startswith('@'):
1150 light_magenta('List name should follow "@owner/list_name" format.'))
1151 raise Exception('Wrong list name')
1158 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1162 printNicely(light_magenta('You belong to no lists :)'))
1169 owner
, slug
= get_slug()
1170 res
= t
.lists
.statuses(
1172 owner_screen_name
=owner
,
1173 count
=c
['LIST_MAX'],
1174 include_entities
=False)
1175 for tweet
in reversed(res
):
1180 def list_members(t
):
1184 owner
, slug
= get_slug()
1188 while next_cursor
!= 0:
1189 m
= t
.lists
.members(
1191 owner_screen_name
=owner
,
1193 include_entities
=False)
1194 for u
in m
['users']:
1195 rel
[u
['name']] = '@' + u
['screen_name']
1196 next_cursor
= m
['next_cursor']
1197 printNicely('All: ' + str(len(rel
)) + ' members.')
1199 user
= ' ' + cycle_color(name
)
1200 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1204 def list_subscribers(t
):
1208 owner
, slug
= get_slug()
1212 while next_cursor
!= 0:
1213 m
= t
.lists
.subscribers(
1215 owner_screen_name
=owner
,
1217 include_entities
=False)
1218 for u
in m
['users']:
1219 rel
[u
['name']] = '@' + u
['screen_name']
1220 next_cursor
= m
['next_cursor']
1221 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1223 user
= ' ' + cycle_color(name
)
1224 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1230 Add specific user to a list
1232 owner
, slug
= get_slug()
1234 user_name
= raw_input(
1236 'Give me name of the newbie: ',
1238 if user_name
.startswith('@'):
1239 user_name
= user_name
[1:]
1241 t
.lists
.members
.create(
1243 owner_screen_name
=owner
,
1244 screen_name
=user_name
)
1245 printNicely(green('Added.'))
1248 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1253 Remove specific user from a list
1255 owner
, slug
= get_slug()
1257 user_name
= raw_input(
1259 'Give me name of the unlucky one: ',
1261 if user_name
.startswith('@'):
1262 user_name
= user_name
[1:]
1264 t
.lists
.members
.destroy(
1266 owner_screen_name
=owner
,
1267 screen_name
=user_name
)
1268 printNicely(green('Gone.'))
1271 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1274 def list_subscribe(t
):
1278 owner
, slug
= get_slug()
1281 t
.lists
.subscribers
.create(
1283 owner_screen_name
=owner
)
1284 printNicely(green('Done.'))
1288 light_magenta('I\'m sorry you can not subscribe to this list.'))
1291 def list_unsubscribe(t
):
1295 owner
, slug
= get_slug()
1298 t
.lists
.subscribers
.destroy(
1300 owner_screen_name
=owner
)
1301 printNicely(green('Done.'))
1305 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1314 while next_cursor
!= 0:
1315 res
= t
.lists
.ownerships(
1316 screen_name
=g
['original_name'],
1319 next_cursor
= res
['next_cursor']
1323 printNicely(light_magenta('You own no lists :)'))
1330 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1333 'New list\'s mode (public/private): ',
1335 description
= raw_input(
1337 'New list\'s description: ',
1343 description
=description
)
1344 printNicely(green(name
+ ' list is created.'))
1347 printNicely(red('Oops something is wrong with Twitter :('))
1356 'Your list that you want to update: ',
1360 'Update name (leave blank to unchange): ',
1362 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1363 description
= raw_input(light_magenta('Update description: ', rl
=True))
1367 slug
='-'.join(slug
.split()),
1368 owner_screen_name
=g
['original_name'],
1371 description
=description
)
1375 owner_screen_name
=g
['original_name'],
1377 description
=description
)
1378 printNicely(green(slug
+ ' list is updated.'))
1381 printNicely(red('Oops something is wrong with Twitter :('))
1390 'Your list that you want to delete: ',
1394 slug
='-'.join(slug
.split()),
1395 owner_screen_name
=g
['original_name'])
1396 printNicely(green(slug
+ ' list is deleted.'))
1399 printNicely(red('Oops something is wrong with Twitter :('))
1406 t
= Twitter(auth
=authen())
1407 # List all lists or base on action
1409 g
['list_action'] = g
['stuff'].split()[0]
1416 'all_mem': list_members
,
1417 'all_sub': list_subscribers
,
1420 'sub': list_subscribe
,
1421 'unsub': list_unsubscribe
,
1424 'update': list_update
,
1428 return action_ary
[g
['list_action']](t
)
1430 printNicely(red('Please try again.'))
1438 target
= g
['stuff'].split()[0]
1440 args
= parse_arguments()
1442 if g
['stuff'].split()[-1] == '-f':
1443 guide
= 'To ignore an option, just hit Enter key.'
1444 printNicely(light_magenta(guide
))
1445 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1446 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1447 args
.filter = list(filter(None, only
.split(',')))
1448 args
.ignore
= list(filter(None, ignore
.split(',')))
1450 printNicely(red('Sorry, wrong format.'))
1453 g
['stream_stop'] = True
1455 stuff
= g
['stuff'].split()[1]
1460 'public': spawn_public_stream
,
1461 'list': spawn_list_stream
,
1462 'mine': spawn_personal_stream
,
1464 spawn_dict
.get(target
)(args
, stuff
)
1467 printNicely(red('Sorry I can\'t understand.'))
1472 Unix's command `cal`
1475 rel
= os
.popen('cal').read().split('\n')
1478 show_calendar(month
, date
, rel
)
1483 List and change theme
1487 for theme
in g
['themes']:
1488 line
= light_magenta(theme
)
1489 if c
['THEME'] == theme
:
1490 line
= ' ' * 2 + light_yellow('* ') + line
1492 line
= ' ' * 4 + line
1498 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1499 # Redefine decorated_name
1500 g
['decorated_name'] = lambda x
: color_func(
1501 c
['DECORATED_NAME'])(
1503 printNicely(green('Theme changed.'))
1505 printNicely(red('No such theme exists.'))
1510 Browse and change config
1512 all_config
= get_all_config()
1513 g
['stuff'] = g
['stuff'].strip()
1516 for k
in all_config
:
1518 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1520 guide
= 'Detailed explanation can be found at ' + \
1521 color_func(c
['TWEET']['link'])(
1522 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1524 # Print specific config
1525 elif len(g
['stuff'].split()) == 1:
1526 if g
['stuff'] in all_config
:
1529 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1532 printNicely(red('No such config key.'))
1533 # Print specific config's default value
1534 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1535 key
= g
['stuff'].split()[0]
1537 value
= get_default_config(key
)
1538 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1542 printNicely(red('Just can not get the default.'))
1543 # Delete specific config key in config file
1544 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1545 key
= g
['stuff'].split()[0]
1548 printNicely(green('Config key is dropped.'))
1551 printNicely(red('Just can not drop the key.'))
1552 # Set specific config
1553 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1554 key
= g
['stuff'].split()[0]
1555 value
= g
['stuff'].split()[-1]
1556 if key
== 'THEME' and not validate_theme(value
):
1557 printNicely(red('Invalid theme\'s value.'))
1560 set_config(key
, value
)
1561 # Keys that needs to be apply immediately
1563 c
['THEME'] = reload_theme(value
, c
['THEME'])
1564 g
['decorated_name'] = lambda x
: color_func(
1565 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1566 elif key
== 'PREFIX':
1567 g
['PREFIX'] = u2str(emojize(format_prefix(
1568 listname
=g
['listname'],
1569 keyword
=g
['keyword']
1572 printNicely(green('Updated successfully.'))
1575 printNicely(red('Just can not set the key.'))
1577 printNicely(light_magenta('Sorry I can\'t understand.'))
1580 def help_discover():
1585 # Discover the world
1587 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1588 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1589 'You can try ' + light_green('trend US') + ' or ' + \
1590 light_green('trend JP Tokyo') + '.\n'
1591 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1592 light_green('home 7') + ' will show 7 tweets.\n'
1593 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1594 light_green('me 2') + ' will show your last 2 tweets.\n'
1596 light_green('notification') + ' will show your recent notification.\n'
1597 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1598 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1599 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1600 magenta('@mdo') + '.\n'
1601 usage
+= s
* 2 + light_green('view @mdo') + \
1602 ' will show ' + magenta('@mdo') + '\'s home.\n'
1603 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1604 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1605 'Search can be performed with or without hashtag.\n'
1616 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1617 usage
+= s
* 2 + light_green('t oops ') + \
1618 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1620 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1621 light_yellow('[id=12]') + '.\n'
1623 light_green('quote 12 ') + ' will quote the tweet with ' + \
1624 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1625 'the quote will be canceled.\n'
1627 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1628 light_yellow('[id=12]') + '.\n'
1629 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1630 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1631 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1632 light_yellow('oops') + '" to the owner of the tweet with ' + \
1633 light_yellow('[id=12]') + '.\n'
1634 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1635 light_yellow('oops') + '" to all people in the tweet with ' + \
1636 light_yellow('[id=12]') + '.\n'
1638 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1639 light_yellow('[id=12]') + '.\n'
1641 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1642 light_yellow('[id=12]') + '.\n'
1644 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1645 light_yellow('[id=12]') + '.\n'
1647 light_green('del 12 ') + ' will delete tweet with ' + \
1648 light_yellow('[id=12]') + '.\n'
1649 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1650 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1651 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1652 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1653 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1654 light_yellow('[id=12]') + ' in your Pocket list.\n'
1658 def help_messages():
1665 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1666 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1667 light_green('inbox 7') + ' will show newest 7 messages.\n'
1668 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1669 light_yellow('[thread_id=2]') + '.\n'
1670 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1671 magenta('@dtvd88') + '.\n'
1672 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1673 light_yellow('[message_id=5]') + '.\n'
1677 def help_friends_and_followers():
1679 Friends and Followers
1682 # Follower and following
1684 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1686 light_green('ls fl') + \
1687 ' will list all followers (people who are following you).\n'
1689 light_green('ls fr') + \
1690 ' will list all friends (people who you are following).\n'
1691 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1692 magenta('@dtvd88') + '.\n'
1693 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1694 magenta('@dtvd88') + '.\n'
1695 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1696 magenta('@dtvd88') + '.\n'
1697 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1698 magenta('@dtvd88') + '.\n'
1699 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1700 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1701 magenta('@dtvd88') + '.\n'
1702 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1703 magenta('@dtvd88') + '.\n'
1704 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1705 magenta('@dtvd88') + ' as a spam account.\n'
1716 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1717 usage
+= s
* 2 + light_green('list') + \
1718 ' will show all lists you are belong to.\n'
1719 usage
+= s
* 2 + light_green('list home') + \
1720 ' will show timeline of list. You will be asked for list\'s name.\n'
1721 usage
+= s
* 2 + light_green('list all_mem') + \
1722 ' will show list\'s all members.\n'
1723 usage
+= s
* 2 + light_green('list all_sub') + \
1724 ' will show list\'s all subscribers.\n'
1725 usage
+= s
* 2 + light_green('list add') + \
1726 ' will add specific person to a list owned by you.' + \
1727 ' You will be asked for list\'s name and person\'s name.\n'
1728 usage
+= s
* 2 + light_green('list rm') + \
1729 ' will remove specific person from a list owned by you.' + \
1730 ' You will be asked for list\'s name and person\'s name.\n'
1731 usage
+= s
* 2 + light_green('list sub') + \
1732 ' will subscribe you to a specific list.\n'
1733 usage
+= s
* 2 + light_green('list unsub') + \
1734 ' will unsubscribe you from a specific list.\n'
1735 usage
+= s
* 2 + light_green('list own') + \
1736 ' will show all list owned by you.\n'
1737 usage
+= s
* 2 + light_green('list new') + \
1738 ' will create a new list.\n'
1739 usage
+= s
* 2 + light_green('list update') + \
1740 ' will update a list owned by you.\n'
1741 usage
+= s
* 2 + light_green('list del') + \
1742 ' will delete a list owned by you.\n'
1753 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1754 usage
+= s
* 2 + light_green('switch public #AKB') + \
1755 ' will switch to public stream and follow "' + \
1756 light_yellow('AKB') + '" keyword.\n'
1757 usage
+= s
* 2 + light_green('switch mine') + \
1758 ' will switch to your personal stream.\n'
1759 usage
+= s
* 2 + light_green('switch mine -f ') + \
1760 ' will prompt to enter the filter.\n'
1761 usage
+= s
* 3 + light_yellow('Only nicks') + \
1762 ' filter will decide nicks will be INCLUDE ONLY.\n'
1763 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1764 ' filter will decide nicks will be EXCLUDE.\n'
1765 usage
+= s
* 2 + light_green('switch list') + \
1766 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1775 h
, w
= os
.popen('stty size', 'r').read().split()
1778 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1779 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1780 usage
+= s
+ 'You are ' + \
1781 light_yellow('already') + ' on your personal stream.\n'
1782 usage
+= s
+ 'Any update from Twitter will show up ' + \
1783 light_yellow('immediately') + '.\n'
1784 usage
+= s
+ 'In addition, following commands are available right now:\n'
1785 # Twitter help section
1787 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1788 usage
+= s
* 2 + light_green('h discover') + \
1789 ' will show help for discover commands.\n'
1790 usage
+= s
* 2 + light_green('h tweets') + \
1791 ' will show help for tweets commands.\n'
1792 usage
+= s
* 2 + light_green('h messages') + \
1793 ' will show help for messages commands.\n'
1794 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1795 ' will show help for friends and followers commands.\n'
1796 usage
+= s
* 2 + light_green('h list') + \
1797 ' will show help for list commands.\n'
1798 usage
+= s
* 2 + light_green('h stream') + \
1799 ' will show help for stream commands.\n'
1802 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1803 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1804 'will be evaluate by Python interpreter.\n'
1805 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1806 ' for current month.\n'
1809 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1810 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1811 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1812 ' theme immediately.\n'
1813 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1815 light_green('config ASCII_ART') + ' will output current value of ' +\
1816 light_yellow('ASCII_ART') + ' config key.\n'
1818 light_green('config TREND_MAX default') + ' will output default value of ' + \
1819 light_yellow('TREND_MAX') + ' config key.\n'
1821 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1822 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1824 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1825 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1826 light_yellow('True') + '.\n'
1829 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1830 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1831 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1832 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1833 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1834 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1835 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1838 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1839 usage
+= s
+ 'Have fun and hang tight! \n'
1842 'discover': help_discover
,
1843 'tweets': help_tweets
,
1844 'messages': help_messages
,
1845 'friends_and_followers': help_friends_and_followers
,
1847 'stream': help_stream
,
1852 lambda: printNicely(red('No such command.'))
1860 Pause stream display
1863 printNicely(green('Stream is paused'))
1871 printNicely(green('Stream is running back now'))
1887 printNicely(green('See you next time :)'))
1895 Reset prefix of line
1898 if c
.get('USER_JSON_ERROR'):
1899 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1900 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1902 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1905 printNicely(str(eval(g
['cmd'])))
1960 # Handle function set
2015 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2020 Listen to user's input
2025 ['public', 'mine', 'list'], # switch
2034 [], # view_my_tweets
2045 ['image'], # show image
2047 ['fl', 'fr'], # list
2049 [i
for i
in g
['message_threads']], # sent
2074 [key
for key
in dict(get_all_config())], # config
2075 g
['themes'], # theme
2080 'friends_and_followers',
2092 init_interactive_shell(d
)
2099 # Only use PREFIX as a string with raw_input
2100 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2103 # Save cmd to compare with readline buffer
2104 g
['cmd'] = line
.strip()
2105 # Get short cmd to pass to handle function
2107 cmd
= line
.split()[0]
2110 # Lock the semaphore
2112 # Save cmd to global variable and call process
2113 g
['stuff'] = ' '.join(line
.split()[1:])
2114 # Check tweet length
2115 # Process the command
2118 if cmd
in ['switch', 't', 'rt', 'rep']:
2124 except TwitterHTTPError
as e
:
2125 detail_twitter_error(e
)
2128 printNicely(red('OMG something is wrong with Twitter API right now.'))
2130 # Release the semaphore lock
2134 def reconn_notice():
2136 Notice when Hangup or Timeout
2138 guide
= light_magenta('You can use ') + \
2139 light_green('switch') + \
2140 light_magenta(' command to return to your stream.\n')
2141 guide
+= light_magenta('Type ') + \
2142 light_green('h stream') + \
2143 light_magenta(' for more details.')
2145 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2149 def stream(domain
, args
, name
='Rainbow Stream'):
2155 c
['USER_DOMAIN']: name
,
2156 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2157 c
['SITE_DOMAIN']: name
,
2160 ascii_art(art_dict
.get(domain
, name
))
2161 # These arguments are optional:
2163 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2165 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2168 if args
.track_keywords
:
2169 query_args
['track'] = args
.track_keywords
2171 stream
= TwitterStream(
2176 if domain
== c
['USER_DOMAIN']:
2177 tweet_iter
= stream
.user(**query_args
)
2178 elif domain
== c
['SITE_DOMAIN']:
2179 tweet_iter
= stream
.site(**query_args
)
2181 if args
.track_keywords
:
2182 tweet_iter
= stream
.statuses
.filter(**query_args
)
2184 tweet_iter
= stream
.statuses
.sample()
2185 # Block new stream until other one exits
2186 StreamLock
.acquire()
2187 g
['stream_stop'] = False
2188 last_tweet_time
= time
.time()
2189 for tweet
in tweet_iter
:
2191 printNicely('-- None --')
2192 elif tweet
is Timeout
:
2193 # Because the stream check for each 0.3s
2194 # so we shouldn't output anything here
2195 if(g
['stream_stop']):
2196 StreamLock
.release()
2198 elif tweet
is HeartbeatTimeout
:
2199 printNicely('-- Heartbeat Timeout --')
2201 StreamLock
.release()
2203 elif tweet
is Hangup
:
2204 printNicely('-- Hangup --')
2206 StreamLock
.release()
2208 elif tweet
.get('text'):
2209 # Slow down the stream by STREAM_DELAY config key
2210 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2212 last_tweet_time
= time
.time()
2213 # Check the semaphore pause and lock (stream process only)
2221 keyword
=args
.track_keywords
,
2226 # Current readline buffer
2227 current_buffer
= readline
.get_line_buffer().strip()
2228 # There is an unexpected behaviour in MacOSX readline + Python 2:
2229 # after completely delete a word after typing it,
2230 # somehow readline buffer still contains
2231 # the 1st character of that word
2232 if current_buffer
and g
['cmd'] != current_buffer
:
2234 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2236 elif not c
['HIDE_PROMPT']:
2237 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2239 elif tweet
.get('direct_message'):
2240 # Check the semaphore pause and lock (stream process only)
2245 print_message(tweet
['direct_message'])
2246 elif tweet
.get('event'):
2247 c
['events'].append(tweet
)
2249 except TwitterHTTPError
as e
:
2252 magenta('We have connection problem with twitter stream API right now :('))
2253 detail_twitter_error(e
)
2254 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2258 magenta('There seems to be a connection problem.'))
2263 def spawn_public_stream(args
, keyword
=None):
2265 Spawn a new public stream
2267 # Only set keyword if specified
2269 if keyword
[0] == '#':
2270 keyword
= keyword
[1:]
2271 args
.track_keywords
= keyword
2272 g
['keyword'] = keyword
2274 g
['keyword'] = 'Global'
2275 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2278 th
= threading
.Thread(
2287 def spawn_list_stream(args
, stuff
=None):
2289 Spawn a new list stream
2292 owner
, slug
= check_slug(stuff
)
2294 owner
, slug
= get_slug()
2296 # Force python 2 not redraw readline buffer
2297 listname
= '/'.join([owner
, slug
])
2298 # Set the listname variable
2299 # and reset tracked keyword
2300 g
['listname'] = listname
2302 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2303 listname
=g
['listname']
2305 printNicely(light_yellow('getting list members ...'))
2307 t
= Twitter(auth
=authen())
2310 while next_cursor
!= 0:
2311 m
= t
.lists
.members(
2313 owner_screen_name
=owner
,
2315 include_entities
=False)
2316 for u
in m
['users']:
2317 members
.append('@' + u
['screen_name'])
2318 next_cursor
= m
['next_cursor']
2319 printNicely(light_yellow('... done.'))
2320 # Build thread filter array
2321 args
.filter = members
2323 th
= threading
.Thread(
2333 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2335 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2339 def spawn_personal_stream(args
, stuff
=None):
2341 Spawn a new personal stream
2343 # Reset the tracked keyword and listname
2344 g
['keyword'] = g
['listname'] = ''
2346 g
['PREFIX'] = u2str(emojize(format_prefix()))
2348 th
= threading
.Thread(
2353 g
['original_name']))
2363 args
= parse_arguments()
2367 # Twitter API connection problem
2368 except TwitterHTTPError
as e
:
2371 magenta('We have connection problem with twitter REST API right now :('))
2372 detail_twitter_error(e
)
2375 # Proxy connection problem
2376 except (socks
.ProxyConnectionError
, URLError
):
2378 magenta('There seems to be a connection problem.'))
2380 magenta('You might want to check your proxy settings (host, port and type)!'))
2384 # Spawn stream thread
2385 target
= args
.stream
.split()[0]
2386 if target
== 'mine':
2387 spawn_personal_stream(args
)
2390 stuff
= args
.stream
.split()[1]
2394 'public': spawn_public_stream
,
2395 'list': spawn_list_stream
,
2397 spawn_dict
.get(target
)(args
, stuff
)
2399 # Start listen process