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).')
95 default
=os
.environ
.get('HOME', os
.environ
.get('USERPROFILE', '')) + os
.sep
+ '.rainbow_oauth',
96 help='Specify which OAuth profile to use for twitter. Default: ~/.rainbow_oauth.')
100 default
=os
.environ
.get('HOME', os
.environ
.get('USERPROFILE', '')) + os
.sep
+ '.rainbow_pckt_oauth',
101 help='Specify which OAuth profile to use for pocket. Default: ~/.rainbow_pckt_oauth.')
102 return parser
.parse_args()
105 def proxy_connect(args
):
107 Connect to specified proxy
110 # Setup proxy by monkeypatching the standard lib
111 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
112 socks
.set_default_proxy(
113 socks
.SOCKS5
, args
.proxy_host
,
114 int(args
.proxy_port
))
115 elif args
.proxy_type
.lower() == "http":
116 socks
.set_default_proxy(
117 socks
.HTTP
, args
.proxy_host
,
118 int(args
.proxy_port
))
119 elif args
.proxy_type
.lower() == "socks4":
120 socks
.set_default_proxy(
121 socks
.SOCKS4
, args
.proxy_host
,
122 int(args
.proxy_port
))
125 magenta('Sorry, wrong proxy type specified! Aborting...'))
127 socket
.socket
= socks
.socksocket
132 Authenticate with Twitter OAuth
134 # When using rainbow stream you must authorize.
135 twitter_credential
= g
['twitter_oauth_path']
136 if not os
.path
.exists(twitter_credential
):
137 oauth_dance('Rainbow Stream',
141 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
151 Authenticate with Pocket OAuth
153 pocket_credential
= g
['pocket_oauth_path']
154 if not os
.path
.exists(pocket_credential
):
155 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
156 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
157 webbrowser
.open(auth_url
)
158 printNicely(green("*** Press [ENTER] after authorization ***"))
160 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
161 access_token
= user_credentials
['access_token']
162 f
= open(pocket_credential
, 'w')
163 f
.write(access_token
)
166 with
open(pocket_credential
, 'r') as f
:
167 access_token
= str(f
.readlines()[0])
170 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
173 def build_mute_dict(dict_data
=False):
177 t
= Twitter(auth
=authen())
180 screen_name_list
= []
183 while next_cursor
!= 0:
184 list = t
.mutes
.users
.list(
185 screen_name
=g
['original_name'],
188 include_entities
=False,
190 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
191 name_list
+= [u
['name'] for u
in list['users']]
192 next_cursor
= list['next_cursor']
193 # Return dict or list
195 return dict(zip(screen_name_list
, name_list
))
197 return screen_name_list
202 Save traceback when run in debug mode
205 g
['traceback'].append(traceback
.format_exc())
208 def upgrade_center():
210 Check latest and notify to upgrade
213 current
= pkg_resources
.get_distribution('rainbowstream').version
214 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
215 readme
= requests
.get(url
).text
216 latest
= readme
.split('version = \'')[1].split('\'')[0]
217 g
['using_latest'] = current
== latest
218 if not g
['using_latest']:
219 notice
= light_magenta('RainbowStream latest version is ')
220 notice
+= light_green(latest
)
221 notice
+= light_magenta(' while your current version is ')
222 notice
+= light_yellow(current
) + '\n'
223 notice
+= light_magenta('You should upgrade with ')
224 notice
+= light_green('pip install -U rainbowstream')
226 notice
= light_yellow('You are running latest version (')
227 notice
+= light_green(current
)
228 notice
+= light_yellow(')')
240 ctrl_c_handler
= lambda signum
, frame
: quit()
241 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
242 # Set OAuth file path (needs to happen before authen is called)
243 g
['twitter_oauth_path'] = args
.twitter_auth
244 g
['pocket_oauth_path'] = args
.pocket_auth
248 t
= Twitter(auth
=authen())
249 credential
= t
.account
.verify_credentials()
250 screen_name
= '@' + credential
['screen_name']
251 name
= credential
['name']
252 c
['original_name'] = g
['original_name'] = screen_name
[1:]
253 g
['listname'] = g
['keyword'] = ''
254 g
['PREFIX'] = u2str(emojize(format_prefix()))
255 g
['full_name'] = name
256 g
['decorated_name'] = lambda x
: color_func(
257 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
259 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
260 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
263 g
['message_threads'] = {}
266 # Debug option default = True
273 # Init tweet dict and message dict
275 c
['message_dict'] = []
277 c
['IMAGE_ON_TERM'] = args
.image_on_term
279 c
['24BIT'] = args
.color_24bit
280 # Check type of ONLY_LIST and IGNORE_LIST
281 if not isinstance(c
['ONLY_LIST'], list):
282 printNicely(red('ONLY_LIST is not a valid list value.'))
284 if not isinstance(c
['IGNORE_LIST'], list):
285 printNicely(red('IGNORE_LIST is not a valid list value.'))
286 c
['IGNORE_LIST'] = []
288 c
['IGNORE_LIST'] += build_mute_dict()
290 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
297 t
= Twitter(auth
=authen())
298 # Get country and town
300 country
= g
['stuff'].split()[0]
304 town
= g
['stuff'].split()[1]
307 avail
= t
.trends
.available()
310 trends
= t
.trends
.place(_id
=1)[0]['trends']
313 for location
in avail
:
314 # Search for country and Town
316 if location
['countryCode'] == country \
317 and location
['placeType']['name'] == 'Town' \
318 and location
['name'] == town
:
319 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
321 # Search for country only
323 if location
['countryCode'] == country \
324 and location
['placeType']['name'] == 'Country':
325 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
333 t
= Twitter(auth
=authen())
334 num
= c
['HOME_TWEET_NUM']
335 if g
['stuff'].isdigit():
336 num
= int(g
['stuff'])
337 kwargs
= {'count': num
}
338 kwargs
= add_tweetmode_parameter(kwargs
)
339 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
349 for e
in c
['events']:
353 printNicely(magenta('Nothing at this time.'))
360 t
= Twitter(auth
=authen())
361 num
= c
['HOME_TWEET_NUM']
362 if g
['stuff'].isdigit():
363 num
= int(g
['stuff'])
364 kwargs
= {'count': num
}
365 kwargs
= add_tweetmode_parameter(kwargs
)
366 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
373 Show profile of a specific user
375 t
= Twitter(auth
=authen())
377 screen_name
= g
['stuff'].split()[0]
379 printNicely(red('Sorry I can\'t understand.'))
381 if screen_name
.startswith('@'):
384 screen_name
=screen_name
[1:],
385 include_entities
=False)
389 printNicely(red('No user.'))
391 printNicely(red('A name should begin with a \'@\''))
398 t
= Twitter(auth
=authen())
400 user
= g
['stuff'].split()[0]
402 printNicely(red('Sorry I can\'t understand.'))
406 num
= int(g
['stuff'].split()[1])
408 num
= c
['HOME_TWEET_NUM']
409 kwargs
= {'count': num
, 'screen_name': user
[1:]}
410 kwargs
= add_tweetmode_parameter(kwargs
)
411 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
415 printNicely(red('A name should begin with a \'@\''))
418 def view_my_tweets():
420 Display user's recent tweets.
422 t
= Twitter(auth
=authen())
424 num
= int(g
['stuff'])
426 num
= c
['HOME_TWEET_NUM']
427 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
428 kwargs
= add_tweetmode_parameter(kwargs
)
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 kwargs
= add_tweetmode_parameter(kwargs
)
457 rel
= t
.search
.tweets(**kwargs
)['statuses']
460 printNicely('Newest tweets:')
461 for i
in reversed(xrange(count
)):
462 draw(t
=rel
[i
], keyword
=query
)
465 printNicely(magenta('I\'m afraid there is no result'))
472 t
= Twitter(auth
=authen())
473 t
.statuses
.update(status
=g
['stuff'])
478 Add new link to Pocket along with tweet id
480 if not c
['POCKET_SUPPORT']:
481 printNicely(yellow('Pocket isn\'t enabled.'))
482 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
488 t
= Twitter(auth
=authen())
490 id = int(g
['stuff'].split()[0])
491 tid
= c
['tweet_dict'][id]
493 printNicely(red('Sorry I can\'t understand.'))
496 tweet
= t
.statuses
.show(id=tid
)
498 if len(tweet
['entities']['urls']) > 0:
499 url
= tweet
['entities']['urls'][0]['expanded_url']
501 url
= "https://twitter.com/" + \
502 tweet
['user']['screen_name'] + '/status/' + str(tid
)
506 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
510 printNicely(red('Something is wrong about your Pocket account,'+ \
511 ' please restart Rainbowstream.'))
512 pocket_credential
= os
.environ
.get(
516 '')) + os
.sep
+ '.rainbow_pckt_oauth'
517 if os
.path
.exists(pocket_credential
):
518 os
.remove(pocket_credential
)
521 printNicely(green('Pocketed !'))
529 t
= Twitter(auth
=authen())
531 id = int(g
['stuff'].split()[0])
533 printNicely(red('Sorry I can\'t understand.'))
535 tid
= c
['tweet_dict'][id]
536 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
544 t
= Twitter(auth
=authen())
546 id = int(g
['stuff'].split()[0])
548 printNicely(red('Sorry I can\'t understand.'))
550 tid
= c
['tweet_dict'][id]
552 kwargs
= add_tweetmode_parameter(kwargs
)
553 tweet
= t
.statuses
.show(**kwargs
)
555 formater
= format_quote(tweet
)
559 prefix
= light_magenta('Compose your ', rl
=True) + \
560 light_green('#comment: ', rl
=True)
561 comment
= raw_input(prefix
)
563 quote
= comment
.join(formater
.split('#comment'))
564 t
.statuses
.update(status
=quote
)
566 printNicely(light_magenta('No text added.'))
573 t
= Twitter(auth
=authen())
576 id = int(g
['stuff'].split()[0])
578 printNicely(red('Sorry I can\'t understand.'))
580 tid
= c
['tweet_dict'][id]
581 # Get display num if exist
583 num
= int(g
['stuff'].split()[1])
585 num
= c
['RETWEETS_SHOW_NUM']
586 # Get result and display
587 kwargs
= {'id': tid
, 'count': num
}
588 kwargs
= add_tweetmode_parameter(kwargs
)
589 rt_ary
= t
.statuses
.retweets(**kwargs
)
591 printNicely(magenta('This tweet has no retweet.'))
593 for tweet
in reversed(rt_ary
):
602 t
= Twitter(auth
=authen())
604 id = int(g
['stuff'].split()[0])
606 printNicely(red('Sorry I can\'t understand.'))
608 tid
= c
['tweet_dict'][id]
610 kwargs
= add_tweetmode_parameter(kwargs
)
611 tweet
= t
.statuses
.show(**kwargs
)
612 limit
= c
['CONVERSATION_MAX']
614 thread_ref
.append(tweet
)
615 prev_tid
= tweet
['in_reply_to_status_id']
616 while prev_tid
and limit
:
618 kwargs
['id'] = prev_tid
619 tweet
= t
.statuses
.show(**kwargs
)
620 prev_tid
= tweet
['in_reply_to_status_id']
621 thread_ref
.append(tweet
)
623 for tweet
in reversed(thread_ref
):
632 t
= Twitter(auth
=authen())
634 id = int(g
['stuff'].split()[0])
636 printNicely(red('Sorry I can\'t understand.'))
638 tid
= c
['tweet_dict'][id]
639 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
640 status
= ' '.join(g
['stuff'].split()[1:])
641 # don't include own username for tweet chains
642 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
643 if user
== g
['original_name']:
644 status
= str2u(status
)
646 status
= '@' + user
+ ' ' + str2u(status
)
647 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
654 t
= Twitter(auth
=authen())
656 id = int(g
['stuff'].split()[0])
658 printNicely(red('Sorry I can\'t understand.'))
660 tid
= c
['tweet_dict'][id]
661 original_tweet
= t
.statuses
.show(id=tid
)
662 text
= original_tweet
['text']
663 nick_ary
= [original_tweet
['user']['screen_name']]
664 for user
in list(original_tweet
['entities']['user_mentions']):
665 if user
['screen_name'] not in nick_ary \
666 and user
['screen_name'] != g
['original_name']:
667 nick_ary
.append(user
['screen_name'])
668 status
= ' '.join(g
['stuff'].split()[1:])
669 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
670 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
677 t
= Twitter(auth
=authen())
679 id = int(g
['stuff'].split()[0])
681 printNicely(red('Sorry I can\'t understand.'))
683 tid
= c
['tweet_dict'][id]
684 t
.favorites
.create(_id
=tid
, include_entities
=False)
685 printNicely(green('Favorited.'))
687 kwargs
= add_tweetmode_parameter(kwargs
)
688 draw(t
.statuses
.show(**kwargs
))
696 t
= Twitter(auth
=authen())
698 id = int(g
['stuff'].split()[0])
700 printNicely(red('Sorry I can\'t understand.'))
702 tid
= c
['tweet_dict'][id]
703 t
.favorites
.destroy(_id
=tid
)
704 printNicely(green('Okay it\'s unfavorited.'))
706 kwargs
= add_tweetmode_parameter(kwargs
)
707 draw(t
.statuses
.show(**kwargs
))
713 Copy url of a tweet to clipboard
715 t
= Twitter(auth
=authen())
717 id = int(g
['stuff'].split()[0])
718 tid
= c
['tweet_dict'][id]
720 printNicely(red('Tweet id is not valid.'))
723 kwargs
= add_tweetmode_parameter(kwargs
)
724 tweet
= t
.statuses
.show(**kwargs
)
725 url
= 'https://twitter.com/' + \
726 tweet
['user']['screen_name'] + '/status/' + str(tid
)
728 if platform
.system().lower() == 'darwin':
729 os
.system("echo '%s' | pbcopy" % url
)
730 printNicely(green('Copied tweet\'s url to clipboard.'))
732 printNicely('Direct link: ' + yellow(url
))
739 t
= Twitter(auth
=authen())
741 id = int(g
['stuff'].split()[0])
743 printNicely(red('Sorry I can\'t understand.'))
745 tid
= c
['tweet_dict'][id]
746 t
.statuses
.destroy(id=tid
)
747 printNicely(green('Okay it\'s gone.'))
754 t
= Twitter(auth
=authen())
756 target
= g
['stuff'].split()[0]
757 if target
!= 'image':
759 id = int(g
['stuff'].split()[1])
760 tid
= c
['tweet_dict'][id]
761 tweet
= t
.statuses
.show(id=tid
)
762 media
= tweet
['entities']['media']
764 res
= requests
.get(m
['media_url'])
765 img
= Image
.open(BytesIO(res
.content
))
769 printNicely(red('Sorry I can\'t show this image.'))
776 t
= Twitter(auth
=authen())
778 if not g
['stuff'].isdigit():
780 tid
= c
['tweet_dict'][int(g
['stuff'])]
781 tweet
= t
.statuses
.show(id=tid
)
782 urls
= tweet
['entities']['urls']
784 printNicely(light_magenta('No url here @.@!'))
788 expanded_url
= url
['expanded_url']
789 webbrowser
.open(expanded_url
)
792 printNicely(red('Sorry I can\'t open url in this tweet.'))
799 t
= Twitter(auth
=authen())
800 num
= c
['MESSAGES_DISPLAY']
801 if g
['stuff'].isdigit():
807 inbox
= inbox
+ t
.direct_messages(
810 include_entities
=False,
815 inbox
= inbox
+ t
.direct_messages(
818 include_entities
=False,
822 num
= c
['MESSAGES_DISPLAY']
823 if g
['stuff'].isdigit():
828 sent
= sent
+ t
.direct_messages
.sent(
831 include_entities
=False,
836 sent
= sent
+ t
.direct_messages
.sent(
839 include_entities
=False,
844 uniq_inbox
= list(set(
845 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
847 uniq_sent
= list(set(
848 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
850 for partner
in uniq_inbox
:
851 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
853 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
854 d
[partner
] = inbox_ary
+ sent_ary
855 for partner
in uniq_sent
:
858 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
859 g
['message_threads'] = print_threads(d
)
864 View a thread of message
867 thread_id
= int(g
['stuff'])
869 g
['message_threads'][thread_id
],
874 printNicely(red('No such thread.'))
879 Send a direct message
881 t
= Twitter(auth
=authen())
883 user
= g
['stuff'].split()[0]
884 if user
[0].startswith('@'):
885 content
= ' '.join(g
['stuff'].split()[1:])
886 t
.direct_messages
.new(
887 screen_name
=user
[1:],
890 printNicely(green('Message sent.'))
892 printNicely(red('A name should begin with a \'@\''))
895 printNicely(red('Sorry I can\'t understand.'))
902 t
= Twitter(auth
=authen())
904 id = int(g
['stuff'].split()[0])
906 printNicely(red('Sorry I can\'t understand.'))
907 mid
= c
['message_dict'][id]
908 t
.direct_messages
.destroy(id=mid
)
909 printNicely(green('Message deleted.'))
914 List friends for followers
916 t
= Twitter(auth
=authen())
919 name
= g
['stuff'].split()[1]
920 if name
.startswith('@'):
923 printNicely(red('A name should begin with a \'@\''))
924 raise Exception('Invalid name')
926 name
= g
['original_name']
927 # Get list followers or friends
929 target
= g
['stuff'].split()[0]
931 printNicely(red('Omg some syntax is wrong.'))
934 d
= {'fl': 'followers', 'fr': 'friends'}
938 printNicely('All ' + d
[target
] + ':')
942 while next_cursor
!= 0:
944 list = getattr(t
, d
[target
]).list(
948 include_entities
=False,
951 for u
in list['users']:
957 + cycle_color( u
['name'] ) \
958 + color_func(c
['TWEET']['nick'])( ' @' \
962 next_cursor
= list['next_cursor']
964 # 300 users means 15 calls to the related API. The rate limit is 15
965 # calls per 15mn periods (see Twitter documentation).
966 if ( number_of_users
% 300 == 0 ):
967 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
968 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
971 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
977 t
= Twitter(auth
=authen())
978 screen_name
= g
['stuff'].split()[0]
979 if screen_name
.startswith('@'):
980 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
981 printNicely(green('You are following ' + screen_name
+ ' now!'))
983 printNicely(red('A name should begin with a \'@\''))
990 t
= Twitter(auth
=authen())
991 screen_name
= g
['stuff'].split()[0]
992 if screen_name
.startswith('@'):
993 t
.friendships
.destroy(
994 screen_name
=screen_name
[1:],
995 include_entities
=False)
996 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
998 printNicely(red('A name should begin with a \'@\''))
1005 t
= Twitter(auth
=authen())
1007 screen_name
= g
['stuff'].split()[0]
1009 printNicely(red('A name should be specified. '))
1011 if screen_name
.startswith('@'):
1013 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1014 if isinstance(rel
, dict):
1015 printNicely(green(screen_name
+ ' is muted.'))
1016 c
['IGNORE_LIST'] += [screen_name
]
1017 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1019 printNicely(red(rel
))
1022 printNicely(red('Something is wrong, can not mute now :('))
1024 printNicely(red('A name should begin with a \'@\''))
1031 t
= Twitter(auth
=authen())
1033 screen_name
= g
['stuff'].split()[0]
1035 printNicely(red('A name should be specified. '))
1037 if screen_name
.startswith('@'):
1039 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1040 if isinstance(rel
, dict):
1041 printNicely(green(screen_name
+ ' is unmuted.'))
1042 c
['IGNORE_LIST'].remove(screen_name
)
1044 printNicely(red(rel
))
1046 printNicely(red('Maybe you are not muting this person ?'))
1048 printNicely(red('A name should begin with a \'@\''))
1055 # Get dict of muting users
1056 md
= build_mute_dict(dict_data
=True)
1057 printNicely('All: ' + str(len(md
)) + ' people.')
1059 user
= ' ' + cycle_color(md
[name
])
1060 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1062 # Update from Twitter
1063 c
['IGNORE_LIST'] = [n
for n
in md
]
1070 t
= Twitter(auth
=authen())
1071 screen_name
= g
['stuff'].split()[0]
1072 if screen_name
.startswith('@'):
1074 screen_name
=screen_name
[1:],
1075 include_entities
=False,
1077 printNicely(green('You blocked ' + screen_name
+ '.'))
1079 printNicely(red('A name should begin with a \'@\''))
1086 t
= Twitter(auth
=authen())
1087 screen_name
= g
['stuff'].split()[0]
1088 if screen_name
.startswith('@'):
1090 screen_name
=screen_name
[1:],
1091 include_entities
=False,
1093 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1095 printNicely(red('A name should begin with a \'@\''))
1100 Report a user as a spam account
1102 t
= Twitter(auth
=authen())
1103 screen_name
= g
['stuff'].split()[0]
1104 if screen_name
.startswith('@'):
1105 t
.users
.report_spam(
1106 screen_name
=screen_name
[1:])
1107 printNicely(green('You reported ' + screen_name
+ '.'))
1109 printNicely(red('Sorry I can\'t understand.'))
1117 list_name
= raw_input(
1118 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1119 # Get list name and owner
1121 owner
, slug
= list_name
.split('/')
1122 if slug
.startswith('@'):
1127 light_magenta('List name should follow "@owner/list_name" format.'))
1128 raise Exception('Wrong list name')
1131 def check_slug(list_name
):
1135 # Get list name and owner
1137 owner
, slug
= list_name
.split('/')
1138 if slug
.startswith('@'):
1143 light_magenta('List name should follow "@owner/list_name" format.'))
1144 raise Exception('Wrong list name')
1151 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1155 printNicely(light_magenta('You belong to no lists :)'))
1162 owner
, slug
= get_slug()
1163 res
= t
.lists
.statuses(
1165 owner_screen_name
=owner
,
1166 count
=c
['LIST_MAX'],
1167 include_entities
=False)
1168 for tweet
in reversed(res
):
1173 def list_members(t
):
1177 owner
, slug
= get_slug()
1181 while next_cursor
!= 0:
1182 m
= t
.lists
.members(
1184 owner_screen_name
=owner
,
1186 include_entities
=False)
1187 for u
in m
['users']:
1188 rel
[u
['name']] = '@' + u
['screen_name']
1189 next_cursor
= m
['next_cursor']
1190 printNicely('All: ' + str(len(rel
)) + ' members.')
1192 user
= ' ' + cycle_color(name
)
1193 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1197 def list_subscribers(t
):
1201 owner
, slug
= get_slug()
1205 while next_cursor
!= 0:
1206 m
= t
.lists
.subscribers(
1208 owner_screen_name
=owner
,
1210 include_entities
=False)
1211 for u
in m
['users']:
1212 rel
[u
['name']] = '@' + u
['screen_name']
1213 next_cursor
= m
['next_cursor']
1214 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1216 user
= ' ' + cycle_color(name
)
1217 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1223 Add specific user to a list
1225 owner
, slug
= get_slug()
1227 user_name
= raw_input(
1229 'Give me name of the newbie: ',
1231 if user_name
.startswith('@'):
1232 user_name
= user_name
[1:]
1234 t
.lists
.members
.create(
1236 owner_screen_name
=owner
,
1237 screen_name
=user_name
)
1238 printNicely(green('Added.'))
1241 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1246 Remove specific user from a list
1248 owner
, slug
= get_slug()
1250 user_name
= raw_input(
1252 'Give me name of the unlucky one: ',
1254 if user_name
.startswith('@'):
1255 user_name
= user_name
[1:]
1257 t
.lists
.members
.destroy(
1259 owner_screen_name
=owner
,
1260 screen_name
=user_name
)
1261 printNicely(green('Gone.'))
1264 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1267 def list_subscribe(t
):
1271 owner
, slug
= get_slug()
1274 t
.lists
.subscribers
.create(
1276 owner_screen_name
=owner
)
1277 printNicely(green('Done.'))
1281 light_magenta('I\'m sorry you can not subscribe to this list.'))
1284 def list_unsubscribe(t
):
1288 owner
, slug
= get_slug()
1291 t
.lists
.subscribers
.destroy(
1293 owner_screen_name
=owner
)
1294 printNicely(green('Done.'))
1298 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1307 while next_cursor
!= 0:
1308 res
= t
.lists
.ownerships(
1309 screen_name
=g
['original_name'],
1312 next_cursor
= res
['next_cursor']
1316 printNicely(light_magenta('You own no lists :)'))
1323 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1326 'New list\'s mode (public/private): ',
1328 description
= raw_input(
1330 'New list\'s description: ',
1336 description
=description
)
1337 printNicely(green(name
+ ' list is created.'))
1340 printNicely(red('Oops something is wrong with Twitter :('))
1349 'Your list that you want to update: ',
1353 'Update name (leave blank to unchange): ',
1355 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1356 description
= raw_input(light_magenta('Update description: ', rl
=True))
1360 slug
='-'.join(slug
.split()),
1361 owner_screen_name
=g
['original_name'],
1364 description
=description
)
1368 owner_screen_name
=g
['original_name'],
1370 description
=description
)
1371 printNicely(green(slug
+ ' list is updated.'))
1374 printNicely(red('Oops something is wrong with Twitter :('))
1383 'Your list that you want to delete: ',
1387 slug
='-'.join(slug
.split()),
1388 owner_screen_name
=g
['original_name'])
1389 printNicely(green(slug
+ ' list is deleted.'))
1392 printNicely(red('Oops something is wrong with Twitter :('))
1399 t
= Twitter(auth
=authen())
1400 # List all lists or base on action
1402 g
['list_action'] = g
['stuff'].split()[0]
1409 'all_mem': list_members
,
1410 'all_sub': list_subscribers
,
1413 'sub': list_subscribe
,
1414 'unsub': list_unsubscribe
,
1417 'update': list_update
,
1421 return action_ary
[g
['list_action']](t
)
1423 printNicely(red('Please try again.'))
1431 target
= g
['stuff'].split()[0]
1433 args
= parse_arguments()
1435 if g
['stuff'].split()[-1] == '-f':
1436 guide
= 'To ignore an option, just hit Enter key.'
1437 printNicely(light_magenta(guide
))
1438 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1439 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1440 args
.filter = list(filter(None, only
.split(',')))
1441 args
.ignore
= list(filter(None, ignore
.split(',')))
1443 printNicely(red('Sorry, wrong format.'))
1446 g
['stream_stop'] = True
1448 stuff
= g
['stuff'].split()[1]
1453 'public': spawn_public_stream
,
1454 'list': spawn_list_stream
,
1455 'mine': spawn_personal_stream
,
1457 spawn_dict
.get(target
)(args
, stuff
)
1460 printNicely(red('Sorry I can\'t understand.'))
1465 Unix's command `cal`
1468 rel
= os
.popen('cal').read().split('\n')
1471 show_calendar(month
, date
, rel
)
1476 List and change theme
1480 for theme
in g
['themes']:
1481 line
= light_magenta(theme
)
1482 if c
['THEME'] == theme
:
1483 line
= ' ' * 2 + light_yellow('* ') + line
1485 line
= ' ' * 4 + line
1491 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1492 # Redefine decorated_name
1493 g
['decorated_name'] = lambda x
: color_func(
1494 c
['DECORATED_NAME'])(
1496 printNicely(green('Theme changed.'))
1498 printNicely(red('No such theme exists.'))
1503 Browse and change config
1505 all_config
= get_all_config()
1506 g
['stuff'] = g
['stuff'].strip()
1509 for k
in all_config
:
1511 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1513 guide
= 'Detailed explanation can be found at ' + \
1514 color_func(c
['TWEET']['link'])(
1515 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1517 # Print specific config
1518 elif len(g
['stuff'].split()) == 1:
1519 if g
['stuff'] in all_config
:
1522 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1525 printNicely(red('No such config key.'))
1526 # Print specific config's default value
1527 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1528 key
= g
['stuff'].split()[0]
1530 value
= get_default_config(key
)
1531 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1535 printNicely(red('Just can not get the default.'))
1536 # Delete specific config key in config file
1537 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1538 key
= g
['stuff'].split()[0]
1541 printNicely(green('Config key is dropped.'))
1544 printNicely(red('Just can not drop the key.'))
1545 # Set specific config
1546 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1547 key
= g
['stuff'].split()[0]
1548 value
= g
['stuff'].split()[-1]
1549 if key
== 'THEME' and not validate_theme(value
):
1550 printNicely(red('Invalid theme\'s value.'))
1553 set_config(key
, value
)
1554 # Keys that needs to be apply immediately
1556 c
['THEME'] = reload_theme(value
, c
['THEME'])
1557 g
['decorated_name'] = lambda x
: color_func(
1558 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1559 elif key
== 'PREFIX':
1560 g
['PREFIX'] = u2str(emojize(format_prefix(
1561 listname
=g
['listname'],
1562 keyword
=g
['keyword']
1565 printNicely(green('Updated successfully.'))
1568 printNicely(red('Just can not set the key.'))
1570 printNicely(light_magenta('Sorry I can\'t understand.'))
1573 def help_discover():
1578 # Discover the world
1580 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1581 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1582 'You can try ' + light_green('trend US') + ' or ' + \
1583 light_green('trend JP Tokyo') + '.\n'
1584 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1585 light_green('home 7') + ' will show 7 tweets.\n'
1586 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1587 light_green('me 2') + ' will show your last 2 tweets.\n'
1589 light_green('notification') + ' will show your recent notification.\n'
1590 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1591 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1592 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1593 magenta('@mdo') + '.\n'
1594 usage
+= s
* 2 + light_green('view @mdo') + \
1595 ' will show ' + magenta('@mdo') + '\'s home.\n'
1596 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1597 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1598 'Search can be performed with or without hashtag.\n'
1609 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1610 usage
+= s
* 2 + light_green('t oops ') + \
1611 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1613 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1614 light_yellow('[id=12]') + '.\n'
1616 light_green('quote 12 ') + ' will quote the tweet with ' + \
1617 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1618 'the quote will be canceled.\n'
1620 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1621 light_yellow('[id=12]') + '.\n'
1622 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1623 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1624 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1625 light_yellow('oops') + '" to the owner of the tweet with ' + \
1626 light_yellow('[id=12]') + '.\n'
1627 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1628 light_yellow('oops') + '" to all people in the tweet with ' + \
1629 light_yellow('[id=12]') + '.\n'
1631 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1632 light_yellow('[id=12]') + '.\n'
1634 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1635 light_yellow('[id=12]') + '.\n'
1637 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1638 light_yellow('[id=12]') + '.\n'
1640 light_green('del 12 ') + ' will delete tweet with ' + \
1641 light_yellow('[id=12]') + '.\n'
1642 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1643 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1644 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1645 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1646 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1647 light_yellow('[id=12]') + ' in your Pocket list.\n'
1651 def help_messages():
1658 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1659 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1660 light_green('inbox 7') + ' will show newest 7 messages.\n'
1661 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1662 light_yellow('[thread_id=2]') + '.\n'
1663 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1664 magenta('@dtvd88') + '.\n'
1665 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1666 light_yellow('[message_id=5]') + '.\n'
1670 def help_friends_and_followers():
1672 Friends and Followers
1675 # Follower and following
1677 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1679 light_green('ls fl') + \
1680 ' will list all followers (people who are following you).\n'
1682 light_green('ls fr') + \
1683 ' will list all friends (people who you are following).\n'
1684 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1685 magenta('@dtvd88') + '.\n'
1686 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1687 magenta('@dtvd88') + '.\n'
1688 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1689 magenta('@dtvd88') + '.\n'
1690 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1691 magenta('@dtvd88') + '.\n'
1692 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1693 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1694 magenta('@dtvd88') + '.\n'
1695 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1696 magenta('@dtvd88') + '.\n'
1697 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1698 magenta('@dtvd88') + ' as a spam account.\n'
1709 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1710 usage
+= s
* 2 + light_green('list') + \
1711 ' will show all lists you are belong to.\n'
1712 usage
+= s
* 2 + light_green('list home') + \
1713 ' will show timeline of list. You will be asked for list\'s name.\n'
1714 usage
+= s
* 2 + light_green('list all_mem') + \
1715 ' will show list\'s all members.\n'
1716 usage
+= s
* 2 + light_green('list all_sub') + \
1717 ' will show list\'s all subscribers.\n'
1718 usage
+= s
* 2 + light_green('list add') + \
1719 ' will add specific person to a list owned by you.' + \
1720 ' You will be asked for list\'s name and person\'s name.\n'
1721 usage
+= s
* 2 + light_green('list rm') + \
1722 ' will remove specific person from a list owned by you.' + \
1723 ' You will be asked for list\'s name and person\'s name.\n'
1724 usage
+= s
* 2 + light_green('list sub') + \
1725 ' will subscribe you to a specific list.\n'
1726 usage
+= s
* 2 + light_green('list unsub') + \
1727 ' will unsubscribe you from a specific list.\n'
1728 usage
+= s
* 2 + light_green('list own') + \
1729 ' will show all list owned by you.\n'
1730 usage
+= s
* 2 + light_green('list new') + \
1731 ' will create a new list.\n'
1732 usage
+= s
* 2 + light_green('list update') + \
1733 ' will update a list owned by you.\n'
1734 usage
+= s
* 2 + light_green('list del') + \
1735 ' will delete a list owned by you.\n'
1746 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1747 usage
+= s
* 2 + light_green('switch public #AKB') + \
1748 ' will switch to public stream and follow "' + \
1749 light_yellow('AKB') + '" keyword.\n'
1750 usage
+= s
* 2 + light_green('switch mine') + \
1751 ' will switch to your personal stream.\n'
1752 usage
+= s
* 2 + light_green('switch mine -f ') + \
1753 ' will prompt to enter the filter.\n'
1754 usage
+= s
* 3 + light_yellow('Only nicks') + \
1755 ' filter will decide nicks will be INCLUDE ONLY.\n'
1756 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1757 ' filter will decide nicks will be EXCLUDE.\n'
1758 usage
+= s
* 2 + light_green('switch list') + \
1759 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1768 h
, w
= os
.popen('stty size', 'r').read().split()
1771 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1772 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1773 usage
+= s
+ 'You are ' + \
1774 light_yellow('already') + ' on your personal stream.\n'
1775 usage
+= s
+ 'Any update from Twitter will show up ' + \
1776 light_yellow('immediately') + '.\n'
1777 usage
+= s
+ 'In addition, following commands are available right now:\n'
1778 # Twitter help section
1780 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1781 usage
+= s
* 2 + light_green('h discover') + \
1782 ' will show help for discover commands.\n'
1783 usage
+= s
* 2 + light_green('h tweets') + \
1784 ' will show help for tweets commands.\n'
1785 usage
+= s
* 2 + light_green('h messages') + \
1786 ' will show help for messages commands.\n'
1787 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1788 ' will show help for friends and followers commands.\n'
1789 usage
+= s
* 2 + light_green('h list') + \
1790 ' will show help for list commands.\n'
1791 usage
+= s
* 2 + light_green('h stream') + \
1792 ' will show help for stream commands.\n'
1795 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1796 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1797 'will be evaluate by Python interpreter.\n'
1798 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1799 ' for current month.\n'
1802 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1803 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1804 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1805 ' theme immediately.\n'
1806 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1808 light_green('config ASCII_ART') + ' will output current value of ' +\
1809 light_yellow('ASCII_ART') + ' config key.\n'
1811 light_green('config TREND_MAX default') + ' will output default value of ' + \
1812 light_yellow('TREND_MAX') + ' config key.\n'
1814 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1815 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1817 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1818 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1819 light_yellow('True') + '.\n'
1822 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1823 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1824 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1825 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1826 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1827 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1828 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1831 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1832 usage
+= s
+ 'Have fun and hang tight! \n'
1835 'discover': help_discover
,
1836 'tweets': help_tweets
,
1837 'messages': help_messages
,
1838 'friends_and_followers': help_friends_and_followers
,
1840 'stream': help_stream
,
1845 lambda: printNicely(red('No such command.'))
1853 Pause stream display
1856 printNicely(green('Stream is paused'))
1864 printNicely(green('Stream is running back now'))
1880 printNicely(green('See you next time :)'))
1888 Reset prefix of line
1891 if c
.get('USER_JSON_ERROR'):
1892 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1893 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1895 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1898 printNicely(str(eval(g
['cmd'])))
1953 # Handle function set
2008 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2013 Listen to user's input
2018 ['public', 'mine', 'list'], # switch
2027 [], # view_my_tweets
2038 ['image'], # show image
2040 ['fl', 'fr'], # list
2042 [i
for i
in g
['message_threads']], # sent
2067 [key
for key
in dict(get_all_config())], # config
2068 g
['themes'], # theme
2073 'friends_and_followers',
2085 init_interactive_shell(d
)
2092 # Only use PREFIX as a string with raw_input
2093 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2096 # Save cmd to compare with readline buffer
2097 g
['cmd'] = line
.strip()
2098 # Get short cmd to pass to handle function
2100 cmd
= line
.split()[0]
2103 # Lock the semaphore
2105 # Save cmd to global variable and call process
2106 g
['stuff'] = ' '.join(line
.split()[1:])
2107 # Check tweet length
2108 # Process the command
2111 if cmd
in ['switch', 't', 'rt', 'rep']:
2117 except TwitterHTTPError
as e
:
2118 detail_twitter_error(e
)
2121 printNicely(red('OMG something is wrong with Twitter API right now.'))
2123 # Release the semaphore lock
2127 def reconn_notice():
2129 Notice when Hangup or Timeout
2131 guide
= light_magenta('You can use ') + \
2132 light_green('switch') + \
2133 light_magenta(' command to return to your stream.\n')
2134 guide
+= light_magenta('Type ') + \
2135 light_green('h stream') + \
2136 light_magenta(' for more details.')
2138 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2142 def stream(domain
, args
, name
='Rainbow Stream'):
2148 c
['USER_DOMAIN']: name
,
2149 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2150 c
['SITE_DOMAIN']: name
,
2153 ascii_art(art_dict
.get(domain
, name
))
2154 # These arguments are optional:
2156 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2158 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2161 if args
.track_keywords
:
2162 query_args
['track'] = args
.track_keywords
2164 stream
= TwitterStream(
2169 if domain
== c
['USER_DOMAIN']:
2170 tweet_iter
= stream
.user(**query_args
)
2171 elif domain
== c
['SITE_DOMAIN']:
2172 tweet_iter
= stream
.site(**query_args
)
2174 if args
.track_keywords
:
2175 tweet_iter
= stream
.statuses
.filter(**query_args
)
2177 tweet_iter
= stream
.statuses
.sample()
2178 # Block new stream until other one exits
2179 StreamLock
.acquire()
2180 g
['stream_stop'] = False
2181 last_tweet_time
= time
.time()
2182 for tweet
in tweet_iter
:
2184 printNicely('-- None --')
2185 elif tweet
is Timeout
:
2186 # Because the stream check for each 0.3s
2187 # so we shouldn't output anything here
2188 if(g
['stream_stop']):
2189 StreamLock
.release()
2191 elif tweet
is HeartbeatTimeout
:
2192 printNicely('-- Heartbeat Timeout --')
2194 StreamLock
.release()
2196 elif tweet
is Hangup
:
2197 printNicely('-- Hangup --')
2199 StreamLock
.release()
2201 elif tweet
.get('text'):
2202 # Slow down the stream by STREAM_DELAY config key
2203 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2205 last_tweet_time
= time
.time()
2206 # Check the semaphore pause and lock (stream process only)
2214 keyword
=args
.track_keywords
,
2219 # Current readline buffer
2220 current_buffer
= readline
.get_line_buffer().strip()
2221 # There is an unexpected behaviour in MacOSX readline + Python 2:
2222 # after completely delete a word after typing it,
2223 # somehow readline buffer still contains
2224 # the 1st character of that word
2225 if current_buffer
and g
['cmd'] != current_buffer
:
2227 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2229 elif not c
['HIDE_PROMPT']:
2230 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2232 elif tweet
.get('direct_message'):
2233 # Check the semaphore pause and lock (stream process only)
2238 print_message(tweet
['direct_message'])
2239 elif tweet
.get('event'):
2240 c
['events'].append(tweet
)
2242 except TwitterHTTPError
as e
:
2245 magenta('We have connection problem with twitter stream API right now :('))
2246 detail_twitter_error(e
)
2247 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2251 magenta('There seems to be a connection problem.'))
2256 def spawn_public_stream(args
, keyword
=None):
2258 Spawn a new public stream
2260 # Only set keyword if specified
2262 if keyword
[0] == '#':
2263 keyword
= keyword
[1:]
2264 args
.track_keywords
= keyword
2265 g
['keyword'] = keyword
2267 g
['keyword'] = 'Global'
2268 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2271 th
= threading
.Thread(
2280 def spawn_list_stream(args
, stuff
=None):
2282 Spawn a new list stream
2285 owner
, slug
= check_slug(stuff
)
2287 owner
, slug
= get_slug()
2289 # Force python 2 not redraw readline buffer
2290 listname
= '/'.join([owner
, slug
])
2291 # Set the listname variable
2292 # and reset tracked keyword
2293 g
['listname'] = listname
2295 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2296 listname
=g
['listname']
2298 printNicely(light_yellow('getting list members ...'))
2300 t
= Twitter(auth
=authen())
2303 while next_cursor
!= 0:
2304 m
= t
.lists
.members(
2306 owner_screen_name
=owner
,
2308 include_entities
=False)
2309 for u
in m
['users']:
2310 members
.append('@' + u
['screen_name'])
2311 next_cursor
= m
['next_cursor']
2312 printNicely(light_yellow('... done.'))
2313 # Build thread filter array
2314 args
.filter = members
2316 th
= threading
.Thread(
2326 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2328 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2332 def spawn_personal_stream(args
, stuff
=None):
2334 Spawn a new personal stream
2336 # Reset the tracked keyword and listname
2337 g
['keyword'] = g
['listname'] = ''
2339 g
['PREFIX'] = u2str(emojize(format_prefix()))
2341 th
= threading
.Thread(
2346 g
['original_name']))
2356 args
= parse_arguments()
2360 # Twitter API connection problem
2361 except TwitterHTTPError
as e
:
2364 magenta('We have connection problem with twitter REST API right now :('))
2365 detail_twitter_error(e
)
2368 # Proxy connection problem
2369 except (socks
.ProxyConnectionError
, URLError
):
2371 magenta('There seems to be a connection problem.'))
2373 magenta('You might want to check your proxy settings (host, port and type)!'))
2377 # Spawn stream thread
2378 target
= args
.stream
.split()[0]
2379 if target
== 'mine':
2380 spawn_personal_stream(args
)
2383 stuff
= args
.stream
.split()[1]
2387 'public': spawn_public_stream
,
2388 'list': spawn_list_stream
,
2390 spawn_dict
.get(target
)(args
, stuff
)
2392 # Start listen process