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 g
['id_str'] = credential
['id_str']
249 c
['original_name'] = g
['original_name'] = screen_name
[1:]
250 g
['listname'] = g
['keyword'] = ''
251 g
['PREFIX'] = u2str(emojize(format_prefix()))
252 g
['full_name'] = name
253 g
['decorated_name'] = lambda x
: color_func(
254 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
256 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
257 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
260 g
['message_threads'] = {}
263 # Debug option default = True
270 # Init tweet dict and message dict
272 c
['message_dict'] = []
274 c
['IMAGE_ON_TERM'] = args
.image_on_term
276 c
['24BIT'] = args
.color_24bit
277 # Check type of ONLY_LIST and IGNORE_LIST
278 if not isinstance(c
['ONLY_LIST'], list):
279 printNicely(red('ONLY_LIST is not a valid list value.'))
281 if not isinstance(c
['IGNORE_LIST'], list):
282 printNicely(red('IGNORE_LIST is not a valid list value.'))
283 c
['IGNORE_LIST'] = []
285 c
['IGNORE_LIST'] += build_mute_dict()
287 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
294 t
= Twitter(auth
=authen())
295 # Get country and town
297 country
= g
['stuff'].split()[0]
301 town
= g
['stuff'].split()[1]
304 avail
= t
.trends
.available()
307 trends
= t
.trends
.place(_id
=1)[0]['trends']
310 for location
in avail
:
311 # Search for country and Town
313 if location
['countryCode'] == country \
314 and location
['placeType']['name'] == 'Town' \
315 and location
['name'] == town
:
316 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
318 # Search for country only
320 if location
['countryCode'] == country \
321 and location
['placeType']['name'] == 'Country':
322 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
328 Fetch stream based on since_id
330 t
= Twitter(auth
=authen())
332 num
= c
['HOME_TWEET_NUM']
333 kwargs
= {'count': num
}
336 kwargs
['since_id'] = g
['since_id']
338 kwargs
= add_tweetmode_parameter(kwargs
)
339 result
= t
.statuses
.home_timeline(**kwargs
)
341 g
['since_id'] = result
[0]['id']
342 for tweet
in reversed(result
):
351 t
= Twitter(auth
=authen())
352 num
= c
['HOME_TWEET_NUM']
353 if g
['stuff'].isdigit():
354 num
= int(g
['stuff'])
355 kwargs
= {'count': num
}
356 kwargs
= add_tweetmode_parameter(kwargs
)
357 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
367 for e
in c
['events']:
371 printNicely(magenta('Nothing at this time.'))
378 t
= Twitter(auth
=authen())
379 num
= c
['HOME_TWEET_NUM']
380 if g
['stuff'].isdigit():
381 num
= int(g
['stuff'])
382 kwargs
= {'count': num
}
383 kwargs
= add_tweetmode_parameter(kwargs
)
384 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
391 Show profile of a specific user
393 t
= Twitter(auth
=authen())
395 screen_name
= g
['stuff'].split()[0]
397 printNicely(red('Sorry I can\'t understand.'))
399 if screen_name
.startswith('@'):
402 screen_name
=screen_name
[1:],
403 include_entities
=False)
407 printNicely(red('No user.'))
409 printNicely(red('A name should begin with a \'@\''))
416 t
= Twitter(auth
=authen())
418 user
= g
['stuff'].split()[0]
420 printNicely(red('Sorry I can\'t understand.'))
424 num
= int(g
['stuff'].split()[1])
426 num
= c
['HOME_TWEET_NUM']
427 kwargs
= {'count': num
, 'screen_name': user
[1:]}
428 kwargs
= add_tweetmode_parameter(kwargs
)
429 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
433 printNicely(red('A name should begin with a \'@\''))
436 def view_my_tweets():
438 Display user's recent tweets.
440 t
= Twitter(auth
=authen())
442 num
= int(g
['stuff'])
444 num
= c
['HOME_TWEET_NUM']
445 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
446 kwargs
= add_tweetmode_parameter(kwargs
)
447 for tweet
in reversed(
448 t
.statuses
.user_timeline(**kwargs
)):
457 t
= Twitter(auth
=authen())
459 query
= g
['stuff'].strip()
461 printNicely(red('Sorry I can\'t understand.'))
463 type = c
['SEARCH_TYPE']
464 if type not in ['mixed', 'recent', 'popular']:
466 max_record
= c
['SEARCH_MAX_RECORD']
467 count
= min(max_record
, 100)
473 kwargs
= add_tweetmode_parameter(kwargs
)
475 rel
= t
.search
.tweets(**kwargs
)['statuses']
478 printNicely('Newest tweets:')
479 for i
in reversed(xrange(count
)):
480 draw(t
=rel
[i
], keyword
=query
)
483 printNicely(magenta('I\'m afraid there is no result'))
490 t
= Twitter(auth
=authen())
491 t
.statuses
.update(status
=g
['stuff'])
496 Add new link to Pocket along with tweet id
498 if not c
['POCKET_SUPPORT']:
499 printNicely(yellow('Pocket isn\'t enabled.'))
500 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
506 t
= Twitter(auth
=authen())
508 id = int(g
['stuff'].split()[0])
509 tid
= c
['tweet_dict'][id]
511 printNicely(red('Sorry I can\'t understand.'))
514 tweet
= t
.statuses
.show(id=tid
)
516 if len(tweet
['entities']['urls']) > 0:
517 url
= tweet
['entities']['urls'][0]['expanded_url']
519 url
= "https://twitter.com/" + \
520 tweet
['user']['screen_name'] + '/status/' + str(tid
)
524 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
528 printNicely(red('Something is wrong about your Pocket account,'+ \
529 ' please restart Rainbowstream.'))
530 pocket_credential
= os
.environ
.get(
534 '')) + os
.sep
+ '.rainbow_pckt_oauth'
535 if os
.path
.exists(pocket_credential
):
536 os
.remove(pocket_credential
)
539 printNicely(green('Pocketed !'))
547 t
= Twitter(auth
=authen())
549 id = int(g
['stuff'].split()[0])
551 printNicely(red('Sorry I can\'t understand.'))
553 tid
= c
['tweet_dict'][id]
554 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
562 t
= Twitter(auth
=authen())
564 id = int(g
['stuff'].split()[0])
566 printNicely(red('Sorry I can\'t understand.'))
568 tid
= c
['tweet_dict'][id]
570 kwargs
= add_tweetmode_parameter(kwargs
)
571 tweet
= t
.statuses
.show(**kwargs
)
573 formater
= format_quote(tweet
)
577 prefix
= light_magenta('Compose your ', rl
=True) + \
578 light_green('#comment: ', rl
=True)
579 comment
= raw_input(prefix
)
581 quote
= comment
.join(formater
.split('#comment'))
582 t
.statuses
.update(status
=quote
)
584 printNicely(light_magenta('No text added.'))
591 t
= Twitter(auth
=authen())
594 id = int(g
['stuff'].split()[0])
596 printNicely(red('Sorry I can\'t understand.'))
598 tid
= c
['tweet_dict'][id]
599 # Get display num if exist
601 num
= int(g
['stuff'].split()[1])
603 num
= c
['RETWEETS_SHOW_NUM']
604 # Get result and display
605 kwargs
= {'id': tid
, 'count': num
}
606 kwargs
= add_tweetmode_parameter(kwargs
)
607 rt_ary
= t
.statuses
.retweets(**kwargs
)
609 printNicely(magenta('This tweet has no retweet.'))
611 for tweet
in reversed(rt_ary
):
620 t
= Twitter(auth
=authen())
622 id = int(g
['stuff'].split()[0])
624 printNicely(red('Sorry I can\'t understand.'))
626 tid
= c
['tweet_dict'][id]
628 kwargs
= add_tweetmode_parameter(kwargs
)
629 tweet
= t
.statuses
.show(**kwargs
)
630 limit
= c
['CONVERSATION_MAX']
632 thread_ref
.append(tweet
)
633 prev_tid
= tweet
['in_reply_to_status_id']
634 while prev_tid
and limit
:
636 kwargs
['id'] = prev_tid
637 tweet
= t
.statuses
.show(**kwargs
)
638 prev_tid
= tweet
['in_reply_to_status_id']
639 thread_ref
.append(tweet
)
641 for tweet
in reversed(thread_ref
):
650 t
= Twitter(auth
=authen())
652 id = int(g
['stuff'].split()[0])
654 printNicely(red('Sorry I can\'t understand.'))
656 tid
= c
['tweet_dict'][id]
657 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
658 status
= ' '.join(g
['stuff'].split()[1:])
659 # don't include own username for tweet chains
660 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
661 if user
== g
['original_name']:
662 status
= str2u(status
)
664 status
= '@' + user
+ ' ' + str2u(status
)
665 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
672 t
= Twitter(auth
=authen())
674 id = int(g
['stuff'].split()[0])
676 printNicely(red('Sorry I can\'t understand.'))
678 tid
= c
['tweet_dict'][id]
679 original_tweet
= t
.statuses
.show(id=tid
)
680 text
= original_tweet
['text']
681 nick_ary
= [original_tweet
['user']['screen_name']]
682 for user
in list(original_tweet
['entities']['user_mentions']):
683 if user
['screen_name'] not in nick_ary \
684 and user
['screen_name'] != g
['original_name']:
685 nick_ary
.append(user
['screen_name'])
686 status
= ' '.join(g
['stuff'].split()[1:])
687 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
688 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
695 t
= Twitter(auth
=authen())
697 id = int(g
['stuff'].split()[0])
699 printNicely(red('Sorry I can\'t understand.'))
701 tid
= c
['tweet_dict'][id]
702 t
.favorites
.create(_id
=tid
, include_entities
=False)
703 printNicely(green('Favorited.'))
705 kwargs
= add_tweetmode_parameter(kwargs
)
706 draw(t
.statuses
.show(**kwargs
))
714 t
= Twitter(auth
=authen())
716 id = int(g
['stuff'].split()[0])
718 printNicely(red('Sorry I can\'t understand.'))
720 tid
= c
['tweet_dict'][id]
721 t
.favorites
.destroy(_id
=tid
)
722 printNicely(green('Okay it\'s unfavorited.'))
724 kwargs
= add_tweetmode_parameter(kwargs
)
725 draw(t
.statuses
.show(**kwargs
))
731 Copy url of a tweet to clipboard
733 t
= Twitter(auth
=authen())
735 id = int(g
['stuff'].split()[0])
736 tid
= c
['tweet_dict'][id]
738 printNicely(red('Tweet id is not valid.'))
741 kwargs
= add_tweetmode_parameter(kwargs
)
742 tweet
= t
.statuses
.show(**kwargs
)
743 url
= 'https://twitter.com/' + \
744 tweet
['user']['screen_name'] + '/status/' + str(tid
)
746 if platform
.system().lower() == 'darwin':
747 os
.system("echo '%s' | pbcopy" % url
)
748 printNicely(green('Copied tweet\'s url to clipboard.'))
750 printNicely('Direct link: ' + yellow(url
))
757 t
= Twitter(auth
=authen())
759 id = int(g
['stuff'].split()[0])
761 printNicely(red('Sorry I can\'t understand.'))
763 tid
= c
['tweet_dict'][id]
764 t
.statuses
.destroy(id=tid
)
765 printNicely(green('Okay it\'s gone.'))
772 t
= Twitter(auth
=authen())
774 target
= g
['stuff'].split()[0]
775 if target
!= 'image':
777 id = int(g
['stuff'].split()[1])
778 tid
= c
['tweet_dict'][id]
779 tweet
= t
.statuses
.show(id=tid
)
780 media
= tweet
['entities']['media']
782 res
= requests
.get(m
['media_url'])
783 img
= Image
.open(BytesIO(res
.content
))
787 printNicely(red('Sorry I can\'t show this image.'))
794 t
= Twitter(auth
=authen())
796 if not g
['stuff'].isdigit():
798 tid
= c
['tweet_dict'][int(g
['stuff'])]
799 tweet
= t
.statuses
.show(id=tid
)
800 urls
= tweet
['entities']['urls']
802 printNicely(light_magenta('No url here @.@!'))
806 expanded_url
= url
['expanded_url']
807 webbrowser
.open(expanded_url
)
810 printNicely(red('Sorry I can\'t open url in this tweet.'))
817 t
= Twitter(auth
=authen())
818 num
= c
['MESSAGES_DISPLAY']
819 if g
['stuff'].isdigit():
822 def inboxFilter(message
):
823 return message
['message_create']['sender_id'] == g
['id_str']
824 def sentFilter(message
):
825 return message
['message_create']['target']['recipient_id'] == g
['id_str']
827 def map_message(message
):
828 message_create
= message
['message_create']
829 sender
= t
.users
.show(id=int(message_create
['sender_id']),include_entities
=False)
830 recipient
= t
.users
.show(id=int(message_create
['target']['recipient_id']),include_entities
=False)
831 message
['sender_screen_name'] = sender
['screen_name']
832 message
['sender_name'] = sender
['name']
833 message
['recipient_screen_name'] = recipient
['screen_name']
834 message
['recipient_name'] = recipient
['name']
835 message
['text'] = message
['message_create']['message_data']['text']
836 message
['created_at'] = message
['created_timestamp']
840 messages
= t
.direct_messages
.events
.list()['events']
841 messages
= list(map(map_message
, messages
))
842 inbox
= list(filter(inboxFilter
, messages
))
843 sent
= list(filter(sentFilter
, messages
))
846 uniq_inbox
= list(set(
847 [(m
['sender_screen_name'], m
['sender_name']) for m
in inbox
]
849 uniq_sent
= list(set(
850 [(m
['recipient_screen_name'], m
['recipient_name']) for m
in sent
]
852 for partner
in uniq_inbox
:
853 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
855 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
856 d
[partner
] = inbox_ary
+ sent_ary
857 for partner
in uniq_sent
:
860 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
861 g
['message_threads'] = print_threads(d
)
866 View a thread of message
869 thread_id
= int(g
['stuff'])
871 g
['message_threads'][thread_id
],
876 printNicely(red('No such thread.'))
881 Send a direct message
883 t
= Twitter(auth
=authen())
885 user
= g
['stuff'].split()[0]
886 if user
[0].startswith('@'):
887 content
= ' '.join(g
['stuff'].split()[1:])
888 t
.direct_messages
.new(
889 screen_name
=user
[1:],
892 printNicely(green('Message sent.'))
894 printNicely(red('A name should begin with a \'@\''))
897 printNicely(red('Sorry I can\'t understand.'))
904 t
= Twitter(auth
=authen())
906 id = int(g
['stuff'].split()[0])
908 printNicely(red('Sorry I can\'t understand.'))
909 mid
= c
['message_dict'][id]
910 t
.direct_messages
.destroy(id=mid
)
911 printNicely(green('Message deleted.'))
916 List friends for followers
918 t
= Twitter(auth
=authen())
921 name
= g
['stuff'].split()[1]
922 if name
.startswith('@'):
925 printNicely(red('A name should begin with a \'@\''))
926 raise Exception('Invalid name')
928 name
= g
['original_name']
929 # Get list followers or friends
931 target
= g
['stuff'].split()[0]
933 printNicely(red('Omg some syntax is wrong.'))
936 d
= {'fl': 'followers', 'fr': 'friends'}
940 printNicely('All ' + d
[target
] + ':')
944 while next_cursor
!= 0:
946 list = getattr(t
, d
[target
]).list(
950 include_entities
=False,
953 for u
in list['users']:
959 + cycle_color( u
['name'] ) \
960 + color_func(c
['TWEET']['nick'])( ' @' \
964 next_cursor
= list['next_cursor']
966 # 300 users means 15 calls to the related API. The rate limit is 15
967 # calls per 15mn periods (see Twitter documentation).
968 if ( number_of_users
% 300 == 0 ):
969 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
970 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
973 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
979 t
= Twitter(auth
=authen())
980 screen_name
= g
['stuff'].split()[0]
981 if screen_name
.startswith('@'):
982 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
983 printNicely(green('You are following ' + screen_name
+ ' now!'))
985 printNicely(red('A name should begin with a \'@\''))
992 t
= Twitter(auth
=authen())
993 screen_name
= g
['stuff'].split()[0]
994 if screen_name
.startswith('@'):
995 t
.friendships
.destroy(
996 screen_name
=screen_name
[1:],
997 include_entities
=False)
998 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
1000 printNicely(red('A name should begin with a \'@\''))
1007 t
= Twitter(auth
=authen())
1009 screen_name
= g
['stuff'].split()[0]
1011 printNicely(red('A name should be specified. '))
1013 if screen_name
.startswith('@'):
1015 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1016 if isinstance(rel
, dict):
1017 printNicely(green(screen_name
+ ' is muted.'))
1018 c
['IGNORE_LIST'] += [screen_name
]
1019 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1021 printNicely(red(rel
))
1024 printNicely(red('Something is wrong, can not mute now :('))
1026 printNicely(red('A name should begin with a \'@\''))
1033 t
= Twitter(auth
=authen())
1035 screen_name
= g
['stuff'].split()[0]
1037 printNicely(red('A name should be specified. '))
1039 if screen_name
.startswith('@'):
1041 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1042 if isinstance(rel
, dict):
1043 printNicely(green(screen_name
+ ' is unmuted.'))
1044 c
['IGNORE_LIST'].remove(screen_name
)
1046 printNicely(red(rel
))
1048 printNicely(red('Maybe you are not muting this person ?'))
1050 printNicely(red('A name should begin with a \'@\''))
1057 # Get dict of muting users
1058 md
= build_mute_dict(dict_data
=True)
1059 printNicely('All: ' + str(len(md
)) + ' people.')
1061 user
= ' ' + cycle_color(md
[name
])
1062 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1064 # Update from Twitter
1065 c
['IGNORE_LIST'] = [n
for n
in md
]
1072 t
= Twitter(auth
=authen())
1073 screen_name
= g
['stuff'].split()[0]
1074 if screen_name
.startswith('@'):
1076 screen_name
=screen_name
[1:],
1077 include_entities
=False,
1079 printNicely(green('You blocked ' + screen_name
+ '.'))
1081 printNicely(red('A name should begin with a \'@\''))
1088 t
= Twitter(auth
=authen())
1089 screen_name
= g
['stuff'].split()[0]
1090 if screen_name
.startswith('@'):
1092 screen_name
=screen_name
[1:],
1093 include_entities
=False,
1095 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1097 printNicely(red('A name should begin with a \'@\''))
1102 Report a user as a spam account
1104 t
= Twitter(auth
=authen())
1105 screen_name
= g
['stuff'].split()[0]
1106 if screen_name
.startswith('@'):
1107 t
.users
.report_spam(
1108 screen_name
=screen_name
[1:])
1109 printNicely(green('You reported ' + screen_name
+ '.'))
1111 printNicely(red('Sorry I can\'t understand.'))
1119 list_name
= raw_input(
1120 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1121 # Get list name and owner
1123 owner
, slug
= list_name
.split('/')
1124 if slug
.startswith('@'):
1129 light_magenta('List name should follow "@owner/list_name" format.'))
1130 raise Exception('Wrong list name')
1133 def check_slug(list_name
):
1137 # Get list name and owner
1139 owner
, slug
= list_name
.split('/')
1140 if slug
.startswith('@'):
1145 light_magenta('List name should follow "@owner/list_name" format.'))
1146 raise Exception('Wrong list name')
1153 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1157 printNicely(light_magenta('You belong to no lists :)'))
1164 owner
, slug
= get_slug()
1165 res
= t
.lists
.statuses(
1167 owner_screen_name
=owner
,
1168 count
=c
['LIST_MAX'],
1169 include_entities
=False)
1170 for tweet
in reversed(res
):
1175 def list_members(t
):
1179 owner
, slug
= get_slug()
1183 while next_cursor
!= 0:
1184 m
= t
.lists
.members(
1186 owner_screen_name
=owner
,
1188 include_entities
=False)
1189 for u
in m
['users']:
1190 rel
[u
['name']] = '@' + u
['screen_name']
1191 next_cursor
= m
['next_cursor']
1192 printNicely('All: ' + str(len(rel
)) + ' members.')
1194 user
= ' ' + cycle_color(name
)
1195 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1199 def list_subscribers(t
):
1203 owner
, slug
= get_slug()
1207 while next_cursor
!= 0:
1208 m
= t
.lists
.subscribers(
1210 owner_screen_name
=owner
,
1212 include_entities
=False)
1213 for u
in m
['users']:
1214 rel
[u
['name']] = '@' + u
['screen_name']
1215 next_cursor
= m
['next_cursor']
1216 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1218 user
= ' ' + cycle_color(name
)
1219 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1225 Add specific user to a list
1227 owner
, slug
= get_slug()
1229 user_name
= raw_input(
1231 'Give me name of the newbie: ',
1233 if user_name
.startswith('@'):
1234 user_name
= user_name
[1:]
1236 t
.lists
.members
.create(
1238 owner_screen_name
=owner
,
1239 screen_name
=user_name
)
1240 printNicely(green('Added.'))
1243 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1248 Remove specific user from a list
1250 owner
, slug
= get_slug()
1252 user_name
= raw_input(
1254 'Give me name of the unlucky one: ',
1256 if user_name
.startswith('@'):
1257 user_name
= user_name
[1:]
1259 t
.lists
.members
.destroy(
1261 owner_screen_name
=owner
,
1262 screen_name
=user_name
)
1263 printNicely(green('Gone.'))
1266 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1269 def list_subscribe(t
):
1273 owner
, slug
= get_slug()
1276 t
.lists
.subscribers
.create(
1278 owner_screen_name
=owner
)
1279 printNicely(green('Done.'))
1283 light_magenta('I\'m sorry you can not subscribe to this list.'))
1286 def list_unsubscribe(t
):
1290 owner
, slug
= get_slug()
1293 t
.lists
.subscribers
.destroy(
1295 owner_screen_name
=owner
)
1296 printNicely(green('Done.'))
1300 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1309 while next_cursor
!= 0:
1310 res
= t
.lists
.ownerships(
1311 screen_name
=g
['original_name'],
1314 next_cursor
= res
['next_cursor']
1318 printNicely(light_magenta('You own no lists :)'))
1325 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1328 'New list\'s mode (public/private): ',
1330 description
= raw_input(
1332 'New list\'s description: ',
1338 description
=description
)
1339 printNicely(green(name
+ ' list is created.'))
1342 printNicely(red('Oops something is wrong with Twitter :('))
1351 'Your list that you want to update: ',
1355 'Update name (leave blank to unchange): ',
1357 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1358 description
= raw_input(light_magenta('Update description: ', rl
=True))
1362 slug
='-'.join(slug
.split()),
1363 owner_screen_name
=g
['original_name'],
1366 description
=description
)
1370 owner_screen_name
=g
['original_name'],
1372 description
=description
)
1373 printNicely(green(slug
+ ' list is updated.'))
1376 printNicely(red('Oops something is wrong with Twitter :('))
1385 'Your list that you want to delete: ',
1389 slug
='-'.join(slug
.split()),
1390 owner_screen_name
=g
['original_name'])
1391 printNicely(green(slug
+ ' list is deleted.'))
1394 printNicely(red('Oops something is wrong with Twitter :('))
1401 t
= Twitter(auth
=authen())
1402 # List all lists or base on action
1404 g
['list_action'] = g
['stuff'].split()[0]
1411 'all_mem': list_members
,
1412 'all_sub': list_subscribers
,
1415 'sub': list_subscribe
,
1416 'unsub': list_unsubscribe
,
1419 'update': list_update
,
1423 return action_ary
[g
['list_action']](t
)
1425 printNicely(red('Please try again.'))
1433 target
= g
['stuff'].split()[0]
1435 args
= parse_arguments()
1437 if g
['stuff'].split()[-1] == '-f':
1438 guide
= 'To ignore an option, just hit Enter key.'
1439 printNicely(light_magenta(guide
))
1440 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1441 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1442 args
.filter = list(filter(None, only
.split(',')))
1443 args
.ignore
= list(filter(None, ignore
.split(',')))
1445 printNicely(red('Sorry, wrong format.'))
1448 g
['stream_stop'] = True
1450 stuff
= g
['stuff'].split()[1]
1455 'public': spawn_public_stream
,
1456 'list': spawn_list_stream
,
1457 'mine': spawn_personal_stream
,
1459 spawn_dict
.get(target
)(args
, stuff
)
1462 printNicely(red('Sorry I can\'t understand.'))
1467 Unix's command `cal`
1470 rel
= os
.popen('cal').read().split('\n')
1473 show_calendar(month
, date
, rel
)
1478 List and change theme
1482 for theme
in g
['themes']:
1483 line
= light_magenta(theme
)
1484 if c
['THEME'] == theme
:
1485 line
= ' ' * 2 + light_yellow('* ') + line
1487 line
= ' ' * 4 + line
1493 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1494 # Redefine decorated_name
1495 g
['decorated_name'] = lambda x
: color_func(
1496 c
['DECORATED_NAME'])(
1497 '[' + x
+ ']: ', rl
=True)
1498 printNicely(green('Theme changed.'))
1500 printNicely(red('No such theme exists.'))
1505 Browse and change config
1507 all_config
= get_all_config()
1508 g
['stuff'] = g
['stuff'].strip()
1511 for k
in all_config
:
1513 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1515 guide
= 'Detailed explanation can be found at ' + \
1516 color_func(c
['TWEET']['link'])(
1517 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1519 # Print specific config
1520 elif len(g
['stuff'].split()) == 1:
1521 if g
['stuff'] in all_config
:
1524 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1527 printNicely(red('No such config key.'))
1528 # Print specific config's default value
1529 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1530 key
= g
['stuff'].split()[0]
1532 value
= get_default_config(key
)
1533 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1537 printNicely(red('Just can not get the default.'))
1538 # Delete specific config key in config file
1539 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1540 key
= g
['stuff'].split()[0]
1543 printNicely(green('Config key is dropped.'))
1546 printNicely(red('Just can not drop the key.'))
1547 # Set specific config
1548 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1549 key
= g
['stuff'].split()[0]
1550 value
= g
['stuff'].split()[-1]
1551 if key
== 'THEME' and not validate_theme(value
):
1552 printNicely(red('Invalid theme\'s value.'))
1555 set_config(key
, value
)
1556 # Keys that needs to be apply immediately
1558 c
['THEME'] = reload_theme(value
, c
['THEME'])
1559 g
['decorated_name'] = lambda x
: color_func(
1560 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
1561 elif key
== 'PREFIX':
1562 g
['PREFIX'] = u2str(emojize(format_prefix(
1563 listname
=g
['listname'],
1564 keyword
=g
['keyword']
1567 printNicely(green('Updated successfully.'))
1570 printNicely(red('Just can not set the key.'))
1572 printNicely(light_magenta('Sorry I can\'t understand.'))
1575 def help_discover():
1580 # Discover the world
1582 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1583 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1584 'You can try ' + light_green('trend US') + ' or ' + \
1585 light_green('trend JP Tokyo') + '.\n'
1586 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1587 light_green('home 7') + ' will show 7 tweets.\n'
1588 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1589 light_green('me 2') + ' will show your last 2 tweets.\n'
1591 light_green('notification') + ' will show your recent notification.\n'
1592 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1593 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1594 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1595 magenta('@mdo') + '.\n'
1596 usage
+= s
* 2 + light_green('view @mdo') + \
1597 ' will show ' + magenta('@mdo') + '\'s home.\n'
1598 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1599 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1600 'Search can be performed with or without hashtag.\n'
1611 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1612 usage
+= s
* 2 + light_green('t oops ') + \
1613 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1615 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1616 light_yellow('[id=12]') + '.\n'
1618 light_green('quote 12 ') + ' will quote the tweet with ' + \
1619 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1620 'the quote will be canceled.\n'
1622 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1623 light_yellow('[id=12]') + '.\n'
1624 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1625 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1626 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1627 light_yellow('oops') + '" to the owner of the tweet with ' + \
1628 light_yellow('[id=12]') + '.\n'
1629 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1630 light_yellow('oops') + '" to all people in the tweet with ' + \
1631 light_yellow('[id=12]') + '.\n'
1633 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1634 light_yellow('[id=12]') + '.\n'
1636 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1637 light_yellow('[id=12]') + '.\n'
1639 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1640 light_yellow('[id=12]') + '.\n'
1642 light_green('del 12 ') + ' will delete tweet with ' + \
1643 light_yellow('[id=12]') + '.\n'
1644 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1645 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1646 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1647 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1648 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1649 light_yellow('[id=12]') + ' in your Pocket list.\n'
1653 def help_messages():
1660 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1661 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1662 light_green('inbox 7') + ' will show newest 7 messages.\n'
1663 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1664 light_yellow('[thread_id=2]') + '.\n'
1665 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1666 magenta('@dtvd88') + '.\n'
1667 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1668 light_yellow('[message_id=5]') + '.\n'
1672 def help_friends_and_followers():
1674 Friends and Followers
1677 # Follower and following
1679 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1681 light_green('ls fl') + \
1682 ' will list all followers (people who are following you).\n'
1684 light_green('ls fr') + \
1685 ' will list all friends (people who you are following).\n'
1686 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1687 magenta('@dtvd88') + '.\n'
1688 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1689 magenta('@dtvd88') + '.\n'
1690 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1691 magenta('@dtvd88') + '.\n'
1692 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1693 magenta('@dtvd88') + '.\n'
1694 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1695 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1696 magenta('@dtvd88') + '.\n'
1697 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1698 magenta('@dtvd88') + '.\n'
1699 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1700 magenta('@dtvd88') + ' as a spam account.\n'
1711 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1712 usage
+= s
* 2 + light_green('list') + \
1713 ' will show all lists you are belong to.\n'
1714 usage
+= s
* 2 + light_green('list home') + \
1715 ' will show timeline of list. You will be asked for list\'s name.\n'
1716 usage
+= s
* 2 + light_green('list all_mem') + \
1717 ' will show list\'s all members.\n'
1718 usage
+= s
* 2 + light_green('list all_sub') + \
1719 ' will show list\'s all subscribers.\n'
1720 usage
+= s
* 2 + light_green('list add') + \
1721 ' will add specific person to a list owned by you.' + \
1722 ' You will be asked for list\'s name and person\'s name.\n'
1723 usage
+= s
* 2 + light_green('list rm') + \
1724 ' will remove specific person from a list owned by you.' + \
1725 ' You will be asked for list\'s name and person\'s name.\n'
1726 usage
+= s
* 2 + light_green('list sub') + \
1727 ' will subscribe you to a specific list.\n'
1728 usage
+= s
* 2 + light_green('list unsub') + \
1729 ' will unsubscribe you from a specific list.\n'
1730 usage
+= s
* 2 + light_green('list own') + \
1731 ' will show all list owned by you.\n'
1732 usage
+= s
* 2 + light_green('list new') + \
1733 ' will create a new list.\n'
1734 usage
+= s
* 2 + light_green('list update') + \
1735 ' will update a list owned by you.\n'
1736 usage
+= s
* 2 + light_green('list del') + \
1737 ' will delete a list owned by you.\n'
1748 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1749 usage
+= s
* 2 + light_green('switch public #AKB') + \
1750 ' will switch to public stream and follow "' + \
1751 light_yellow('AKB') + '" keyword.\n'
1752 usage
+= s
* 2 + light_green('switch mine') + \
1753 ' will switch to your personal stream.\n'
1754 usage
+= s
* 2 + light_green('switch mine -f ') + \
1755 ' will prompt to enter the filter.\n'
1756 usage
+= s
* 3 + light_yellow('Only nicks') + \
1757 ' filter will decide nicks will be INCLUDE ONLY.\n'
1758 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1759 ' filter will decide nicks will be EXCLUDE.\n'
1760 usage
+= s
* 2 + light_green('switch list') + \
1761 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1770 h
, w
= os
.popen('stty size', 'r').read().split()
1773 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1774 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1775 usage
+= s
+ 'You are ' + \
1776 light_yellow('already') + ' on your personal stream.\n'
1777 usage
+= s
+ 'Any update from Twitter will show up ' + \
1778 light_yellow('immediately') + '.\n'
1779 usage
+= s
+ 'In addition, following commands are available right now:\n'
1780 # Twitter help section
1782 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1783 usage
+= s
* 2 + light_green('h discover') + \
1784 ' will show help for discover commands.\n'
1785 usage
+= s
* 2 + light_green('h tweets') + \
1786 ' will show help for tweets commands.\n'
1787 usage
+= s
* 2 + light_green('h messages') + \
1788 ' will show help for messages commands.\n'
1789 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1790 ' will show help for friends and followers commands.\n'
1791 usage
+= s
* 2 + light_green('h list') + \
1792 ' will show help for list commands.\n'
1793 usage
+= s
* 2 + light_green('h stream') + \
1794 ' will show help for stream commands.\n'
1797 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1798 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1799 'will be evaluate by Python interpreter.\n'
1800 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1801 ' for current month.\n'
1804 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1805 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1806 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1807 ' theme immediately.\n'
1808 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1810 light_green('config ASCII_ART') + ' will output current value of ' +\
1811 light_yellow('ASCII_ART') + ' config key.\n'
1813 light_green('config TREND_MAX default') + ' will output default value of ' + \
1814 light_yellow('TREND_MAX') + ' config key.\n'
1816 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1817 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1819 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1820 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1821 light_yellow('True') + '.\n'
1824 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1825 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1826 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1827 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1828 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1829 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1830 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1833 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1834 usage
+= s
+ 'Have fun and hang tight! \n'
1837 'discover': help_discover
,
1838 'tweets': help_tweets
,
1839 'messages': help_messages
,
1840 'friends_and_followers': help_friends_and_followers
,
1842 'stream': help_stream
,
1847 lambda: printNicely(red('No such command.'))
1855 Pause stream display
1858 printNicely(green('Stream is paused'))
1866 printNicely(green('Stream is running back now'))
1882 printNicely(green('See you next time :)'))
1890 Reset prefix of line
1893 if c
.get('USER_JSON_ERROR'):
1894 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1895 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1897 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1900 printNicely(str(eval(g
['cmd'])))
1955 # Handle function set
2010 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2015 Listen to user's input
2020 ['public', 'mine', 'list'], # switch
2029 [], # view_my_tweets
2040 ['image'], # show image
2042 ['fl', 'fr'], # list
2044 [i
for i
in g
['message_threads']], # sent
2069 [key
for key
in dict(get_all_config())], # config
2070 g
['themes'], # theme
2075 'friends_and_followers',
2087 init_interactive_shell(d
)
2094 # Only use PREFIX as a string with raw_input
2095 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2098 # Save cmd to compare with readline buffer
2099 g
['cmd'] = line
.strip()
2100 # Get short cmd to pass to handle function
2102 cmd
= line
.split()[0]
2105 # Lock the semaphore
2107 # Save cmd to global variable and call process
2108 g
['stuff'] = ' '.join(line
.split()[1:])
2109 # Check tweet length
2110 # Process the command
2113 if cmd
in ['switch', 't', 'rt', 'rep']:
2119 except TwitterHTTPError
as e
:
2120 detail_twitter_error(e
)
2123 printNicely(red('OMG something is wrong with Twitter API right now.'))
2125 # Release the semaphore lock
2129 def reconn_notice():
2131 Notice when Hangup or Timeout
2133 guide
= light_magenta('You can use ') + \
2134 light_green('switch') + \
2135 light_magenta(' command to return to your stream.\n')
2136 guide
+= light_magenta('Type ') + \
2137 light_green('h stream') + \
2138 light_magenta(' for more details.')
2140 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2144 def stream(domain
, args
, name
='Rainbow Stream'):
2150 c
['USER_DOMAIN']: name
,
2151 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2152 c
['SITE_DOMAIN']: name
,
2155 ascii_art(art_dict
.get(domain
, name
))
2156 # These arguments are optional:
2158 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2160 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2163 if args
.track_keywords
:
2164 query_args
['track'] = args
.track_keywords
2168 time
.sleep(polling_time
)
2171 def spawn_public_stream(args
, keyword
=None):
2173 Spawn a new public stream
2175 # Only set keyword if specified
2177 if keyword
[0] == '#':
2178 keyword
= keyword
[1:]
2179 args
.track_keywords
= keyword
2180 g
['keyword'] = keyword
2182 g
['keyword'] = 'Global'
2183 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2186 th
= threading
.Thread(
2195 def spawn_list_stream(args
, stuff
=None):
2197 Spawn a new list stream
2200 owner
, slug
= check_slug(stuff
)
2202 owner
, slug
= get_slug()
2204 # Force python 2 not redraw readline buffer
2205 listname
= '/'.join([owner
, slug
])
2206 # Set the listname variable
2207 # and reset tracked keyword
2208 g
['listname'] = listname
2210 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2211 listname
=g
['listname']
2213 printNicely(light_yellow('getting list members ...'))
2215 t
= Twitter(auth
=authen())
2218 while next_cursor
!= 0:
2219 m
= t
.lists
.members(
2221 owner_screen_name
=owner
,
2223 include_entities
=False)
2224 for u
in m
['users']:
2225 members
.append('@' + u
['screen_name'])
2226 next_cursor
= m
['next_cursor']
2227 printNicely(light_yellow('... done.'))
2228 # Build thread filter array
2229 args
.filter = members
2231 th
= threading
.Thread(
2241 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2243 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2247 def spawn_personal_stream(args
, stuff
=None):
2249 Spawn a new personal stream
2251 # Reset the tracked keyword and listname
2252 g
['keyword'] = g
['listname'] = ''
2254 g
['PREFIX'] = u2str(emojize(format_prefix()))
2256 th
= threading
.Thread(
2261 g
['original_name']))
2271 args
= parse_arguments()
2275 # Twitter API connection problem
2276 except TwitterHTTPError
as e
:
2279 magenta('We have connection problem with twitter REST API right now :('))
2280 detail_twitter_error(e
)
2283 # Proxy connection problem
2284 except (socks
.ProxyConnectionError
, URLError
):
2286 magenta('There seems to be a connection problem.'))
2288 magenta('You might want to check your proxy settings (host, port and type)!'))
2292 # Spawn stream thread
2293 target
= args
.stream
.split()[0]
2294 if target
== 'mine':
2295 spawn_personal_stream(args
)
2298 stuff
= args
.stream
.split()[1]
2302 'public': spawn_public_stream
,
2303 'list': spawn_list_stream
,
2305 spawn_dict
.get(target
)(args
, stuff
)
2307 # Start listen process