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 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
, tweet_mode
='extended')):
343 for e
in c
['events']:
347 printNicely(magenta('Nothing at this time.'))
354 t
= Twitter(auth
=authen())
355 num
= c
['HOME_TWEET_NUM']
356 if g
['stuff'].isdigit():
357 num
= int(g
['stuff'])
358 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
, tweet_mode
='extended')):
365 Show profile of a specific user
367 t
= Twitter(auth
=authen())
369 screen_name
= g
['stuff'].split()[0]
371 printNicely(red('Sorry I can\'t understand.'))
373 if screen_name
.startswith('@'):
376 screen_name
=screen_name
[1:],
377 include_entities
=False)
381 printNicely(red('No user.'))
383 printNicely(red('A name should begin with a \'@\''))
390 t
= Twitter(auth
=authen())
392 user
= g
['stuff'].split()[0]
394 printNicely(red('Sorry I can\'t understand.'))
398 num
= int(g
['stuff'].split()[1])
400 num
= c
['HOME_TWEET_NUM']
401 for tweet
in reversed(
402 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:], tweet_mode
='extended')):
406 printNicely(red('A name should begin with a \'@\''))
409 def view_my_tweets():
411 Display user's recent tweets.
413 t
= Twitter(auth
=authen())
415 num
= int(g
['stuff'])
417 num
= c
['HOME_TWEET_NUM']
418 for tweet
in reversed(
419 t
.statuses
.user_timeline(count
=num
, screen_name
=g
['original_name'], tweet_mode
='extended')):
428 t
= Twitter(auth
=authen())
430 query
= g
['stuff'].strip()
432 printNicely(red('Sorry I can\'t understand.'))
434 type = c
['SEARCH_TYPE']
435 if type not in ['mixed', 'recent', 'popular']:
437 max_record
= c
['SEARCH_MAX_RECORD']
438 count
= min(max_record
, 100)
440 rel
= t
.search
.tweets(
444 tweet_mode
='extended'
448 printNicely('Newest tweets:')
449 for i
in reversed(xrange(count
)):
450 draw(t
=rel
[i
], keyword
=query
)
453 printNicely(magenta('I\'m afraid there is no result'))
460 t
= Twitter(auth
=authen())
461 t
.statuses
.update(status
=g
['stuff'])
466 Add new link to Pocket along with tweet id
468 if not c
['POCKET_SUPPORT']:
469 printNicely(yellow('Pocket isn\'t enabled.'))
470 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
476 t
= Twitter(auth
=authen())
478 id = int(g
['stuff'].split()[0])
479 tid
= c
['tweet_dict'][id]
481 printNicely(red('Sorry I can\'t understand.'))
484 tweet
= t
.statuses
.show(id=tid
)
486 if len(tweet
['entities']['urls']) > 0:
487 url
= tweet
['entities']['urls'][0]['expanded_url']
489 url
= "https://twitter.com/" + \
490 tweet
['user']['screen_name'] + '/status/' + str(tid
)
494 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
498 printNicely(red('Something is wrong about your Pocket account,'+ \
499 ' please restart Rainbowstream.'))
500 pocket_credential
= os
.environ
.get(
504 '')) + os
.sep
+ '.rainbow_pckt_oauth'
505 if os
.path
.exists(pocket_credential
):
506 os
.remove(pocket_credential
)
509 printNicely(green('Pocketed !'))
517 t
= Twitter(auth
=authen())
519 id = int(g
['stuff'].split()[0])
521 printNicely(red('Sorry I can\'t understand.'))
523 tid
= c
['tweet_dict'][id]
524 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
532 t
= Twitter(auth
=authen())
534 id = int(g
['stuff'].split()[0])
536 printNicely(red('Sorry I can\'t understand.'))
538 tid
= c
['tweet_dict'][id]
539 tweet
= t
.statuses
.show(id=tid
, tweet_mode
='extended')
541 formater
= format_quote(tweet
)
545 prefix
= light_magenta('Compose your ', rl
=True) + \
546 light_green('#comment: ', rl
=True)
547 comment
= raw_input(prefix
)
549 quote
= comment
.join(formater
.split('#comment'))
550 t
.statuses
.update(status
=quote
)
552 printNicely(light_magenta('No text added.'))
559 t
= Twitter(auth
=authen())
562 id = int(g
['stuff'].split()[0])
564 printNicely(red('Sorry I can\'t understand.'))
566 tid
= c
['tweet_dict'][id]
567 # Get display num if exist
569 num
= int(g
['stuff'].split()[1])
571 num
= c
['RETWEETS_SHOW_NUM']
572 # Get result and display
573 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
, tweet_mode
='extended')
575 printNicely(magenta('This tweet has no retweet.'))
577 for tweet
in reversed(rt_ary
):
586 t
= Twitter(auth
=authen())
588 id = int(g
['stuff'].split()[0])
590 printNicely(red('Sorry I can\'t understand.'))
592 tid
= c
['tweet_dict'][id]
593 tweet
= t
.statuses
.show(id=tid
, tweet_mode
='extended')
594 limit
= c
['CONVERSATION_MAX']
596 thread_ref
.append(tweet
)
597 prev_tid
= tweet
['in_reply_to_status_id']
598 while prev_tid
and limit
:
600 tweet
= t
.statuses
.show(id=prev_tid
, tweet_mode
='extended')
601 prev_tid
= tweet
['in_reply_to_status_id']
602 thread_ref
.append(tweet
)
604 for tweet
in reversed(thread_ref
):
613 t
= Twitter(auth
=authen())
615 id = int(g
['stuff'].split()[0])
617 printNicely(red('Sorry I can\'t understand.'))
619 tid
= c
['tweet_dict'][id]
620 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
621 status
= ' '.join(g
['stuff'].split()[1:])
622 # don't include own username for tweet chains
623 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
624 if user
== g
['original_name']:
625 status
= str2u(status
)
627 status
= '@' + user
+ ' ' + str2u(status
)
628 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
635 t
= Twitter(auth
=authen())
637 id = int(g
['stuff'].split()[0])
639 printNicely(red('Sorry I can\'t understand.'))
641 tid
= c
['tweet_dict'][id]
642 original_tweet
= t
.statuses
.show(id=tid
)
643 text
= original_tweet
['text']
644 nick_ary
= [original_tweet
['user']['screen_name']]
645 for user
in list(original_tweet
['entities']['user_mentions']):
646 if user
['screen_name'] not in nick_ary \
647 and user
['screen_name'] != g
['original_name']:
648 nick_ary
.append(user
['screen_name'])
649 status
= ' '.join(g
['stuff'].split()[1:])
650 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + 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 t
.favorites
.create(_id
=tid
, include_entities
=False)
666 printNicely(green('Favorited.'))
667 draw(t
.statuses
.show(id=tid
, tweet_mode
='extended'))
675 t
= Twitter(auth
=authen())
677 id = int(g
['stuff'].split()[0])
679 printNicely(red('Sorry I can\'t understand.'))
681 tid
= c
['tweet_dict'][id]
682 t
.favorites
.destroy(_id
=tid
)
683 printNicely(green('Okay it\'s unfavorited.'))
684 draw(t
.statuses
.show(id=tid
, tweet_mode
='extended'))
690 Copy url of a tweet to clipboard
692 t
= Twitter(auth
=authen())
694 id = int(g
['stuff'].split()[0])
695 tid
= c
['tweet_dict'][id]
697 printNicely(red('Tweet id is not valid.'))
699 tweet
= t
.statuses
.show(id=tid
, tweet_mode
='extended')
700 url
= 'https://twitter.com/' + \
701 tweet
['user']['screen_name'] + '/status/' + str(tid
)
703 if platform
.system().lower() == 'darwin':
704 os
.system("echo '%s' | pbcopy" % url
)
705 printNicely(green('Copied tweet\'s url to clipboard.'))
707 printNicely('Direct link: ' + yellow(url
))
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
.statuses
.destroy(id=tid
)
722 printNicely(green('Okay it\'s gone.'))
729 t
= Twitter(auth
=authen())
731 target
= g
['stuff'].split()[0]
732 if target
!= 'image':
734 id = int(g
['stuff'].split()[1])
735 tid
= c
['tweet_dict'][id]
736 tweet
= t
.statuses
.show(id=tid
)
737 media
= tweet
['entities']['media']
739 res
= requests
.get(m
['media_url'])
740 img
= Image
.open(BytesIO(res
.content
))
744 printNicely(red('Sorry I can\'t show this image.'))
751 t
= Twitter(auth
=authen())
753 if not g
['stuff'].isdigit():
755 tid
= c
['tweet_dict'][int(g
['stuff'])]
756 tweet
= t
.statuses
.show(id=tid
)
757 urls
= tweet
['entities']['urls']
759 printNicely(light_magenta('No url here @.@!'))
763 expanded_url
= url
['expanded_url']
764 webbrowser
.open(expanded_url
)
767 printNicely(red('Sorry I can\'t open url in this tweet.'))
774 t
= Twitter(auth
=authen())
775 num
= c
['MESSAGES_DISPLAY']
776 if g
['stuff'].isdigit():
782 inbox
= inbox
+ t
.direct_messages(
785 include_entities
=False,
790 inbox
= inbox
+ t
.direct_messages(
793 include_entities
=False,
797 num
= c
['MESSAGES_DISPLAY']
798 if g
['stuff'].isdigit():
803 sent
= sent
+ t
.direct_messages
.sent(
806 include_entities
=False,
811 sent
= sent
+ t
.direct_messages
.sent(
814 include_entities
=False,
819 uniq_inbox
= list(set(
820 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
822 uniq_sent
= list(set(
823 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
825 for partner
in uniq_inbox
:
826 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
828 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
829 d
[partner
] = inbox_ary
+ sent_ary
830 for partner
in uniq_sent
:
833 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
834 g
['message_threads'] = print_threads(d
)
839 View a thread of message
842 thread_id
= int(g
['stuff'])
844 g
['message_threads'][thread_id
],
849 printNicely(red('No such thread.'))
854 Send a direct message
856 t
= Twitter(auth
=authen())
858 user
= g
['stuff'].split()[0]
859 if user
[0].startswith('@'):
860 content
= ' '.join(g
['stuff'].split()[1:])
861 t
.direct_messages
.new(
862 screen_name
=user
[1:],
865 printNicely(green('Message sent.'))
867 printNicely(red('A name should begin with a \'@\''))
870 printNicely(red('Sorry I can\'t understand.'))
877 t
= Twitter(auth
=authen())
879 id = int(g
['stuff'].split()[0])
881 printNicely(red('Sorry I can\'t understand.'))
882 mid
= c
['message_dict'][id]
883 t
.direct_messages
.destroy(id=mid
)
884 printNicely(green('Message deleted.'))
889 List friends for followers
891 t
= Twitter(auth
=authen())
894 name
= g
['stuff'].split()[1]
895 if name
.startswith('@'):
898 printNicely(red('A name should begin with a \'@\''))
899 raise Exception('Invalid name')
901 name
= g
['original_name']
902 # Get list followers or friends
904 target
= g
['stuff'].split()[0]
906 printNicely(red('Omg some syntax is wrong.'))
909 d
= {'fl': 'followers', 'fr': 'friends'}
913 printNicely('All ' + d
[target
] + ':')
917 while next_cursor
!= 0:
919 list = getattr(t
, d
[target
]).list(
923 include_entities
=False,
926 for u
in list['users']:
932 + cycle_color( u
['name'] ) \
933 + color_func(c
['TWEET']['nick'])( ' @' \
937 next_cursor
= list['next_cursor']
939 # 300 users means 15 calls to the related API. The rate limit is 15
940 # calls per 15mn periods (see Twitter documentation).
941 if ( number_of_users
% 300 == 0 ):
942 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
943 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
946 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
952 t
= Twitter(auth
=authen())
953 screen_name
= g
['stuff'].split()[0]
954 if screen_name
.startswith('@'):
955 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
956 printNicely(green('You are following ' + screen_name
+ ' now!'))
958 printNicely(red('A name should begin with a \'@\''))
965 t
= Twitter(auth
=authen())
966 screen_name
= g
['stuff'].split()[0]
967 if screen_name
.startswith('@'):
968 t
.friendships
.destroy(
969 screen_name
=screen_name
[1:],
970 include_entities
=False)
971 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
973 printNicely(red('A name should begin with a \'@\''))
980 t
= Twitter(auth
=authen())
982 screen_name
= g
['stuff'].split()[0]
984 printNicely(red('A name should be specified. '))
986 if screen_name
.startswith('@'):
988 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
989 if isinstance(rel
, dict):
990 printNicely(green(screen_name
+ ' is muted.'))
991 c
['IGNORE_LIST'] += [screen_name
]
992 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
994 printNicely(red(rel
))
997 printNicely(red('Something is wrong, can not mute now :('))
999 printNicely(red('A name should begin with a \'@\''))
1006 t
= Twitter(auth
=authen())
1008 screen_name
= g
['stuff'].split()[0]
1010 printNicely(red('A name should be specified. '))
1012 if screen_name
.startswith('@'):
1014 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1015 if isinstance(rel
, dict):
1016 printNicely(green(screen_name
+ ' is unmuted.'))
1017 c
['IGNORE_LIST'].remove(screen_name
)
1019 printNicely(red(rel
))
1021 printNicely(red('Maybe you are not muting this person ?'))
1023 printNicely(red('A name should begin with a \'@\''))
1030 # Get dict of muting users
1031 md
= build_mute_dict(dict_data
=True)
1032 printNicely('All: ' + str(len(md
)) + ' people.')
1034 user
= ' ' + cycle_color(md
[name
])
1035 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1037 # Update from Twitter
1038 c
['IGNORE_LIST'] = [n
for n
in md
]
1045 t
= Twitter(auth
=authen())
1046 screen_name
= g
['stuff'].split()[0]
1047 if screen_name
.startswith('@'):
1049 screen_name
=screen_name
[1:],
1050 include_entities
=False,
1052 printNicely(green('You blocked ' + screen_name
+ '.'))
1054 printNicely(red('A name should begin with a \'@\''))
1061 t
= Twitter(auth
=authen())
1062 screen_name
= g
['stuff'].split()[0]
1063 if screen_name
.startswith('@'):
1065 screen_name
=screen_name
[1:],
1066 include_entities
=False,
1068 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1070 printNicely(red('A name should begin with a \'@\''))
1075 Report a user as a spam account
1077 t
= Twitter(auth
=authen())
1078 screen_name
= g
['stuff'].split()[0]
1079 if screen_name
.startswith('@'):
1080 t
.users
.report_spam(
1081 screen_name
=screen_name
[1:])
1082 printNicely(green('You reported ' + screen_name
+ '.'))
1084 printNicely(red('Sorry I can\'t understand.'))
1092 list_name
= raw_input(
1093 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1094 # Get list name and owner
1096 owner
, slug
= list_name
.split('/')
1097 if slug
.startswith('@'):
1102 light_magenta('List name should follow "@owner/list_name" format.'))
1103 raise Exception('Wrong list name')
1106 def check_slug(list_name
):
1110 # Get list name and owner
1112 owner
, slug
= list_name
.split('/')
1113 if slug
.startswith('@'):
1118 light_magenta('List name should follow "@owner/list_name" format.'))
1119 raise Exception('Wrong list name')
1126 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1130 printNicely(light_magenta('You belong to no lists :)'))
1137 owner
, slug
= get_slug()
1138 res
= t
.lists
.statuses(
1140 owner_screen_name
=owner
,
1141 count
=c
['LIST_MAX'],
1142 include_entities
=False)
1143 for tweet
in reversed(res
):
1148 def list_members(t
):
1152 owner
, slug
= get_slug()
1156 while next_cursor
!= 0:
1157 m
= t
.lists
.members(
1159 owner_screen_name
=owner
,
1161 include_entities
=False)
1162 for u
in m
['users']:
1163 rel
[u
['name']] = '@' + u
['screen_name']
1164 next_cursor
= m
['next_cursor']
1165 printNicely('All: ' + str(len(rel
)) + ' members.')
1167 user
= ' ' + cycle_color(name
)
1168 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1172 def list_subscribers(t
):
1176 owner
, slug
= get_slug()
1180 while next_cursor
!= 0:
1181 m
= t
.lists
.subscribers(
1183 owner_screen_name
=owner
,
1185 include_entities
=False)
1186 for u
in m
['users']:
1187 rel
[u
['name']] = '@' + u
['screen_name']
1188 next_cursor
= m
['next_cursor']
1189 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1191 user
= ' ' + cycle_color(name
)
1192 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1198 Add specific user to a list
1200 owner
, slug
= get_slug()
1202 user_name
= raw_input(
1204 'Give me name of the newbie: ',
1206 if user_name
.startswith('@'):
1207 user_name
= user_name
[1:]
1209 t
.lists
.members
.create(
1211 owner_screen_name
=owner
,
1212 screen_name
=user_name
)
1213 printNicely(green('Added.'))
1216 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1221 Remove specific user from a list
1223 owner
, slug
= get_slug()
1225 user_name
= raw_input(
1227 'Give me name of the unlucky one: ',
1229 if user_name
.startswith('@'):
1230 user_name
= user_name
[1:]
1232 t
.lists
.members
.destroy(
1234 owner_screen_name
=owner
,
1235 screen_name
=user_name
)
1236 printNicely(green('Gone.'))
1239 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1242 def list_subscribe(t
):
1246 owner
, slug
= get_slug()
1249 t
.lists
.subscribers
.create(
1251 owner_screen_name
=owner
)
1252 printNicely(green('Done.'))
1256 light_magenta('I\'m sorry you can not subscribe to this list.'))
1259 def list_unsubscribe(t
):
1263 owner
, slug
= get_slug()
1266 t
.lists
.subscribers
.destroy(
1268 owner_screen_name
=owner
)
1269 printNicely(green('Done.'))
1273 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1282 while next_cursor
!= 0:
1283 res
= t
.lists
.ownerships(
1284 screen_name
=g
['original_name'],
1287 next_cursor
= res
['next_cursor']
1291 printNicely(light_magenta('You own no lists :)'))
1298 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1301 'New list\'s mode (public/private): ',
1303 description
= raw_input(
1305 'New list\'s description: ',
1311 description
=description
)
1312 printNicely(green(name
+ ' list is created.'))
1315 printNicely(red('Oops something is wrong with Twitter :('))
1324 'Your list that you want to update: ',
1328 'Update name (leave blank to unchange): ',
1330 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1331 description
= raw_input(light_magenta('Update description: ', rl
=True))
1335 slug
='-'.join(slug
.split()),
1336 owner_screen_name
=g
['original_name'],
1339 description
=description
)
1343 owner_screen_name
=g
['original_name'],
1345 description
=description
)
1346 printNicely(green(slug
+ ' list is updated.'))
1349 printNicely(red('Oops something is wrong with Twitter :('))
1358 'Your list that you want to delete: ',
1362 slug
='-'.join(slug
.split()),
1363 owner_screen_name
=g
['original_name'])
1364 printNicely(green(slug
+ ' list is deleted.'))
1367 printNicely(red('Oops something is wrong with Twitter :('))
1374 t
= Twitter(auth
=authen())
1375 # List all lists or base on action
1377 g
['list_action'] = g
['stuff'].split()[0]
1384 'all_mem': list_members
,
1385 'all_sub': list_subscribers
,
1388 'sub': list_subscribe
,
1389 'unsub': list_unsubscribe
,
1392 'update': list_update
,
1396 return action_ary
[g
['list_action']](t
)
1398 printNicely(red('Please try again.'))
1406 target
= g
['stuff'].split()[0]
1408 args
= parse_arguments()
1410 if g
['stuff'].split()[-1] == '-f':
1411 guide
= 'To ignore an option, just hit Enter key.'
1412 printNicely(light_magenta(guide
))
1413 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1414 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1415 args
.filter = list(filter(None, only
.split(',')))
1416 args
.ignore
= list(filter(None, ignore
.split(',')))
1418 printNicely(red('Sorry, wrong format.'))
1421 g
['stream_stop'] = True
1423 stuff
= g
['stuff'].split()[1]
1428 'public': spawn_public_stream
,
1429 'list': spawn_list_stream
,
1430 'mine': spawn_personal_stream
,
1432 spawn_dict
.get(target
)(args
, stuff
)
1435 printNicely(red('Sorry I can\'t understand.'))
1440 Unix's command `cal`
1443 rel
= os
.popen('cal').read().split('\n')
1446 show_calendar(month
, date
, rel
)
1451 List and change theme
1455 for theme
in g
['themes']:
1456 line
= light_magenta(theme
)
1457 if c
['THEME'] == theme
:
1458 line
= ' ' * 2 + light_yellow('* ') + line
1460 line
= ' ' * 4 + line
1466 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1467 # Redefine decorated_name
1468 g
['decorated_name'] = lambda x
: color_func(
1469 c
['DECORATED_NAME'])(
1471 printNicely(green('Theme changed.'))
1473 printNicely(red('No such theme exists.'))
1478 Browse and change config
1480 all_config
= get_all_config()
1481 g
['stuff'] = g
['stuff'].strip()
1484 for k
in all_config
:
1486 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1488 guide
= 'Detailed explanation can be found at ' + \
1489 color_func(c
['TWEET']['link'])(
1490 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1492 # Print specific config
1493 elif len(g
['stuff'].split()) == 1:
1494 if g
['stuff'] in all_config
:
1497 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1500 printNicely(red('No such config key.'))
1501 # Print specific config's default value
1502 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1503 key
= g
['stuff'].split()[0]
1505 value
= get_default_config(key
)
1506 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1510 printNicely(red('Just can not get the default.'))
1511 # Delete specific config key in config file
1512 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1513 key
= g
['stuff'].split()[0]
1516 printNicely(green('Config key is dropped.'))
1519 printNicely(red('Just can not drop the key.'))
1520 # Set specific config
1521 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1522 key
= g
['stuff'].split()[0]
1523 value
= g
['stuff'].split()[-1]
1524 if key
== 'THEME' and not validate_theme(value
):
1525 printNicely(red('Invalid theme\'s value.'))
1528 set_config(key
, value
)
1529 # Keys that needs to be apply immediately
1531 c
['THEME'] = reload_theme(value
, c
['THEME'])
1532 g
['decorated_name'] = lambda x
: color_func(
1533 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1534 elif key
== 'PREFIX':
1535 g
['PREFIX'] = u2str(emojize(format_prefix(
1536 listname
=g
['listname'],
1537 keyword
=g
['keyword']
1540 printNicely(green('Updated successfully.'))
1543 printNicely(red('Just can not set the key.'))
1545 printNicely(light_magenta('Sorry I can\'t understand.'))
1548 def help_discover():
1553 # Discover the world
1555 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1556 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1557 'You can try ' + light_green('trend US') + ' or ' + \
1558 light_green('trend JP Tokyo') + '.\n'
1559 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1560 light_green('home 7') + ' will show 7 tweets.\n'
1561 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1562 light_green('me 2') + ' will show your last 2 tweets.\n'
1564 light_green('notification') + ' will show your recent notification.\n'
1565 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1566 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1567 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1568 magenta('@mdo') + '.\n'
1569 usage
+= s
* 2 + light_green('view @mdo') + \
1570 ' will show ' + magenta('@mdo') + '\'s home.\n'
1571 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1572 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1573 'Search can be performed with or without hashtag.\n'
1584 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1585 usage
+= s
* 2 + light_green('t oops ') + \
1586 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1588 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1589 light_yellow('[id=12]') + '.\n'
1591 light_green('quote 12 ') + ' will quote the tweet with ' + \
1592 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1593 'the quote will be canceled.\n'
1595 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1596 light_yellow('[id=12]') + '.\n'
1597 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1598 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1599 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1600 light_yellow('oops') + '" to the owner of the tweet with ' + \
1601 light_yellow('[id=12]') + '.\n'
1602 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1603 light_yellow('oops') + '" to all people in the tweet with ' + \
1604 light_yellow('[id=12]') + '.\n'
1606 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1607 light_yellow('[id=12]') + '.\n'
1609 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1610 light_yellow('[id=12]') + '.\n'
1612 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1613 light_yellow('[id=12]') + '.\n'
1615 light_green('del 12 ') + ' will delete tweet with ' + \
1616 light_yellow('[id=12]') + '.\n'
1617 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1618 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1619 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1620 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1621 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1622 light_yellow('[id=12]') + ' in your Pocket list.\n'
1626 def help_messages():
1633 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1634 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1635 light_green('inbox 7') + ' will show newest 7 messages.\n'
1636 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1637 light_yellow('[thread_id=2]') + '.\n'
1638 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1639 magenta('@dtvd88') + '.\n'
1640 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1641 light_yellow('[message_id=5]') + '.\n'
1645 def help_friends_and_followers():
1647 Friends and Followers
1650 # Follower and following
1652 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1654 light_green('ls fl') + \
1655 ' will list all followers (people who are following you).\n'
1657 light_green('ls fr') + \
1658 ' will list all friends (people who you are following).\n'
1659 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1660 magenta('@dtvd88') + '.\n'
1661 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1662 magenta('@dtvd88') + '.\n'
1663 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1664 magenta('@dtvd88') + '.\n'
1665 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1666 magenta('@dtvd88') + '.\n'
1667 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1668 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1669 magenta('@dtvd88') + '.\n'
1670 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1671 magenta('@dtvd88') + '.\n'
1672 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1673 magenta('@dtvd88') + ' as a spam account.\n'
1684 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1685 usage
+= s
* 2 + light_green('list') + \
1686 ' will show all lists you are belong to.\n'
1687 usage
+= s
* 2 + light_green('list home') + \
1688 ' will show timeline of list. You will be asked for list\'s name.\n'
1689 usage
+= s
* 2 + light_green('list all_mem') + \
1690 ' will show list\'s all members.\n'
1691 usage
+= s
* 2 + light_green('list all_sub') + \
1692 ' will show list\'s all subscribers.\n'
1693 usage
+= s
* 2 + light_green('list add') + \
1694 ' will add specific person to a list owned by you.' + \
1695 ' You will be asked for list\'s name and person\'s name.\n'
1696 usage
+= s
* 2 + light_green('list rm') + \
1697 ' will remove specific person from a list owned by you.' + \
1698 ' You will be asked for list\'s name and person\'s name.\n'
1699 usage
+= s
* 2 + light_green('list sub') + \
1700 ' will subscribe you to a specific list.\n'
1701 usage
+= s
* 2 + light_green('list unsub') + \
1702 ' will unsubscribe you from a specific list.\n'
1703 usage
+= s
* 2 + light_green('list own') + \
1704 ' will show all list owned by you.\n'
1705 usage
+= s
* 2 + light_green('list new') + \
1706 ' will create a new list.\n'
1707 usage
+= s
* 2 + light_green('list update') + \
1708 ' will update a list owned by you.\n'
1709 usage
+= s
* 2 + light_green('list del') + \
1710 ' will delete a list owned by you.\n'
1721 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1722 usage
+= s
* 2 + light_green('switch public #AKB') + \
1723 ' will switch to public stream and follow "' + \
1724 light_yellow('AKB') + '" keyword.\n'
1725 usage
+= s
* 2 + light_green('switch mine') + \
1726 ' will switch to your personal stream.\n'
1727 usage
+= s
* 2 + light_green('switch mine -f ') + \
1728 ' will prompt to enter the filter.\n'
1729 usage
+= s
* 3 + light_yellow('Only nicks') + \
1730 ' filter will decide nicks will be INCLUDE ONLY.\n'
1731 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1732 ' filter will decide nicks will be EXCLUDE.\n'
1733 usage
+= s
* 2 + light_green('switch list') + \
1734 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1743 h
, w
= os
.popen('stty size', 'r').read().split()
1746 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1747 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1748 usage
+= s
+ 'You are ' + \
1749 light_yellow('already') + ' on your personal stream.\n'
1750 usage
+= s
+ 'Any update from Twitter will show up ' + \
1751 light_yellow('immediately') + '.\n'
1752 usage
+= s
+ 'In addition, following commands are available right now:\n'
1753 # Twitter help section
1755 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1756 usage
+= s
* 2 + light_green('h discover') + \
1757 ' will show help for discover commands.\n'
1758 usage
+= s
* 2 + light_green('h tweets') + \
1759 ' will show help for tweets commands.\n'
1760 usage
+= s
* 2 + light_green('h messages') + \
1761 ' will show help for messages commands.\n'
1762 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1763 ' will show help for friends and followers commands.\n'
1764 usage
+= s
* 2 + light_green('h list') + \
1765 ' will show help for list commands.\n'
1766 usage
+= s
* 2 + light_green('h stream') + \
1767 ' will show help for stream commands.\n'
1770 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1771 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1772 'will be evaluate by Python interpreter.\n'
1773 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1774 ' for current month.\n'
1777 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1778 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1779 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1780 ' theme immediately.\n'
1781 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1783 light_green('config ASCII_ART') + ' will output current value of ' +\
1784 light_yellow('ASCII_ART') + ' config key.\n'
1786 light_green('config TREND_MAX default') + ' will output default value of ' + \
1787 light_yellow('TREND_MAX') + ' config key.\n'
1789 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1790 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1792 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1793 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1794 light_yellow('True') + '.\n'
1797 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1798 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1799 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1800 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1801 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1802 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1803 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1806 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1807 usage
+= s
+ 'Have fun and hang tight! \n'
1810 'discover': help_discover
,
1811 'tweets': help_tweets
,
1812 'messages': help_messages
,
1813 'friends_and_followers': help_friends_and_followers
,
1815 'stream': help_stream
,
1820 lambda: printNicely(red('No such command.'))
1828 Pause stream display
1831 printNicely(green('Stream is paused'))
1839 printNicely(green('Stream is running back now'))
1855 printNicely(green('See you next time :)'))
1863 Reset prefix of line
1866 if c
.get('USER_JSON_ERROR'):
1867 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1868 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1870 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1873 printNicely(str(eval(g
['cmd'])))
1928 # Handle function set
1983 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1988 Listen to user's input
1993 ['public', 'mine', 'list'], # switch
2002 [], # view_my_tweets
2013 ['image'], # show image
2015 ['fl', 'fr'], # list
2017 [i
for i
in g
['message_threads']], # sent
2042 [key
for key
in dict(get_all_config())], # config
2043 g
['themes'], # theme
2048 'friends_and_followers',
2060 init_interactive_shell(d
)
2067 # Only use PREFIX as a string with raw_input
2068 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2071 # Save cmd to compare with readline buffer
2072 g
['cmd'] = line
.strip()
2073 # Get short cmd to pass to handle function
2075 cmd
= line
.split()[0]
2078 # Lock the semaphore
2080 # Save cmd to global variable and call process
2081 g
['stuff'] = ' '.join(line
.split()[1:])
2082 # Check tweet length
2083 # Process the command
2086 if cmd
in ['switch', 't', 'rt', 'rep']:
2092 except TwitterHTTPError
as e
:
2093 detail_twitter_error(e
)
2096 printNicely(red('OMG something is wrong with Twitter API right now.'))
2098 # Release the semaphore lock
2102 def reconn_notice():
2104 Notice when Hangup or Timeout
2106 guide
= light_magenta('You can use ') + \
2107 light_green('switch') + \
2108 light_magenta(' command to return to your stream.\n')
2109 guide
+= light_magenta('Type ') + \
2110 light_green('h stream') + \
2111 light_magenta(' for more details.')
2113 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2117 def stream(domain
, args
, name
='Rainbow Stream'):
2123 c
['USER_DOMAIN']: name
,
2124 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2125 c
['SITE_DOMAIN']: name
,
2128 ascii_art(art_dict
.get(domain
, name
))
2129 # These arguments are optional:
2131 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2133 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2136 if args
.track_keywords
:
2137 query_args
['track'] = args
.track_keywords
2139 stream
= TwitterStream(
2144 if domain
== c
['USER_DOMAIN']:
2145 tweet_iter
= stream
.user(**query_args
)
2146 elif domain
== c
['SITE_DOMAIN']:
2147 tweet_iter
= stream
.site(**query_args
)
2149 if args
.track_keywords
:
2150 tweet_iter
= stream
.statuses
.filter(**query_args
)
2152 tweet_iter
= stream
.statuses
.sample()
2153 # Block new stream until other one exits
2154 StreamLock
.acquire()
2155 g
['stream_stop'] = False
2156 last_tweet_time
= time
.time()
2157 for tweet
in tweet_iter
:
2159 printNicely('-- None --')
2160 elif tweet
is Timeout
:
2161 # Because the stream check for each 0.3s
2162 # so we shouldn't output anything here
2163 if(g
['stream_stop']):
2164 StreamLock
.release()
2166 elif tweet
is HeartbeatTimeout
:
2167 printNicely('-- Heartbeat Timeout --')
2169 StreamLock
.release()
2171 elif tweet
is Hangup
:
2172 printNicely('-- Hangup --')
2174 StreamLock
.release()
2176 elif tweet
.get('text'):
2177 # Slow down the stream by STREAM_DELAY config key
2178 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2180 last_tweet_time
= time
.time()
2181 # Check the semaphore pause and lock (stream process only)
2189 keyword
=args
.track_keywords
,
2194 # Current readline buffer
2195 current_buffer
= readline
.get_line_buffer().strip()
2196 # There is an unexpected behaviour in MacOSX readline + Python 2:
2197 # after completely delete a word after typing it,
2198 # somehow readline buffer still contains
2199 # the 1st character of that word
2200 if current_buffer
and g
['cmd'] != current_buffer
:
2202 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2204 elif not c
['HIDE_PROMPT']:
2205 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2207 elif tweet
.get('direct_message'):
2208 # Check the semaphore pause and lock (stream process only)
2213 print_message(tweet
['direct_message'])
2214 elif tweet
.get('event'):
2215 c
['events'].append(tweet
)
2217 except TwitterHTTPError
as e
:
2220 magenta('We have connection problem with twitter stream API right now :('))
2221 detail_twitter_error(e
)
2222 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2226 magenta('There seems to be a connection problem.'))
2231 def spawn_public_stream(args
, keyword
=None):
2233 Spawn a new public stream
2235 # Only set keyword if specified
2237 if keyword
[0] == '#':
2238 keyword
= keyword
[1:]
2239 args
.track_keywords
= keyword
2240 g
['keyword'] = keyword
2242 g
['keyword'] = 'Global'
2243 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2246 th
= threading
.Thread(
2255 def spawn_list_stream(args
, stuff
=None):
2257 Spawn a new list stream
2260 owner
, slug
= check_slug(stuff
)
2262 owner
, slug
= get_slug()
2264 # Force python 2 not redraw readline buffer
2265 listname
= '/'.join([owner
, slug
])
2266 # Set the listname variable
2267 # and reset tracked keyword
2268 g
['listname'] = listname
2270 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2271 listname
=g
['listname']
2273 printNicely(light_yellow('getting list members ...'))
2275 t
= Twitter(auth
=authen())
2278 while next_cursor
!= 0:
2279 m
= t
.lists
.members(
2281 owner_screen_name
=owner
,
2283 include_entities
=False)
2284 for u
in m
['users']:
2285 members
.append('@' + u
['screen_name'])
2286 next_cursor
= m
['next_cursor']
2287 printNicely(light_yellow('... done.'))
2288 # Build thread filter array
2289 args
.filter = members
2291 th
= threading
.Thread(
2301 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2303 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2307 def spawn_personal_stream(args
, stuff
=None):
2309 Spawn a new personal stream
2311 # Reset the tracked keyword and listname
2312 g
['keyword'] = g
['listname'] = ''
2314 g
['PREFIX'] = u2str(emojize(format_prefix()))
2316 th
= threading
.Thread(
2321 g
['original_name']))
2331 args
= parse_arguments()
2335 # Twitter API connection problem
2336 except TwitterHTTPError
as e
:
2339 magenta('We have connection problem with twitter REST API right now :('))
2340 detail_twitter_error(e
)
2343 # Proxy connection problem
2344 except (socks
.ProxyConnectionError
, URLError
):
2346 magenta('There seems to be a connection problem.'))
2348 magenta('You might want to check your proxy settings (host, port and type)!'))
2352 # Spawn stream thread
2353 target
= args
.stream
.split()[0]
2354 if target
== 'mine':
2355 spawn_personal_stream(args
)
2358 stuff
= args
.stream
.split()[1]
2362 'public': spawn_public_stream
,
2363 'list': spawn_list_stream
,
2365 spawn_dict
.get(target
)(args
, stuff
)
2367 # Start listen process