16 from io
import BytesIO
17 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
18 from twitter
.api
import *
19 from twitter
.oauth
import OAuth
, read_token_file
20 from twitter
.oauth_dance
import oauth_dance
21 from twitter
.util
import printNicely
23 from pocket
import Pocket
28 from .consumer
import *
29 from .interactive
import *
30 from .c_image
import *
31 from .py3patch
import *
39 StreamLock
= threading
.Lock()
42 def parse_arguments():
46 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
51 help='Default stream after program start. (Default: mine)')
55 help='Timeout for the stream (seconds).')
59 help='Search the stream for specific text.')
63 help='Filter specific screen_name.')
67 help='Ignore specific screen_name.')
72 help='Display all image on terminal.')
77 help='Display images using 24bit color codes.')
81 help='Use HTTP/SOCKS proxy for network connections.')
86 help='HTTP/SOCKS proxy port (Default: 8080).')
91 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
92 return parser
.parse_args()
95 def proxy_connect(args
):
97 Connect to specified proxy
100 # Setup proxy by monkeypatching the standard lib
101 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
102 socks
.set_default_proxy(
103 socks
.SOCKS5
, args
.proxy_host
,
104 int(args
.proxy_port
))
105 elif args
.proxy_type
.lower() == "http":
106 socks
.set_default_proxy(
107 socks
.HTTP
, args
.proxy_host
,
108 int(args
.proxy_port
))
109 elif args
.proxy_type
.lower() == "socks4":
110 socks
.set_default_proxy(
111 socks
.SOCKS4
, args
.proxy_host
,
112 int(args
.proxy_port
))
115 magenta('Sorry, wrong proxy type specified! Aborting...'))
117 socket
.socket
= socks
.socksocket
122 Authenticate with Twitter OAuth
124 # When using rainbow stream you must authorize.
125 twitter_credential
= os
.environ
.get(
129 '')) + os
.sep
+ '.rainbow_oauth'
130 if not os
.path
.exists(twitter_credential
):
131 oauth_dance('Rainbow Stream',
135 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
145 Authenticate with Pocket OAuth
147 pocket_credential
= os
.environ
.get(
151 '')) + os
.sep
+ '.rainbow_pckt_oauth'
153 if not os
.path
.exists(pocket_credential
):
154 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
155 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
156 webbrowser
.open(auth_url
)
157 printNicely(green("*** Press [ENTER] after authorization ***"))
159 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
160 access_token
= user_credentials
['access_token']
161 f
= open(pocket_credential
, 'w')
162 f
.write(access_token
)
165 with
open(pocket_credential
, 'r') as f
:
166 access_token
= str(f
.readlines()[0])
169 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
172 def build_mute_dict(dict_data
=False):
176 t
= Twitter(auth
=authen())
179 screen_name_list
= []
182 while next_cursor
!= 0:
183 list = t
.mutes
.users
.list(
184 screen_name
=g
['original_name'],
187 include_entities
=False,
189 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
190 name_list
+= [u
['name'] for u
in list['users']]
191 next_cursor
= list['next_cursor']
192 # Return dict or list
194 return dict(zip(screen_name_list
, name_list
))
196 return screen_name_list
201 Save traceback when run in debug mode
204 g
['traceback'].append(traceback
.format_exc())
207 def upgrade_center():
209 Check latest and notify to upgrade
212 current
= pkg_resources
.get_distribution('rainbowstream').version
213 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
214 readme
= requests
.get(url
).text
215 latest
= readme
.split('version = \'')[1].split('\'')[0]
216 g
['using_latest'] = current
== latest
217 if not g
['using_latest']:
218 notice
= light_magenta('RainbowStream latest version is ')
219 notice
+= light_green(latest
)
220 notice
+= light_magenta(' while your current version is ')
221 notice
+= light_yellow(current
) + '\n'
222 notice
+= light_magenta('You should upgrade with ')
223 notice
+= light_green('pip install -U rainbowstream')
225 notice
= light_yellow('You are running latest version (')
226 notice
+= light_green(current
)
227 notice
+= light_yellow(')')
239 ctrl_c_handler
= lambda signum
, frame
: quit()
240 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
244 t
= Twitter(auth
=authen())
245 credential
= t
.account
.verify_credentials()
246 screen_name
= '@' + credential
['screen_name']
247 name
= credential
['name']
248 c
['original_name'] = g
['original_name'] = screen_name
[1:]
249 g
['listname'] = g
['keyword'] = ''
250 g
['PREFIX'] = u2str(emojize(format_prefix()))
251 g
['full_name'] = name
252 g
['decorated_name'] = lambda x
: color_func(
253 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
255 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
256 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
259 g
['message_threads'] = {}
262 # Debug option default = True
269 # Init tweet dict and message dict
271 c
['message_dict'] = []
273 c
['IMAGE_ON_TERM'] = args
.image_on_term
275 c
['24BIT'] = args
.color_24bit
276 # Check type of ONLY_LIST and IGNORE_LIST
277 if not isinstance(c
['ONLY_LIST'], list):
278 printNicely(red('ONLY_LIST is not a valid list value.'))
280 if not isinstance(c
['IGNORE_LIST'], list):
281 printNicely(red('IGNORE_LIST is not a valid list value.'))
282 c
['IGNORE_LIST'] = []
284 c
['IGNORE_LIST'] += build_mute_dict()
286 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
293 t
= Twitter(auth
=authen())
294 # Get country and town
296 country
= g
['stuff'].split()[0]
300 town
= g
['stuff'].split()[1]
303 avail
= t
.trends
.available()
306 trends
= t
.trends
.place(_id
=1)[0]['trends']
309 for location
in avail
:
310 # Search for country and Town
312 if location
['countryCode'] == country \
313 and location
['placeType']['name'] == 'Town' \
314 and location
['name'] == town
:
315 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
317 # Search for country only
319 if location
['countryCode'] == country \
320 and location
['placeType']['name'] == 'Country':
321 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
329 t
= Twitter(auth
=authen())
330 num
= c
['HOME_TWEET_NUM']
331 if g
['stuff'].isdigit():
332 num
= int(g
['stuff'])
333 kwargs
= {'count': num
}
334 kwargs
= add_tweetmode_parameter(kwargs
)
335 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
345 for e
in c
['events']:
349 printNicely(magenta('Nothing at this time.'))
356 t
= Twitter(auth
=authen())
357 num
= c
['HOME_TWEET_NUM']
358 if g
['stuff'].isdigit():
359 num
= int(g
['stuff'])
360 kwargs
= {'count': num
}
361 kwargs
= add_tweetmode_parameter(kwargs
)
362 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
369 Show profile of a specific user
371 t
= Twitter(auth
=authen())
373 screen_name
= g
['stuff'].split()[0]
375 printNicely(red('Sorry I can\'t understand.'))
377 if screen_name
.startswith('@'):
380 screen_name
=screen_name
[1:],
381 include_entities
=False)
385 printNicely(red('No user.'))
387 printNicely(red('A name should begin with a \'@\''))
394 t
= Twitter(auth
=authen())
396 user
= g
['stuff'].split()[0]
398 printNicely(red('Sorry I can\'t understand.'))
402 num
= int(g
['stuff'].split()[1])
404 num
= c
['HOME_TWEET_NUM']
405 kwargs
= {'count': num
, 'screen_name': user
[1:]}
406 kwargs
= add_tweetmode_parameter(kwargs
)
407 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
411 printNicely(red('A name should begin with a \'@\''))
414 def view_my_tweets():
416 Display user's recent tweets.
418 t
= Twitter(auth
=authen())
420 num
= int(g
['stuff'])
422 num
= c
['HOME_TWEET_NUM']
423 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
424 kwargs
= add_tweetmode_parameter(kwargs
)
425 for tweet
in reversed(
426 t
.statuses
.user_timeline(**kwargs
)):
435 t
= Twitter(auth
=authen())
437 query
= g
['stuff'].strip()
439 printNicely(red('Sorry I can\'t understand.'))
441 type = c
['SEARCH_TYPE']
442 if type not in ['mixed', 'recent', 'popular']:
444 max_record
= c
['SEARCH_MAX_RECORD']
445 count
= min(max_record
, 100)
451 kwargs
= add_tweetmode_parameter(kwargs
)
453 rel
= t
.search
.tweets(**kwargs
)['statuses']
456 printNicely('Newest tweets:')
457 for i
in reversed(xrange(count
)):
458 draw(t
=rel
[i
], keyword
=query
)
461 printNicely(magenta('I\'m afraid there is no result'))
468 t
= Twitter(auth
=authen())
469 t
.statuses
.update(status
=g
['stuff'])
474 Add new link to Pocket along with tweet id
476 if not c
['POCKET_SUPPORT']:
477 printNicely(yellow('Pocket isn\'t enabled.'))
478 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
484 t
= Twitter(auth
=authen())
486 id = int(g
['stuff'].split()[0])
487 tid
= c
['tweet_dict'][id]
489 printNicely(red('Sorry I can\'t understand.'))
492 tweet
= t
.statuses
.show(id=tid
)
494 if len(tweet
['entities']['urls']) > 0:
495 url
= tweet
['entities']['urls'][0]['expanded_url']
497 url
= "https://twitter.com/" + \
498 tweet
['user']['screen_name'] + '/status/' + str(tid
)
502 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
506 printNicely(red('Something is wrong about your Pocket account,'+ \
507 ' please restart Rainbowstream.'))
508 pocket_credential
= os
.environ
.get(
512 '')) + os
.sep
+ '.rainbow_pckt_oauth'
513 if os
.path
.exists(pocket_credential
):
514 os
.remove(pocket_credential
)
517 printNicely(green('Pocketed !'))
525 t
= Twitter(auth
=authen())
527 id = int(g
['stuff'].split()[0])
529 printNicely(red('Sorry I can\'t understand.'))
531 tid
= c
['tweet_dict'][id]
532 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
540 t
= Twitter(auth
=authen())
542 id = int(g
['stuff'].split()[0])
544 printNicely(red('Sorry I can\'t understand.'))
546 tid
= c
['tweet_dict'][id]
548 kwargs
= add_tweetmode_parameter(kwargs
)
549 tweet
= t
.statuses
.show(**kwargs
)
551 formater
= format_quote(tweet
)
555 prefix
= light_magenta('Compose your ', rl
=True) + \
556 light_green('#comment: ', rl
=True)
557 comment
= raw_input(prefix
)
559 quote
= comment
.join(formater
.split('#comment'))
560 t
.statuses
.update(status
=quote
)
562 printNicely(light_magenta('No text added.'))
569 t
= Twitter(auth
=authen())
572 id = int(g
['stuff'].split()[0])
574 printNicely(red('Sorry I can\'t understand.'))
576 tid
= c
['tweet_dict'][id]
577 # Get display num if exist
579 num
= int(g
['stuff'].split()[1])
581 num
= c
['RETWEETS_SHOW_NUM']
582 # Get result and display
583 kwargs
= {'id': tid
, 'count': num
}
584 kwargs
= add_tweetmode_parameter(kwargs
)
585 rt_ary
= t
.statuses
.retweets(**kwargs
)
587 printNicely(magenta('This tweet has no retweet.'))
589 for tweet
in reversed(rt_ary
):
598 t
= Twitter(auth
=authen())
600 id = int(g
['stuff'].split()[0])
602 printNicely(red('Sorry I can\'t understand.'))
604 tid
= c
['tweet_dict'][id]
606 kwargs
= add_tweetmode_parameter(kwargs
)
607 tweet
= t
.statuses
.show(**kwargs
)
608 limit
= c
['CONVERSATION_MAX']
610 thread_ref
.append(tweet
)
611 prev_tid
= tweet
['in_reply_to_status_id']
612 while prev_tid
and limit
:
614 kwargs
['id'] = prev_tid
615 tweet
= t
.statuses
.show(**kwargs
)
616 prev_tid
= tweet
['in_reply_to_status_id']
617 thread_ref
.append(tweet
)
619 for tweet
in reversed(thread_ref
):
628 t
= Twitter(auth
=authen())
630 id = int(g
['stuff'].split()[0])
632 printNicely(red('Sorry I can\'t understand.'))
634 tid
= c
['tweet_dict'][id]
635 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
636 status
= ' '.join(g
['stuff'].split()[1:])
637 # don't include own username for tweet chains
638 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
639 if user
== g
['original_name']:
640 status
= str2u(status
)
642 status
= '@' + user
+ ' ' + str2u(status
)
643 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
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 original_tweet
= t
.statuses
.show(id=tid
)
658 text
= original_tweet
['text']
659 nick_ary
= [original_tweet
['user']['screen_name']]
660 for user
in list(original_tweet
['entities']['user_mentions']):
661 if user
['screen_name'] not in nick_ary \
662 and user
['screen_name'] != g
['original_name']:
663 nick_ary
.append(user
['screen_name'])
664 status
= ' '.join(g
['stuff'].split()[1:])
665 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
666 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
673 t
= Twitter(auth
=authen())
675 id = int(g
['stuff'].split()[0])
677 printNicely(red('Sorry I can\'t understand.'))
679 tid
= c
['tweet_dict'][id]
680 t
.favorites
.create(_id
=tid
, include_entities
=False)
681 printNicely(green('Favorited.'))
683 kwargs
= add_tweetmode_parameter(kwargs
)
684 draw(t
.statuses
.show(**kwargs
))
692 t
= Twitter(auth
=authen())
694 id = int(g
['stuff'].split()[0])
696 printNicely(red('Sorry I can\'t understand.'))
698 tid
= c
['tweet_dict'][id]
699 t
.favorites
.destroy(_id
=tid
)
700 printNicely(green('Okay it\'s unfavorited.'))
702 kwargs
= add_tweetmode_parameter(kwargs
)
703 draw(t
.statuses
.show(**kwargs
))
709 Copy url of a tweet to clipboard
711 t
= Twitter(auth
=authen())
713 id = int(g
['stuff'].split()[0])
714 tid
= c
['tweet_dict'][id]
716 printNicely(red('Tweet id is not valid.'))
719 kwargs
= add_tweetmode_parameter(kwargs
)
720 tweet
= t
.statuses
.show(**kwargs
)
721 url
= 'https://twitter.com/' + \
722 tweet
['user']['screen_name'] + '/status/' + str(tid
)
724 if platform
.system().lower() == 'darwin':
725 os
.system("echo '%s' | pbcopy" % url
)
726 printNicely(green('Copied tweet\'s url to clipboard.'))
728 printNicely('Direct link: ' + yellow(url
))
735 t
= Twitter(auth
=authen())
737 id = int(g
['stuff'].split()[0])
739 printNicely(red('Sorry I can\'t understand.'))
741 tid
= c
['tweet_dict'][id]
742 t
.statuses
.destroy(id=tid
)
743 printNicely(green('Okay it\'s gone.'))
750 t
= Twitter(auth
=authen())
752 target
= g
['stuff'].split()[0]
753 if target
!= 'image':
755 id = int(g
['stuff'].split()[1])
756 tid
= c
['tweet_dict'][id]
757 tweet
= t
.statuses
.show(id=tid
)
758 media
= tweet
['entities']['media']
760 res
= requests
.get(m
['media_url'])
761 img
= Image
.open(BytesIO(res
.content
))
765 printNicely(red('Sorry I can\'t show this image.'))
772 t
= Twitter(auth
=authen())
774 if not g
['stuff'].isdigit():
776 tid
= c
['tweet_dict'][int(g
['stuff'])]
777 tweet
= t
.statuses
.show(id=tid
)
778 urls
= tweet
['entities']['urls']
780 printNicely(light_magenta('No url here @.@!'))
784 expanded_url
= url
['expanded_url']
785 webbrowser
.open(expanded_url
)
788 printNicely(red('Sorry I can\'t open url in this tweet.'))
795 t
= Twitter(auth
=authen())
796 num
= c
['MESSAGES_DISPLAY']
797 if g
['stuff'].isdigit():
803 inbox
= inbox
+ t
.direct_messages(
806 include_entities
=False,
811 inbox
= inbox
+ t
.direct_messages(
814 include_entities
=False,
818 num
= c
['MESSAGES_DISPLAY']
819 if g
['stuff'].isdigit():
824 sent
= sent
+ t
.direct_messages
.sent(
827 include_entities
=False,
832 sent
= sent
+ t
.direct_messages
.sent(
835 include_entities
=False,
840 uniq_inbox
= list(set(
841 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
843 uniq_sent
= list(set(
844 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
846 for partner
in uniq_inbox
:
847 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
849 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
850 d
[partner
] = inbox_ary
+ sent_ary
851 for partner
in uniq_sent
:
854 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
855 g
['message_threads'] = print_threads(d
)
860 View a thread of message
863 thread_id
= int(g
['stuff'])
865 g
['message_threads'][thread_id
],
870 printNicely(red('No such thread.'))
875 Send a direct message
877 t
= Twitter(auth
=authen())
879 user
= g
['stuff'].split()[0]
880 if user
[0].startswith('@'):
881 content
= ' '.join(g
['stuff'].split()[1:])
882 t
.direct_messages
.new(
883 screen_name
=user
[1:],
886 printNicely(green('Message sent.'))
888 printNicely(red('A name should begin with a \'@\''))
891 printNicely(red('Sorry I can\'t understand.'))
898 t
= Twitter(auth
=authen())
900 id = int(g
['stuff'].split()[0])
902 printNicely(red('Sorry I can\'t understand.'))
903 mid
= c
['message_dict'][id]
904 t
.direct_messages
.destroy(id=mid
)
905 printNicely(green('Message deleted.'))
910 List friends for followers
912 t
= Twitter(auth
=authen())
915 name
= g
['stuff'].split()[1]
916 if name
.startswith('@'):
919 printNicely(red('A name should begin with a \'@\''))
920 raise Exception('Invalid name')
922 name
= g
['original_name']
923 # Get list followers or friends
925 target
= g
['stuff'].split()[0]
927 printNicely(red('Omg some syntax is wrong.'))
930 d
= {'fl': 'followers', 'fr': 'friends'}
934 printNicely('All ' + d
[target
] + ':')
938 while next_cursor
!= 0:
940 list = getattr(t
, d
[target
]).list(
944 include_entities
=False,
947 for u
in list['users']:
953 + cycle_color( u
['name'] ) \
954 + color_func(c
['TWEET']['nick'])( ' @' \
958 next_cursor
= list['next_cursor']
960 # 300 users means 15 calls to the related API. The rate limit is 15
961 # calls per 15mn periods (see Twitter documentation).
962 if ( number_of_users
% 300 == 0 ):
963 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
964 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
967 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
973 t
= Twitter(auth
=authen())
974 screen_name
= g
['stuff'].split()[0]
975 if screen_name
.startswith('@'):
976 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
977 printNicely(green('You are following ' + screen_name
+ ' now!'))
979 printNicely(red('A name should begin with a \'@\''))
986 t
= Twitter(auth
=authen())
987 screen_name
= g
['stuff'].split()[0]
988 if screen_name
.startswith('@'):
989 t
.friendships
.destroy(
990 screen_name
=screen_name
[1:],
991 include_entities
=False)
992 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
994 printNicely(red('A name should begin with a \'@\''))
1001 t
= Twitter(auth
=authen())
1003 screen_name
= g
['stuff'].split()[0]
1005 printNicely(red('A name should be specified. '))
1007 if screen_name
.startswith('@'):
1009 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1010 if isinstance(rel
, dict):
1011 printNicely(green(screen_name
+ ' is muted.'))
1012 c
['IGNORE_LIST'] += [screen_name
]
1013 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1015 printNicely(red(rel
))
1018 printNicely(red('Something is wrong, can not mute now :('))
1020 printNicely(red('A name should begin with a \'@\''))
1027 t
= Twitter(auth
=authen())
1029 screen_name
= g
['stuff'].split()[0]
1031 printNicely(red('A name should be specified. '))
1033 if screen_name
.startswith('@'):
1035 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1036 if isinstance(rel
, dict):
1037 printNicely(green(screen_name
+ ' is unmuted.'))
1038 c
['IGNORE_LIST'].remove(screen_name
)
1040 printNicely(red(rel
))
1042 printNicely(red('Maybe you are not muting this person ?'))
1044 printNicely(red('A name should begin with a \'@\''))
1051 # Get dict of muting users
1052 md
= build_mute_dict(dict_data
=True)
1053 printNicely('All: ' + str(len(md
)) + ' people.')
1055 user
= ' ' + cycle_color(md
[name
])
1056 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1058 # Update from Twitter
1059 c
['IGNORE_LIST'] = [n
for n
in md
]
1066 t
= Twitter(auth
=authen())
1067 screen_name
= g
['stuff'].split()[0]
1068 if screen_name
.startswith('@'):
1070 screen_name
=screen_name
[1:],
1071 include_entities
=False,
1073 printNicely(green('You blocked ' + screen_name
+ '.'))
1075 printNicely(red('A name should begin with a \'@\''))
1082 t
= Twitter(auth
=authen())
1083 screen_name
= g
['stuff'].split()[0]
1084 if screen_name
.startswith('@'):
1086 screen_name
=screen_name
[1:],
1087 include_entities
=False,
1089 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1091 printNicely(red('A name should begin with a \'@\''))
1096 Report a user as a spam account
1098 t
= Twitter(auth
=authen())
1099 screen_name
= g
['stuff'].split()[0]
1100 if screen_name
.startswith('@'):
1101 t
.users
.report_spam(
1102 screen_name
=screen_name
[1:])
1103 printNicely(green('You reported ' + screen_name
+ '.'))
1105 printNicely(red('Sorry I can\'t understand.'))
1113 list_name
= raw_input(
1114 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1115 # Get list name and owner
1117 owner
, slug
= list_name
.split('/')
1118 if slug
.startswith('@'):
1123 light_magenta('List name should follow "@owner/list_name" format.'))
1124 raise Exception('Wrong list name')
1127 def check_slug(list_name
):
1131 # Get list name and owner
1133 owner
, slug
= list_name
.split('/')
1134 if slug
.startswith('@'):
1139 light_magenta('List name should follow "@owner/list_name" format.'))
1140 raise Exception('Wrong list name')
1147 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1151 printNicely(light_magenta('You belong to no lists :)'))
1158 owner
, slug
= get_slug()
1159 res
= t
.lists
.statuses(
1161 owner_screen_name
=owner
,
1162 count
=c
['LIST_MAX'],
1163 include_entities
=False)
1164 for tweet
in reversed(res
):
1169 def list_members(t
):
1173 owner
, slug
= get_slug()
1177 while next_cursor
!= 0:
1178 m
= t
.lists
.members(
1180 owner_screen_name
=owner
,
1182 include_entities
=False)
1183 for u
in m
['users']:
1184 rel
[u
['name']] = '@' + u
['screen_name']
1185 next_cursor
= m
['next_cursor']
1186 printNicely('All: ' + str(len(rel
)) + ' members.')
1188 user
= ' ' + cycle_color(name
)
1189 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1193 def list_subscribers(t
):
1197 owner
, slug
= get_slug()
1201 while next_cursor
!= 0:
1202 m
= t
.lists
.subscribers(
1204 owner_screen_name
=owner
,
1206 include_entities
=False)
1207 for u
in m
['users']:
1208 rel
[u
['name']] = '@' + u
['screen_name']
1209 next_cursor
= m
['next_cursor']
1210 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1212 user
= ' ' + cycle_color(name
)
1213 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1219 Add specific user to a list
1221 owner
, slug
= get_slug()
1223 user_name
= raw_input(
1225 'Give me name of the newbie: ',
1227 if user_name
.startswith('@'):
1228 user_name
= user_name
[1:]
1230 t
.lists
.members
.create(
1232 owner_screen_name
=owner
,
1233 screen_name
=user_name
)
1234 printNicely(green('Added.'))
1237 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1242 Remove specific user from a list
1244 owner
, slug
= get_slug()
1246 user_name
= raw_input(
1248 'Give me name of the unlucky one: ',
1250 if user_name
.startswith('@'):
1251 user_name
= user_name
[1:]
1253 t
.lists
.members
.destroy(
1255 owner_screen_name
=owner
,
1256 screen_name
=user_name
)
1257 printNicely(green('Gone.'))
1260 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1263 def list_subscribe(t
):
1267 owner
, slug
= get_slug()
1270 t
.lists
.subscribers
.create(
1272 owner_screen_name
=owner
)
1273 printNicely(green('Done.'))
1277 light_magenta('I\'m sorry you can not subscribe to this list.'))
1280 def list_unsubscribe(t
):
1284 owner
, slug
= get_slug()
1287 t
.lists
.subscribers
.destroy(
1289 owner_screen_name
=owner
)
1290 printNicely(green('Done.'))
1294 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1303 while next_cursor
!= 0:
1304 res
= t
.lists
.ownerships(
1305 screen_name
=g
['original_name'],
1308 next_cursor
= res
['next_cursor']
1312 printNicely(light_magenta('You own no lists :)'))
1319 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1322 'New list\'s mode (public/private): ',
1324 description
= raw_input(
1326 'New list\'s description: ',
1332 description
=description
)
1333 printNicely(green(name
+ ' list is created.'))
1336 printNicely(red('Oops something is wrong with Twitter :('))
1345 'Your list that you want to update: ',
1349 'Update name (leave blank to unchange): ',
1351 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1352 description
= raw_input(light_magenta('Update description: ', rl
=True))
1356 slug
='-'.join(slug
.split()),
1357 owner_screen_name
=g
['original_name'],
1360 description
=description
)
1364 owner_screen_name
=g
['original_name'],
1366 description
=description
)
1367 printNicely(green(slug
+ ' list is updated.'))
1370 printNicely(red('Oops something is wrong with Twitter :('))
1379 'Your list that you want to delete: ',
1383 slug
='-'.join(slug
.split()),
1384 owner_screen_name
=g
['original_name'])
1385 printNicely(green(slug
+ ' list is deleted.'))
1388 printNicely(red('Oops something is wrong with Twitter :('))
1395 t
= Twitter(auth
=authen())
1396 # List all lists or base on action
1398 g
['list_action'] = g
['stuff'].split()[0]
1405 'all_mem': list_members
,
1406 'all_sub': list_subscribers
,
1409 'sub': list_subscribe
,
1410 'unsub': list_unsubscribe
,
1413 'update': list_update
,
1417 return action_ary
[g
['list_action']](t
)
1419 printNicely(red('Please try again.'))
1427 target
= g
['stuff'].split()[0]
1429 args
= parse_arguments()
1431 if g
['stuff'].split()[-1] == '-f':
1432 guide
= 'To ignore an option, just hit Enter key.'
1433 printNicely(light_magenta(guide
))
1434 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1435 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1436 args
.filter = list(filter(None, only
.split(',')))
1437 args
.ignore
= list(filter(None, ignore
.split(',')))
1439 printNicely(red('Sorry, wrong format.'))
1442 g
['stream_stop'] = True
1444 stuff
= g
['stuff'].split()[1]
1449 'public': spawn_public_stream
,
1450 'list': spawn_list_stream
,
1451 'mine': spawn_personal_stream
,
1453 spawn_dict
.get(target
)(args
, stuff
)
1456 printNicely(red('Sorry I can\'t understand.'))
1461 Unix's command `cal`
1464 rel
= os
.popen('cal').read().split('\n')
1467 show_calendar(month
, date
, rel
)
1472 List and change theme
1476 for theme
in g
['themes']:
1477 line
= light_magenta(theme
)
1478 if c
['THEME'] == theme
:
1479 line
= ' ' * 2 + light_yellow('* ') + line
1481 line
= ' ' * 4 + line
1487 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1488 # Redefine decorated_name
1489 g
['decorated_name'] = lambda x
: color_func(
1490 c
['DECORATED_NAME'])(
1492 printNicely(green('Theme changed.'))
1494 printNicely(red('No such theme exists.'))
1499 Browse and change config
1501 all_config
= get_all_config()
1502 g
['stuff'] = g
['stuff'].strip()
1505 for k
in all_config
:
1507 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1509 guide
= 'Detailed explanation can be found at ' + \
1510 color_func(c
['TWEET']['link'])(
1511 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1513 # Print specific config
1514 elif len(g
['stuff'].split()) == 1:
1515 if g
['stuff'] in all_config
:
1518 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1521 printNicely(red('No such config key.'))
1522 # Print specific config's default value
1523 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1524 key
= g
['stuff'].split()[0]
1526 value
= get_default_config(key
)
1527 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1531 printNicely(red('Just can not get the default.'))
1532 # Delete specific config key in config file
1533 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1534 key
= g
['stuff'].split()[0]
1537 printNicely(green('Config key is dropped.'))
1540 printNicely(red('Just can not drop the key.'))
1541 # Set specific config
1542 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1543 key
= g
['stuff'].split()[0]
1544 value
= g
['stuff'].split()[-1]
1545 if key
== 'THEME' and not validate_theme(value
):
1546 printNicely(red('Invalid theme\'s value.'))
1549 set_config(key
, value
)
1550 # Keys that needs to be apply immediately
1552 c
['THEME'] = reload_theme(value
, c
['THEME'])
1553 g
['decorated_name'] = lambda x
: color_func(
1554 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1555 elif key
== 'PREFIX':
1556 g
['PREFIX'] = u2str(emojize(format_prefix(
1557 listname
=g
['listname'],
1558 keyword
=g
['keyword']
1561 printNicely(green('Updated successfully.'))
1564 printNicely(red('Just can not set the key.'))
1566 printNicely(light_magenta('Sorry I can\'t understand.'))
1569 def help_discover():
1574 # Discover the world
1576 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1577 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1578 'You can try ' + light_green('trend US') + ' or ' + \
1579 light_green('trend JP Tokyo') + '.\n'
1580 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1581 light_green('home 7') + ' will show 7 tweets.\n'
1582 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1583 light_green('me 2') + ' will show your last 2 tweets.\n'
1585 light_green('notification') + ' will show your recent notification.\n'
1586 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1587 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1588 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1589 magenta('@mdo') + '.\n'
1590 usage
+= s
* 2 + light_green('view @mdo') + \
1591 ' will show ' + magenta('@mdo') + '\'s home.\n'
1592 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1593 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1594 'Search can be performed with or without hashtag.\n'
1605 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1606 usage
+= s
* 2 + light_green('t oops ') + \
1607 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1609 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1610 light_yellow('[id=12]') + '.\n'
1612 light_green('quote 12 ') + ' will quote the tweet with ' + \
1613 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1614 'the quote will be canceled.\n'
1616 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1617 light_yellow('[id=12]') + '.\n'
1618 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1619 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1620 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1621 light_yellow('oops') + '" to the owner of the tweet with ' + \
1622 light_yellow('[id=12]') + '.\n'
1623 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1624 light_yellow('oops') + '" to all people in the tweet with ' + \
1625 light_yellow('[id=12]') + '.\n'
1627 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1628 light_yellow('[id=12]') + '.\n'
1630 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1631 light_yellow('[id=12]') + '.\n'
1633 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1634 light_yellow('[id=12]') + '.\n'
1636 light_green('del 12 ') + ' will delete tweet with ' + \
1637 light_yellow('[id=12]') + '.\n'
1638 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1639 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1640 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1641 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1642 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1643 light_yellow('[id=12]') + ' in your Pocket list.\n'
1647 def help_messages():
1654 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1655 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1656 light_green('inbox 7') + ' will show newest 7 messages.\n'
1657 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1658 light_yellow('[thread_id=2]') + '.\n'
1659 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1660 magenta('@dtvd88') + '.\n'
1661 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1662 light_yellow('[message_id=5]') + '.\n'
1666 def help_friends_and_followers():
1668 Friends and Followers
1671 # Follower and following
1673 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1675 light_green('ls fl') + \
1676 ' will list all followers (people who are following you).\n'
1678 light_green('ls fr') + \
1679 ' will list all friends (people who you are following).\n'
1680 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1681 magenta('@dtvd88') + '.\n'
1682 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1683 magenta('@dtvd88') + '.\n'
1684 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1685 magenta('@dtvd88') + '.\n'
1686 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1687 magenta('@dtvd88') + '.\n'
1688 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1689 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1690 magenta('@dtvd88') + '.\n'
1691 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1692 magenta('@dtvd88') + '.\n'
1693 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1694 magenta('@dtvd88') + ' as a spam account.\n'
1705 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1706 usage
+= s
* 2 + light_green('list') + \
1707 ' will show all lists you are belong to.\n'
1708 usage
+= s
* 2 + light_green('list home') + \
1709 ' will show timeline of list. You will be asked for list\'s name.\n'
1710 usage
+= s
* 2 + light_green('list all_mem') + \
1711 ' will show list\'s all members.\n'
1712 usage
+= s
* 2 + light_green('list all_sub') + \
1713 ' will show list\'s all subscribers.\n'
1714 usage
+= s
* 2 + light_green('list add') + \
1715 ' will add specific person to a list owned by you.' + \
1716 ' You will be asked for list\'s name and person\'s name.\n'
1717 usage
+= s
* 2 + light_green('list rm') + \
1718 ' will remove specific person from a list owned by you.' + \
1719 ' You will be asked for list\'s name and person\'s name.\n'
1720 usage
+= s
* 2 + light_green('list sub') + \
1721 ' will subscribe you to a specific list.\n'
1722 usage
+= s
* 2 + light_green('list unsub') + \
1723 ' will unsubscribe you from a specific list.\n'
1724 usage
+= s
* 2 + light_green('list own') + \
1725 ' will show all list owned by you.\n'
1726 usage
+= s
* 2 + light_green('list new') + \
1727 ' will create a new list.\n'
1728 usage
+= s
* 2 + light_green('list update') + \
1729 ' will update a list owned by you.\n'
1730 usage
+= s
* 2 + light_green('list del') + \
1731 ' will delete a list owned by you.\n'
1742 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1743 usage
+= s
* 2 + light_green('switch public #AKB') + \
1744 ' will switch to public stream and follow "' + \
1745 light_yellow('AKB') + '" keyword.\n'
1746 usage
+= s
* 2 + light_green('switch mine') + \
1747 ' will switch to your personal stream.\n'
1748 usage
+= s
* 2 + light_green('switch mine -f ') + \
1749 ' will prompt to enter the filter.\n'
1750 usage
+= s
* 3 + light_yellow('Only nicks') + \
1751 ' filter will decide nicks will be INCLUDE ONLY.\n'
1752 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1753 ' filter will decide nicks will be EXCLUDE.\n'
1754 usage
+= s
* 2 + light_green('switch list') + \
1755 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1764 h
, w
= os
.popen('stty size', 'r').read().split()
1767 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1768 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1769 usage
+= s
+ 'You are ' + \
1770 light_yellow('already') + ' on your personal stream.\n'
1771 usage
+= s
+ 'Any update from Twitter will show up ' + \
1772 light_yellow('immediately') + '.\n'
1773 usage
+= s
+ 'In addition, following commands are available right now:\n'
1774 # Twitter help section
1776 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1777 usage
+= s
* 2 + light_green('h discover') + \
1778 ' will show help for discover commands.\n'
1779 usage
+= s
* 2 + light_green('h tweets') + \
1780 ' will show help for tweets commands.\n'
1781 usage
+= s
* 2 + light_green('h messages') + \
1782 ' will show help for messages commands.\n'
1783 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1784 ' will show help for friends and followers commands.\n'
1785 usage
+= s
* 2 + light_green('h list') + \
1786 ' will show help for list commands.\n'
1787 usage
+= s
* 2 + light_green('h stream') + \
1788 ' will show help for stream commands.\n'
1791 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1792 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1793 'will be evaluate by Python interpreter.\n'
1794 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1795 ' for current month.\n'
1798 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1799 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1800 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1801 ' theme immediately.\n'
1802 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1804 light_green('config ASCII_ART') + ' will output current value of ' +\
1805 light_yellow('ASCII_ART') + ' config key.\n'
1807 light_green('config TREND_MAX default') + ' will output default value of ' + \
1808 light_yellow('TREND_MAX') + ' config key.\n'
1810 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1811 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1813 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1814 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1815 light_yellow('True') + '.\n'
1818 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1819 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1820 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1821 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1822 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1823 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1824 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1827 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1828 usage
+= s
+ 'Have fun and hang tight! \n'
1831 'discover': help_discover
,
1832 'tweets': help_tweets
,
1833 'messages': help_messages
,
1834 'friends_and_followers': help_friends_and_followers
,
1836 'stream': help_stream
,
1841 lambda: printNicely(red('No such command.'))
1849 Pause stream display
1852 printNicely(green('Stream is paused'))
1860 printNicely(green('Stream is running back now'))
1876 printNicely(green('See you next time :)'))
1884 Reset prefix of line
1887 if c
.get('USER_JSON_ERROR'):
1888 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1889 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1891 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1894 printNicely(str(eval(g
['cmd'])))
1949 # Handle function set
2004 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2009 Listen to user's input
2014 ['public', 'mine', 'list'], # switch
2023 [], # view_my_tweets
2034 ['image'], # show image
2036 ['fl', 'fr'], # list
2038 [i
for i
in g
['message_threads']], # sent
2063 [key
for key
in dict(get_all_config())], # config
2064 g
['themes'], # theme
2069 'friends_and_followers',
2081 init_interactive_shell(d
)
2088 # Only use PREFIX as a string with raw_input
2089 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2092 # Save cmd to compare with readline buffer
2093 g
['cmd'] = line
.strip()
2094 # Get short cmd to pass to handle function
2096 cmd
= line
.split()[0]
2099 # Lock the semaphore
2101 # Save cmd to global variable and call process
2102 g
['stuff'] = ' '.join(line
.split()[1:])
2103 # Check tweet length
2104 # Process the command
2107 if cmd
in ['switch', 't', 'rt', 'rep']:
2113 except TwitterHTTPError
as e
:
2114 detail_twitter_error(e
)
2117 printNicely(red('OMG something is wrong with Twitter API right now.'))
2119 # Release the semaphore lock
2123 def reconn_notice():
2125 Notice when Hangup or Timeout
2127 guide
= light_magenta('You can use ') + \
2128 light_green('switch') + \
2129 light_magenta(' command to return to your stream.\n')
2130 guide
+= light_magenta('Type ') + \
2131 light_green('h stream') + \
2132 light_magenta(' for more details.')
2134 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2138 def stream(domain
, args
, name
='Rainbow Stream'):
2144 c
['USER_DOMAIN']: name
,
2145 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2146 c
['SITE_DOMAIN']: name
,
2149 ascii_art(art_dict
.get(domain
, name
))
2150 # These arguments are optional:
2152 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2154 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2157 if args
.track_keywords
:
2158 query_args
['track'] = args
.track_keywords
2160 stream
= TwitterStream(
2165 if domain
== c
['USER_DOMAIN']:
2166 tweet_iter
= stream
.user(**query_args
)
2167 elif domain
== c
['SITE_DOMAIN']:
2168 tweet_iter
= stream
.site(**query_args
)
2170 if args
.track_keywords
:
2171 tweet_iter
= stream
.statuses
.filter(**query_args
)
2173 tweet_iter
= stream
.statuses
.sample()
2174 # Block new stream until other one exits
2175 StreamLock
.acquire()
2176 g
['stream_stop'] = False
2177 last_tweet_time
= time
.time()
2178 for tweet
in tweet_iter
:
2180 printNicely('-- None --')
2181 elif tweet
is Timeout
:
2182 # Because the stream check for each 0.3s
2183 # so we shouldn't output anything here
2184 if(g
['stream_stop']):
2185 StreamLock
.release()
2187 elif tweet
is HeartbeatTimeout
:
2188 printNicely('-- Heartbeat Timeout --')
2190 StreamLock
.release()
2192 elif tweet
is Hangup
:
2193 printNicely('-- Hangup --')
2195 StreamLock
.release()
2197 elif tweet
.get('text'):
2198 # Slow down the stream by STREAM_DELAY config key
2199 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2201 last_tweet_time
= time
.time()
2202 # Check the semaphore pause and lock (stream process only)
2210 keyword
=args
.track_keywords
,
2215 # Current readline buffer
2216 current_buffer
= readline
.get_line_buffer().strip()
2217 # There is an unexpected behaviour in MacOSX readline + Python 2:
2218 # after completely delete a word after typing it,
2219 # somehow readline buffer still contains
2220 # the 1st character of that word
2221 if current_buffer
and g
['cmd'] != current_buffer
:
2223 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2225 elif not c
['HIDE_PROMPT']:
2226 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2228 elif tweet
.get('direct_message'):
2229 # Check the semaphore pause and lock (stream process only)
2234 print_message(tweet
['direct_message'])
2235 elif tweet
.get('event'):
2236 c
['events'].append(tweet
)
2238 except TwitterHTTPError
as e
:
2241 magenta('We have connection problem with twitter stream API right now :('))
2242 detail_twitter_error(e
)
2243 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2247 magenta('There seems to be a connection problem.'))
2252 def spawn_public_stream(args
, keyword
=None):
2254 Spawn a new public stream
2256 # Only set keyword if specified
2258 if keyword
[0] == '#':
2259 keyword
= keyword
[1:]
2260 args
.track_keywords
= keyword
2261 g
['keyword'] = keyword
2263 g
['keyword'] = 'Global'
2264 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2267 th
= threading
.Thread(
2276 def spawn_list_stream(args
, stuff
=None):
2278 Spawn a new list stream
2281 owner
, slug
= check_slug(stuff
)
2283 owner
, slug
= get_slug()
2285 # Force python 2 not redraw readline buffer
2286 listname
= '/'.join([owner
, slug
])
2287 # Set the listname variable
2288 # and reset tracked keyword
2289 g
['listname'] = listname
2291 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2292 listname
=g
['listname']
2294 printNicely(light_yellow('getting list members ...'))
2296 t
= Twitter(auth
=authen())
2299 while next_cursor
!= 0:
2300 m
= t
.lists
.members(
2302 owner_screen_name
=owner
,
2304 include_entities
=False)
2305 for u
in m
['users']:
2306 members
.append('@' + u
['screen_name'])
2307 next_cursor
= m
['next_cursor']
2308 printNicely(light_yellow('... done.'))
2309 # Build thread filter array
2310 args
.filter = members
2312 th
= threading
.Thread(
2322 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2324 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2328 def spawn_personal_stream(args
, stuff
=None):
2330 Spawn a new personal stream
2332 # Reset the tracked keyword and listname
2333 g
['keyword'] = g
['listname'] = ''
2335 g
['PREFIX'] = u2str(emojize(format_prefix()))
2337 th
= threading
.Thread(
2342 g
['original_name']))
2352 args
= parse_arguments()
2356 # Twitter API connection problem
2357 except TwitterHTTPError
as e
:
2360 magenta('We have connection problem with twitter REST API right now :('))
2361 detail_twitter_error(e
)
2364 # Proxy connection problem
2365 except (socks
.ProxyConnectionError
, URLError
):
2367 magenta('There seems to be a connection problem.'))
2369 magenta('You might want to check your proxy settings (host, port and type)!'))
2373 # Spawn stream thread
2374 target
= args
.stream
.split()[0]
2375 if target
== 'mine':
2376 spawn_personal_stream(args
)
2379 stuff
= args
.stream
.split()[1]
2383 'public': spawn_public_stream
,
2384 'list': spawn_list_stream
,
2386 spawn_dict
.get(target
)(args
, stuff
)
2388 # Start listen process