16 from io
import BytesIO
17 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
18 from twitter
.api
import *
19 from twitter
.oauth
import OAuth
, read_token_file
20 from twitter
.oauth_dance
import oauth_dance
21 from twitter
.util
import printNicely
23 from pocket
import Pocket
28 from .consumer
import *
29 from .interactive
import *
30 from .c_image
import *
31 from .py3patch
import *
39 StreamLock
= threading
.Lock()
42 def parse_arguments():
46 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
51 help='Default stream after program start. (Default: mine)')
55 help='Timeout for the stream (seconds).')
59 help='Search the stream for specific text.')
63 help='Filter specific screen_name.')
67 help='Ignore specific screen_name.')
72 help='Display all image on terminal.')
77 help='Display images using 24bit color codes.')
81 help='Use HTTP/SOCKS proxy for network connections.')
86 help='HTTP/SOCKS proxy port (Default: 8080).')
91 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
92 return parser
.parse_args()
95 def proxy_connect(args
):
97 Connect to specified proxy
100 # Setup proxy by monkeypatching the standard lib
101 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
102 socks
.set_default_proxy(
103 socks
.SOCKS5
, args
.proxy_host
,
104 int(args
.proxy_port
))
105 elif args
.proxy_type
.lower() == "http":
106 socks
.set_default_proxy(
107 socks
.HTTP
, args
.proxy_host
,
108 int(args
.proxy_port
))
109 elif args
.proxy_type
.lower() == "socks4":
110 socks
.set_default_proxy(
111 socks
.SOCKS4
, args
.proxy_host
,
112 int(args
.proxy_port
))
115 magenta('Sorry, wrong proxy type specified! Aborting...'))
117 socket
.socket
= socks
.socksocket
122 Authenticate with Twitter OAuth
124 # When using rainbow stream you must authorize.
125 twitter_credential
= os
.environ
.get(
129 '')) + os
.sep
+ '.rainbow_oauth'
130 if not os
.path
.exists(twitter_credential
):
131 oauth_dance('Rainbow Stream',
135 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
145 Authenticate with Pocket OAuth
147 pocket_credential
= os
.environ
.get(
151 '')) + os
.sep
+ '.rainbow_pckt_oauth'
153 if not os
.path
.exists(pocket_credential
):
154 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
155 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
156 webbrowser
.open(auth_url
)
157 printNicely(green("*** Press [ENTER] after authorization ***"))
159 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
160 access_token
= user_credentials
['access_token']
161 f
= open(pocket_credential
, 'w')
162 f
.write(access_token
)
165 with
open(pocket_credential
, 'r') as f
:
166 access_token
= str(f
.readlines()[0])
169 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
172 def build_mute_dict(dict_data
=False):
176 t
= Twitter(auth
=authen())
179 screen_name_list
= []
182 while next_cursor
!= 0:
183 list = t
.mutes
.users
.list(
184 screen_name
=g
['original_name'],
187 include_entities
=False,
189 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
190 name_list
+= [u
['name'] for u
in list['users']]
191 next_cursor
= list['next_cursor']
192 # Return dict or list
194 return dict(zip(screen_name_list
, name_list
))
196 return screen_name_list
201 Save traceback when run in debug mode
204 g
['traceback'].append(traceback
.format_exc())
207 def upgrade_center():
209 Check latest and notify to upgrade
212 current
= pkg_resources
.get_distribution('rainbowstream').version
213 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
214 readme
= requests
.get(url
).text
215 latest
= readme
.split('version = \'')[1].split('\'')[0]
216 g
['using_latest'] = current
== latest
217 if not g
['using_latest']:
218 notice
= light_magenta('RainbowStream latest version is ')
219 notice
+= light_green(latest
)
220 notice
+= light_magenta(' while your current version is ')
221 notice
+= light_yellow(current
) + '\n'
222 notice
+= light_magenta('You should upgrade with ')
223 notice
+= light_green('pip install -U rainbowstream')
225 notice
= light_yellow('You are running latest version (')
226 notice
+= light_green(current
)
227 notice
+= light_yellow(')')
239 ctrl_c_handler
= lambda signum
, frame
: quit()
240 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
244 t
= Twitter(auth
=authen())
245 credential
= t
.account
.verify_credentials()
246 screen_name
= '@' + credential
['screen_name']
247 name
= credential
['name']
248 c
['original_name'] = g
['original_name'] = screen_name
[1:]
249 g
['listname'] = g
['keyword'] = ''
250 g
['PREFIX'] = u2str(emojize(format_prefix()))
251 g
['full_name'] = name
252 g
['decorated_name'] = lambda x
: color_func(
253 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
255 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
256 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
259 g
['message_threads'] = {}
262 # Debug option default = True
269 # Init tweet dict and message dict
271 c
['message_dict'] = []
273 c
['IMAGE_ON_TERM'] = args
.image_on_term
275 c
['24BIT'] = args
.color_24bit
276 # Check type of ONLY_LIST and IGNORE_LIST
277 if not isinstance(c
['ONLY_LIST'], list):
278 printNicely(red('ONLY_LIST is not a valid list value.'))
280 if not isinstance(c
['IGNORE_LIST'], list):
281 printNicely(red('IGNORE_LIST is not a valid list value.'))
282 c
['IGNORE_LIST'] = []
284 c
['IGNORE_LIST'] += build_mute_dict()
286 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
293 t
= Twitter(auth
=authen())
294 # Get country and town
296 country
= g
['stuff'].split()[0]
300 town
= g
['stuff'].split()[1]
303 avail
= t
.trends
.available()
306 trends
= t
.trends
.place(_id
=1)[0]['trends']
309 for location
in avail
:
310 # Search for country and Town
312 if location
['countryCode'] == country \
313 and location
['placeType']['name'] == 'Town' \
314 and location
['name'] == town
:
315 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
317 # Search for country only
319 if location
['countryCode'] == country \
320 and location
['placeType']['name'] == 'Country':
321 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
329 t
= Twitter(auth
=authen())
330 num
= c
['HOME_TWEET_NUM']
331 if g
['stuff'].isdigit():
332 num
= int(g
['stuff'])
333 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
343 for e
in c
['events']:
347 printNicely(magenta('Nothing at this time.'))
354 t
= Twitter(auth
=authen())
355 num
= c
['HOME_TWEET_NUM']
356 if g
['stuff'].isdigit():
357 num
= int(g
['stuff'])
358 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
365 Show profile of a specific user
367 t
= Twitter(auth
=authen())
369 screen_name
= g
['stuff'].split()[0]
371 printNicely(red('Sorry I can\'t understand.'))
373 if screen_name
.startswith('@'):
376 screen_name
=screen_name
[1:],
377 include_entities
=False)
381 printNicely(red('No user.'))
383 printNicely(red('A name should begin with a \'@\''))
390 t
= Twitter(auth
=authen())
392 user
= g
['stuff'].split()[0]
394 printNicely(red('Sorry I can\'t understand.'))
398 num
= int(g
['stuff'].split()[1])
400 num
= c
['HOME_TWEET_NUM']
401 for tweet
in reversed(
402 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
406 printNicely(red('A name should begin with a \'@\''))
409 def view_my_tweets():
411 Display user's recent tweets.
413 t
= Twitter(auth
=authen())
415 num
= int(g
['stuff'])
417 num
= c
['HOME_TWEET_NUM']
418 for tweet
in reversed(
419 t
.statuses
.user_timeline(count
=num
, screen_name
=g
['original_name'])):
428 t
= Twitter(auth
=authen())
430 query
= g
['stuff'].strip()
432 printNicely(red('Sorry I can\'t understand.'))
434 type = c
['SEARCH_TYPE']
435 if type not in ['mixed', 'recent', 'popular']:
437 max_record
= c
['SEARCH_MAX_RECORD']
438 count
= min(max_record
, 100)
440 rel
= t
.search
.tweets(
447 printNicely('Newest tweets:')
448 for i
in reversed(xrange(count
)):
449 draw(t
=rel
[i
], keyword
=query
)
452 printNicely(magenta('I\'m afraid there is no result'))
459 t
= Twitter(auth
=authen())
460 t
.statuses
.update(status
=g
['stuff'])
465 Add new link to Pocket along with tweet id
467 if not c
['POCKET_SUPPORT']:
468 printNicely(yellow('Pocket isn\'t enabled.'))
469 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
475 t
= Twitter(auth
=authen())
477 id = int(g
['stuff'].split()[0])
478 tid
= c
['tweet_dict'][id]
480 printNicely(red('Sorry I can\'t understand.'))
483 tweet
= t
.statuses
.show(id=tid
)
485 if len(tweet
['entities']['urls']) > 0:
486 url
= tweet
['entities']['urls'][0]['expanded_url']
488 url
= "https://twitter.com/" + \
489 tweet
['user']['screen_name'] + '/status/' + str(tid
)
493 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
497 printNicely(red('Something is wrong about your Pocket account,'+ \
498 ' please restart Rainbowstream.'))
499 pocket_credential
= os
.environ
.get(
503 '')) + os
.sep
+ '.rainbow_pckt_oauth'
504 if os
.path
.exists(pocket_credential
):
505 os
.remove(pocket_credential
)
508 printNicely(green('Pocketed !'))
516 t
= Twitter(auth
=authen())
518 id = int(g
['stuff'].split()[0])
520 printNicely(red('Sorry I can\'t understand.'))
522 tid
= c
['tweet_dict'][id]
523 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
531 t
= Twitter(auth
=authen())
533 id = int(g
['stuff'].split()[0])
535 printNicely(red('Sorry I can\'t understand.'))
537 tid
= c
['tweet_dict'][id]
538 tweet
= t
.statuses
.show(id=tid
)
540 formater
= format_quote(tweet
)
544 prefix
= light_magenta('Compose your ', rl
=True) + \
545 light_green('#comment: ', rl
=True)
546 comment
= raw_input(prefix
)
548 quote
= comment
.join(formater
.split('#comment'))
549 t
.statuses
.update(status
=quote
)
551 printNicely(light_magenta('No text added.'))
558 t
= Twitter(auth
=authen())
561 id = int(g
['stuff'].split()[0])
563 printNicely(red('Sorry I can\'t understand.'))
565 tid
= c
['tweet_dict'][id]
566 # Get display num if exist
568 num
= int(g
['stuff'].split()[1])
570 num
= c
['RETWEETS_SHOW_NUM']
571 # Get result and display
572 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
574 printNicely(magenta('This tweet has no retweet.'))
576 for tweet
in reversed(rt_ary
):
585 t
= Twitter(auth
=authen())
587 id = int(g
['stuff'].split()[0])
589 printNicely(red('Sorry I can\'t understand.'))
591 tid
= c
['tweet_dict'][id]
592 tweet
= t
.statuses
.show(id=tid
)
593 limit
= c
['CONVERSATION_MAX']
595 thread_ref
.append(tweet
)
596 prev_tid
= tweet
['in_reply_to_status_id']
597 while prev_tid
and limit
:
599 tweet
= t
.statuses
.show(id=prev_tid
)
600 prev_tid
= tweet
['in_reply_to_status_id']
601 thread_ref
.append(tweet
)
603 for tweet
in reversed(thread_ref
):
612 t
= Twitter(auth
=authen())
614 id = int(g
['stuff'].split()[0])
616 printNicely(red('Sorry I can\'t understand.'))
618 tid
= c
['tweet_dict'][id]
619 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
620 status
= ' '.join(g
['stuff'].split()[1:])
621 # don't include own username for tweet chains
622 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
623 if user
== g
['original_name']:
624 status
= str2u(status
)
626 status
= '@' + user
+ ' ' + str2u(status
)
627 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
634 t
= Twitter(auth
=authen())
636 id = int(g
['stuff'].split()[0])
638 printNicely(red('Sorry I can\'t understand.'))
640 tid
= c
['tweet_dict'][id]
641 original_tweet
= t
.statuses
.show(id=tid
)
642 text
= original_tweet
['text']
643 nick_ary
= [original_tweet
['user']['screen_name']]
644 for user
in list(original_tweet
['entities']['user_mentions']):
645 if user
['screen_name'] not in nick_ary \
646 and user
['screen_name'] != g
['original_name']:
647 nick_ary
.append(user
['screen_name'])
648 status
= ' '.join(g
['stuff'].split()[1:])
649 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
650 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
657 t
= Twitter(auth
=authen())
659 id = int(g
['stuff'].split()[0])
661 printNicely(red('Sorry I can\'t understand.'))
663 tid
= c
['tweet_dict'][id]
664 t
.favorites
.create(_id
=tid
, include_entities
=False)
665 printNicely(green('Favorited.'))
666 draw(t
.statuses
.show(id=tid
))
674 t
= Twitter(auth
=authen())
676 id = int(g
['stuff'].split()[0])
678 printNicely(red('Sorry I can\'t understand.'))
680 tid
= c
['tweet_dict'][id]
681 t
.favorites
.destroy(_id
=tid
)
682 printNicely(green('Okay it\'s unfavorited.'))
683 draw(t
.statuses
.show(id=tid
))
689 Copy url of a tweet to clipboard
691 t
= Twitter(auth
=authen())
693 id = int(g
['stuff'].split()[0])
694 tid
= c
['tweet_dict'][id]
696 printNicely(red('Tweet id is not valid.'))
698 tweet
= t
.statuses
.show(id=tid
)
699 url
= 'https://twitter.com/' + \
700 tweet
['user']['screen_name'] + '/status/' + str(tid
)
702 if platform
.system().lower() == 'darwin':
703 os
.system("echo '%s' | pbcopy" % url
)
704 printNicely(green('Copied tweet\'s url to clipboard.'))
706 printNicely('Direct link: ' + yellow(url
))
713 t
= Twitter(auth
=authen())
715 id = int(g
['stuff'].split()[0])
717 printNicely(red('Sorry I can\'t understand.'))
719 tid
= c
['tweet_dict'][id]
720 t
.statuses
.destroy(id=tid
)
721 printNicely(green('Okay it\'s gone.'))
728 t
= Twitter(auth
=authen())
730 target
= g
['stuff'].split()[0]
731 if target
!= 'image':
733 id = int(g
['stuff'].split()[1])
734 tid
= c
['tweet_dict'][id]
735 tweet
= t
.statuses
.show(id=tid
)
736 media
= tweet
['entities']['media']
738 res
= requests
.get(m
['media_url'])
739 img
= Image
.open(BytesIO(res
.content
))
743 printNicely(red('Sorry I can\'t show this image.'))
750 t
= Twitter(auth
=authen())
752 if not g
['stuff'].isdigit():
754 tid
= c
['tweet_dict'][int(g
['stuff'])]
755 tweet
= t
.statuses
.show(id=tid
)
756 urls
= tweet
['entities']['urls']
758 printNicely(light_magenta('No url here @.@!'))
762 expanded_url
= url
['expanded_url']
763 webbrowser
.open(expanded_url
)
766 printNicely(red('Sorry I can\'t open url in this tweet.'))
773 t
= Twitter(auth
=authen())
774 num
= c
['MESSAGES_DISPLAY']
775 if g
['stuff'].isdigit():
781 inbox
= inbox
+ t
.direct_messages(
784 include_entities
=False,
789 inbox
= inbox
+ t
.direct_messages(
792 include_entities
=False,
796 num
= c
['MESSAGES_DISPLAY']
797 if g
['stuff'].isdigit():
802 sent
= sent
+ t
.direct_messages
.sent(
805 include_entities
=False,
810 sent
= sent
+ t
.direct_messages
.sent(
813 include_entities
=False,
818 uniq_inbox
= list(set(
819 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
821 uniq_sent
= list(set(
822 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
824 for partner
in uniq_inbox
:
825 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
827 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
828 d
[partner
] = inbox_ary
+ sent_ary
829 for partner
in uniq_sent
:
832 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
833 g
['message_threads'] = print_threads(d
)
838 View a thread of message
841 thread_id
= int(g
['stuff'])
843 g
['message_threads'][thread_id
],
848 printNicely(red('No such thread.'))
853 Send a direct message
855 t
= Twitter(auth
=authen())
857 user
= g
['stuff'].split()[0]
858 if user
[0].startswith('@'):
859 content
= ' '.join(g
['stuff'].split()[1:])
860 t
.direct_messages
.new(
861 screen_name
=user
[1:],
864 printNicely(green('Message sent.'))
866 printNicely(red('A name should begin with a \'@\''))
869 printNicely(red('Sorry I can\'t understand.'))
876 t
= Twitter(auth
=authen())
878 id = int(g
['stuff'].split()[0])
880 printNicely(red('Sorry I can\'t understand.'))
881 mid
= c
['message_dict'][id]
882 t
.direct_messages
.destroy(id=mid
)
883 printNicely(green('Message deleted.'))
888 List friends for followers
890 t
= Twitter(auth
=authen())
893 name
= g
['stuff'].split()[1]
894 if name
.startswith('@'):
897 printNicely(red('A name should begin with a \'@\''))
898 raise Exception('Invalid name')
900 name
= g
['original_name']
901 # Get list followers or friends
903 target
= g
['stuff'].split()[0]
905 printNicely(red('Omg some syntax is wrong.'))
908 d
= {'fl': 'followers', 'fr': 'friends'}
912 printNicely('All ' + d
[target
] + ':')
916 while next_cursor
!= 0:
918 list = getattr(t
, d
[target
]).list(
922 include_entities
=False,
925 for u
in list['users']:
931 + cycle_color( u
['name'] ) \
932 + color_func(c
['TWEET']['nick'])( ' @' \
936 next_cursor
= list['next_cursor']
938 # 300 users means 15 calls to the related API. The rate limit is 15
939 # calls per 15mn periods (see Twitter documentation).
940 if ( number_of_users
% 300 == 0 ):
941 printNicely( '(waiting 16mn for rate limits reasons...)' )
944 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
950 t
= Twitter(auth
=authen())
951 screen_name
= g
['stuff'].split()[0]
952 if screen_name
.startswith('@'):
953 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
954 printNicely(green('You are following ' + screen_name
+ ' now!'))
956 printNicely(red('A name should begin with a \'@\''))
963 t
= Twitter(auth
=authen())
964 screen_name
= g
['stuff'].split()[0]
965 if screen_name
.startswith('@'):
966 t
.friendships
.destroy(
967 screen_name
=screen_name
[1:],
968 include_entities
=False)
969 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
971 printNicely(red('A name should begin with a \'@\''))
978 t
= Twitter(auth
=authen())
980 screen_name
= g
['stuff'].split()[0]
982 printNicely(red('A name should be specified. '))
984 if screen_name
.startswith('@'):
986 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
987 if isinstance(rel
, dict):
988 printNicely(green(screen_name
+ ' is muted.'))
989 c
['IGNORE_LIST'] += [screen_name
]
990 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
992 printNicely(red(rel
))
995 printNicely(red('Something is wrong, can not mute now :('))
997 printNicely(red('A name should begin with a \'@\''))
1004 t
= Twitter(auth
=authen())
1006 screen_name
= g
['stuff'].split()[0]
1008 printNicely(red('A name should be specified. '))
1010 if screen_name
.startswith('@'):
1012 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1013 if isinstance(rel
, dict):
1014 printNicely(green(screen_name
+ ' is unmuted.'))
1015 c
['IGNORE_LIST'].remove(screen_name
)
1017 printNicely(red(rel
))
1019 printNicely(red('Maybe you are not muting this person ?'))
1021 printNicely(red('A name should begin with a \'@\''))
1028 # Get dict of muting users
1029 md
= build_mute_dict(dict_data
=True)
1030 printNicely('All: ' + str(len(md
)) + ' people.')
1032 user
= ' ' + cycle_color(md
[name
])
1033 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1035 # Update from Twitter
1036 c
['IGNORE_LIST'] = [n
for n
in md
]
1043 t
= Twitter(auth
=authen())
1044 screen_name
= g
['stuff'].split()[0]
1045 if screen_name
.startswith('@'):
1047 screen_name
=screen_name
[1:],
1048 include_entities
=False,
1050 printNicely(green('You blocked ' + screen_name
+ '.'))
1052 printNicely(red('A name should begin with a \'@\''))
1059 t
= Twitter(auth
=authen())
1060 screen_name
= g
['stuff'].split()[0]
1061 if screen_name
.startswith('@'):
1063 screen_name
=screen_name
[1:],
1064 include_entities
=False,
1066 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1068 printNicely(red('A name should begin with a \'@\''))
1073 Report a user as a spam account
1075 t
= Twitter(auth
=authen())
1076 screen_name
= g
['stuff'].split()[0]
1077 if screen_name
.startswith('@'):
1078 t
.users
.report_spam(
1079 screen_name
=screen_name
[1:])
1080 printNicely(green('You reported ' + screen_name
+ '.'))
1082 printNicely(red('Sorry I can\'t understand.'))
1090 list_name
= raw_input(
1091 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1092 # Get list name and owner
1094 owner
, slug
= list_name
.split('/')
1095 if slug
.startswith('@'):
1100 light_magenta('List name should follow "@owner/list_name" format.'))
1101 raise Exception('Wrong list name')
1104 def check_slug(list_name
):
1108 # Get list name and owner
1110 owner
, slug
= list_name
.split('/')
1111 if slug
.startswith('@'):
1116 light_magenta('List name should follow "@owner/list_name" format.'))
1117 raise Exception('Wrong list name')
1124 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1128 printNicely(light_magenta('You belong to no lists :)'))
1135 owner
, slug
= get_slug()
1136 res
= t
.lists
.statuses(
1138 owner_screen_name
=owner
,
1139 count
=c
['LIST_MAX'],
1140 include_entities
=False)
1141 for tweet
in reversed(res
):
1146 def list_members(t
):
1150 owner
, slug
= get_slug()
1154 while next_cursor
!= 0:
1155 m
= t
.lists
.members(
1157 owner_screen_name
=owner
,
1159 include_entities
=False)
1160 for u
in m
['users']:
1161 rel
[u
['name']] = '@' + u
['screen_name']
1162 next_cursor
= m
['next_cursor']
1163 printNicely('All: ' + str(len(rel
)) + ' members.')
1165 user
= ' ' + cycle_color(name
)
1166 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1170 def list_subscribers(t
):
1174 owner
, slug
= get_slug()
1178 while next_cursor
!= 0:
1179 m
= t
.lists
.subscribers(
1181 owner_screen_name
=owner
,
1183 include_entities
=False)
1184 for u
in m
['users']:
1185 rel
[u
['name']] = '@' + u
['screen_name']
1186 next_cursor
= m
['next_cursor']
1187 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1189 user
= ' ' + cycle_color(name
)
1190 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1196 Add specific user to a list
1198 owner
, slug
= get_slug()
1200 user_name
= raw_input(
1202 'Give me name of the newbie: ',
1204 if user_name
.startswith('@'):
1205 user_name
= user_name
[1:]
1207 t
.lists
.members
.create(
1209 owner_screen_name
=owner
,
1210 screen_name
=user_name
)
1211 printNicely(green('Added.'))
1214 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1219 Remove specific user from a list
1221 owner
, slug
= get_slug()
1223 user_name
= raw_input(
1225 'Give me name of the unlucky one: ',
1227 if user_name
.startswith('@'):
1228 user_name
= user_name
[1:]
1230 t
.lists
.members
.destroy(
1232 owner_screen_name
=owner
,
1233 screen_name
=user_name
)
1234 printNicely(green('Gone.'))
1237 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1240 def list_subscribe(t
):
1244 owner
, slug
= get_slug()
1247 t
.lists
.subscribers
.create(
1249 owner_screen_name
=owner
)
1250 printNicely(green('Done.'))
1254 light_magenta('I\'m sorry you can not subscribe to this list.'))
1257 def list_unsubscribe(t
):
1261 owner
, slug
= get_slug()
1264 t
.lists
.subscribers
.destroy(
1266 owner_screen_name
=owner
)
1267 printNicely(green('Done.'))
1271 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1280 while next_cursor
!= 0:
1281 res
= t
.lists
.ownerships(
1282 screen_name
=g
['original_name'],
1285 next_cursor
= res
['next_cursor']
1289 printNicely(light_magenta('You own no lists :)'))
1296 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1299 'New list\'s mode (public/private): ',
1301 description
= raw_input(
1303 'New list\'s description: ',
1309 description
=description
)
1310 printNicely(green(name
+ ' list is created.'))
1313 printNicely(red('Oops something is wrong with Twitter :('))
1322 'Your list that you want to update: ',
1326 'Update name (leave blank to unchange): ',
1328 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1329 description
= raw_input(light_magenta('Update description: ', rl
=True))
1333 slug
='-'.join(slug
.split()),
1334 owner_screen_name
=g
['original_name'],
1337 description
=description
)
1341 owner_screen_name
=g
['original_name'],
1343 description
=description
)
1344 printNicely(green(slug
+ ' list is updated.'))
1347 printNicely(red('Oops something is wrong with Twitter :('))
1356 'Your list that you want to delete: ',
1360 slug
='-'.join(slug
.split()),
1361 owner_screen_name
=g
['original_name'])
1362 printNicely(green(slug
+ ' list is deleted.'))
1365 printNicely(red('Oops something is wrong with Twitter :('))
1372 t
= Twitter(auth
=authen())
1373 # List all lists or base on action
1375 g
['list_action'] = g
['stuff'].split()[0]
1382 'all_mem': list_members
,
1383 'all_sub': list_subscribers
,
1386 'sub': list_subscribe
,
1387 'unsub': list_unsubscribe
,
1390 'update': list_update
,
1394 return action_ary
[g
['list_action']](t
)
1396 printNicely(red('Please try again.'))
1404 target
= g
['stuff'].split()[0]
1406 args
= parse_arguments()
1408 if g
['stuff'].split()[-1] == '-f':
1409 guide
= 'To ignore an option, just hit Enter key.'
1410 printNicely(light_magenta(guide
))
1411 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1412 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1413 args
.filter = list(filter(None, only
.split(',')))
1414 args
.ignore
= list(filter(None, ignore
.split(',')))
1416 printNicely(red('Sorry, wrong format.'))
1419 g
['stream_stop'] = True
1421 stuff
= g
['stuff'].split()[1]
1426 'public': spawn_public_stream
,
1427 'list': spawn_list_stream
,
1428 'mine': spawn_personal_stream
,
1430 spawn_dict
.get(target
)(args
, stuff
)
1433 printNicely(red('Sorry I can\'t understand.'))
1438 Unix's command `cal`
1441 rel
= os
.popen('cal').read().split('\n')
1444 show_calendar(month
, date
, rel
)
1449 List and change theme
1453 for theme
in g
['themes']:
1454 line
= light_magenta(theme
)
1455 if c
['THEME'] == theme
:
1456 line
= ' ' * 2 + light_yellow('* ') + line
1458 line
= ' ' * 4 + line
1464 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1465 # Redefine decorated_name
1466 g
['decorated_name'] = lambda x
: color_func(
1467 c
['DECORATED_NAME'])(
1469 printNicely(green('Theme changed.'))
1471 printNicely(red('No such theme exists.'))
1476 Browse and change config
1478 all_config
= get_all_config()
1479 g
['stuff'] = g
['stuff'].strip()
1482 for k
in all_config
:
1484 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1486 guide
= 'Detailed explanation can be found at ' + \
1487 color_func(c
['TWEET']['link'])(
1488 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1490 # Print specific config
1491 elif len(g
['stuff'].split()) == 1:
1492 if g
['stuff'] in all_config
:
1495 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1498 printNicely(red('No such config key.'))
1499 # Print specific config's default value
1500 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1501 key
= g
['stuff'].split()[0]
1503 value
= get_default_config(key
)
1504 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1508 printNicely(red('Just can not get the default.'))
1509 # Delete specific config key in config file
1510 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1511 key
= g
['stuff'].split()[0]
1514 printNicely(green('Config key is dropped.'))
1517 printNicely(red('Just can not drop the key.'))
1518 # Set specific config
1519 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1520 key
= g
['stuff'].split()[0]
1521 value
= g
['stuff'].split()[-1]
1522 if key
== 'THEME' and not validate_theme(value
):
1523 printNicely(red('Invalid theme\'s value.'))
1526 set_config(key
, value
)
1527 # Keys that needs to be apply immediately
1529 c
['THEME'] = reload_theme(value
, c
['THEME'])
1530 g
['decorated_name'] = lambda x
: color_func(
1531 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1532 elif key
== 'PREFIX':
1533 g
['PREFIX'] = u2str(emojize(format_prefix(
1534 listname
=g
['listname'],
1535 keyword
=g
['keyword']
1538 printNicely(green('Updated successfully.'))
1541 printNicely(red('Just can not set the key.'))
1543 printNicely(light_magenta('Sorry I can\'t understand.'))
1546 def help_discover():
1551 # Discover the world
1553 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1554 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1555 'You can try ' + light_green('trend US') + ' or ' + \
1556 light_green('trend JP Tokyo') + '.\n'
1557 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1558 light_green('home 7') + ' will show 7 tweets.\n'
1559 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1560 light_green('me 2') + ' will show your last 2 tweets.\n'
1562 light_green('notification') + ' will show your recent notification.\n'
1563 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1564 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1565 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1566 magenta('@mdo') + '.\n'
1567 usage
+= s
* 2 + light_green('view @mdo') + \
1568 ' will show ' + magenta('@mdo') + '\'s home.\n'
1569 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1570 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1571 'Search can be performed with or without hashtag.\n'
1582 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1583 usage
+= s
* 2 + light_green('t oops ') + \
1584 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1586 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1587 light_yellow('[id=12]') + '.\n'
1589 light_green('quote 12 ') + ' will quote the tweet with ' + \
1590 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1591 'the quote will be canceled.\n'
1593 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1594 light_yellow('[id=12]') + '.\n'
1595 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1596 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1597 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1598 light_yellow('oops') + '" to the owner of the tweet with ' + \
1599 light_yellow('[id=12]') + '.\n'
1600 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1601 light_yellow('oops') + '" to all people in the tweet with ' + \
1602 light_yellow('[id=12]') + '.\n'
1604 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1605 light_yellow('[id=12]') + '.\n'
1607 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1608 light_yellow('[id=12]') + '.\n'
1610 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1611 light_yellow('[id=12]') + '.\n'
1613 light_green('del 12 ') + ' will delete tweet with ' + \
1614 light_yellow('[id=12]') + '.\n'
1615 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1616 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1617 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1618 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1619 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1620 light_yellow('[id=12]') + ' in your Pocket list.\n'
1624 def help_messages():
1631 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1632 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1633 light_green('inbox 7') + ' will show newest 7 messages.\n'
1634 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1635 light_yellow('[thread_id=2]') + '.\n'
1636 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1637 magenta('@dtvd88') + '.\n'
1638 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1639 light_yellow('[message_id=5]') + '.\n'
1643 def help_friends_and_followers():
1645 Friends and Followers
1648 # Follower and following
1650 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1652 light_green('ls fl') + \
1653 ' will list all followers (people who are following you).\n'
1655 light_green('ls fr') + \
1656 ' will list all friends (people who you are following).\n'
1657 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1658 magenta('@dtvd88') + '.\n'
1659 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1660 magenta('@dtvd88') + '.\n'
1661 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1662 magenta('@dtvd88') + '.\n'
1663 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1664 magenta('@dtvd88') + '.\n'
1665 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1666 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1667 magenta('@dtvd88') + '.\n'
1668 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1669 magenta('@dtvd88') + '.\n'
1670 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1671 magenta('@dtvd88') + ' as a spam account.\n'
1682 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1683 usage
+= s
* 2 + light_green('list') + \
1684 ' will show all lists you are belong to.\n'
1685 usage
+= s
* 2 + light_green('list home') + \
1686 ' will show timeline of list. You will be asked for list\'s name.\n'
1687 usage
+= s
* 2 + light_green('list all_mem') + \
1688 ' will show list\'s all members.\n'
1689 usage
+= s
* 2 + light_green('list all_sub') + \
1690 ' will show list\'s all subscribers.\n'
1691 usage
+= s
* 2 + light_green('list add') + \
1692 ' will add specific person to a list owned by you.' + \
1693 ' You will be asked for list\'s name and person\'s name.\n'
1694 usage
+= s
* 2 + light_green('list rm') + \
1695 ' will remove specific person from a list owned by you.' + \
1696 ' You will be asked for list\'s name and person\'s name.\n'
1697 usage
+= s
* 2 + light_green('list sub') + \
1698 ' will subscribe you to a specific list.\n'
1699 usage
+= s
* 2 + light_green('list unsub') + \
1700 ' will unsubscribe you from a specific list.\n'
1701 usage
+= s
* 2 + light_green('list own') + \
1702 ' will show all list owned by you.\n'
1703 usage
+= s
* 2 + light_green('list new') + \
1704 ' will create a new list.\n'
1705 usage
+= s
* 2 + light_green('list update') + \
1706 ' will update a list owned by you.\n'
1707 usage
+= s
* 2 + light_green('list del') + \
1708 ' will delete a list owned by you.\n'
1719 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1720 usage
+= s
* 2 + light_green('switch public #AKB') + \
1721 ' will switch to public stream and follow "' + \
1722 light_yellow('AKB') + '" keyword.\n'
1723 usage
+= s
* 2 + light_green('switch mine') + \
1724 ' will switch to your personal stream.\n'
1725 usage
+= s
* 2 + light_green('switch mine -f ') + \
1726 ' will prompt to enter the filter.\n'
1727 usage
+= s
* 3 + light_yellow('Only nicks') + \
1728 ' filter will decide nicks will be INCLUDE ONLY.\n'
1729 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1730 ' filter will decide nicks will be EXCLUDE.\n'
1731 usage
+= s
* 2 + light_green('switch list') + \
1732 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1741 h
, w
= os
.popen('stty size', 'r').read().split()
1744 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1745 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1746 usage
+= s
+ 'You are ' + \
1747 light_yellow('already') + ' on your personal stream.\n'
1748 usage
+= s
+ 'Any update from Twitter will show up ' + \
1749 light_yellow('immediately') + '.\n'
1750 usage
+= s
+ 'In addition, following commands are available right now:\n'
1751 # Twitter help section
1753 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1754 usage
+= s
* 2 + light_green('h discover') + \
1755 ' will show help for discover commands.\n'
1756 usage
+= s
* 2 + light_green('h tweets') + \
1757 ' will show help for tweets commands.\n'
1758 usage
+= s
* 2 + light_green('h messages') + \
1759 ' will show help for messages commands.\n'
1760 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1761 ' will show help for friends and followers commands.\n'
1762 usage
+= s
* 2 + light_green('h list') + \
1763 ' will show help for list commands.\n'
1764 usage
+= s
* 2 + light_green('h stream') + \
1765 ' will show help for stream commands.\n'
1768 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1769 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1770 'will be evaluate by Python interpreter.\n'
1771 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1772 ' for current month.\n'
1775 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1776 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1777 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1778 ' theme immediately.\n'
1779 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1781 light_green('config ASCII_ART') + ' will output current value of ' +\
1782 light_yellow('ASCII_ART') + ' config key.\n'
1784 light_green('config TREND_MAX default') + ' will output default value of ' + \
1785 light_yellow('TREND_MAX') + ' config key.\n'
1787 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1788 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1790 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1791 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1792 light_yellow('True') + '.\n'
1795 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1796 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1797 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1798 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1799 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1800 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1801 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1804 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1805 usage
+= s
+ 'Have fun and hang tight! \n'
1808 'discover': help_discover
,
1809 'tweets': help_tweets
,
1810 'messages': help_messages
,
1811 'friends_and_followers': help_friends_and_followers
,
1813 'stream': help_stream
,
1818 lambda: printNicely(red('No such command.'))
1826 Pause stream display
1829 printNicely(green('Stream is paused'))
1837 printNicely(green('Stream is running back now'))
1853 printNicely(green('See you next time :)'))
1861 Reset prefix of line
1864 if c
.get('USER_JSON_ERROR'):
1865 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1866 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1868 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1871 printNicely(str(eval(g
['cmd'])))
1926 # Handle function set
1981 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1986 Listen to user's input
1991 ['public', 'mine', 'list'], # switch
2000 [], # view_my_tweets
2011 ['image'], # show image
2013 ['fl', 'fr'], # list
2015 [i
for i
in g
['message_threads']], # sent
2040 [key
for key
in dict(get_all_config())], # config
2041 g
['themes'], # theme
2046 'friends_and_followers',
2058 init_interactive_shell(d
)
2065 # Only use PREFIX as a string with raw_input
2066 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2069 # Save cmd to compare with readline buffer
2070 g
['cmd'] = line
.strip()
2071 # Get short cmd to pass to handle function
2073 cmd
= line
.split()[0]
2076 # Lock the semaphore
2078 # Save cmd to global variable and call process
2079 g
['stuff'] = ' '.join(line
.split()[1:])
2080 # Check tweet length
2081 # Process the command
2084 if cmd
in ['switch', 't', 'rt', 'rep']:
2090 except TwitterHTTPError
as e
:
2091 detail_twitter_error(e
)
2094 printNicely(red('OMG something is wrong with Twitter API right now.'))
2096 # Release the semaphore lock
2100 def reconn_notice():
2102 Notice when Hangup or Timeout
2104 guide
= light_magenta('You can use ') + \
2105 light_green('switch') + \
2106 light_magenta(' command to return to your stream.\n')
2107 guide
+= light_magenta('Type ') + \
2108 light_green('h stream') + \
2109 light_magenta(' for more details.')
2111 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2115 def stream(domain
, args
, name
='Rainbow Stream'):
2121 c
['USER_DOMAIN']: name
,
2122 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2123 c
['SITE_DOMAIN']: name
,
2126 ascii_art(art_dict
.get(domain
, name
))
2127 # These arguments are optional:
2129 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2131 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2134 if args
.track_keywords
:
2135 query_args
['track'] = args
.track_keywords
2137 stream
= TwitterStream(
2142 if domain
== c
['USER_DOMAIN']:
2143 tweet_iter
= stream
.user(**query_args
)
2144 elif domain
== c
['SITE_DOMAIN']:
2145 tweet_iter
= stream
.site(**query_args
)
2147 if args
.track_keywords
:
2148 tweet_iter
= stream
.statuses
.filter(**query_args
)
2150 tweet_iter
= stream
.statuses
.sample()
2151 # Block new stream until other one exits
2152 StreamLock
.acquire()
2153 g
['stream_stop'] = False
2154 last_tweet_time
= time
.time()
2155 for tweet
in tweet_iter
:
2157 printNicely('-- None --')
2158 elif tweet
is Timeout
:
2159 # Because the stream check for each 0.3s
2160 # so we shouldn't output anything here
2161 if(g
['stream_stop']):
2162 StreamLock
.release()
2164 elif tweet
is HeartbeatTimeout
:
2165 printNicely('-- Heartbeat Timeout --')
2167 StreamLock
.release()
2169 elif tweet
is Hangup
:
2170 printNicely('-- Hangup --')
2172 StreamLock
.release()
2174 elif tweet
.get('text'):
2175 # Slow down the stream by STREAM_DELAY config key
2176 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2178 last_tweet_time
= time
.time()
2179 # Check the semaphore pause and lock (stream process only)
2187 keyword
=args
.track_keywords
,
2192 # Current readline buffer
2193 current_buffer
= readline
.get_line_buffer().strip()
2194 # There is an unexpected behaviour in MacOSX readline + Python 2:
2195 # after completely delete a word after typing it,
2196 # somehow readline buffer still contains
2197 # the 1st character of that word
2198 if current_buffer
and g
['cmd'] != current_buffer
:
2200 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2202 elif not c
['HIDE_PROMPT']:
2203 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2205 elif tweet
.get('direct_message'):
2206 # Check the semaphore pause and lock (stream process only)
2211 print_message(tweet
['direct_message'])
2212 elif tweet
.get('event'):
2213 c
['events'].append(tweet
)
2215 except TwitterHTTPError
as e
:
2218 magenta('We have connection problem with twitter stream API right now :('))
2219 detail_twitter_error(e
)
2220 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2224 magenta('There seems to be a connection problem.'))
2229 def spawn_public_stream(args
, keyword
=None):
2231 Spawn a new public stream
2233 # Only set keyword if specified
2235 if keyword
[0] == '#':
2236 keyword
= keyword
[1:]
2237 args
.track_keywords
= keyword
2238 g
['keyword'] = keyword
2240 g
['keyword'] = 'Global'
2241 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2244 th
= threading
.Thread(
2253 def spawn_list_stream(args
, stuff
=None):
2255 Spawn a new list stream
2258 owner
, slug
= check_slug(stuff
)
2260 owner
, slug
= get_slug()
2262 # Force python 2 not redraw readline buffer
2263 listname
= '/'.join([owner
, slug
])
2264 # Set the listname variable
2265 # and reset tracked keyword
2266 g
['listname'] = listname
2268 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2269 listname
=g
['listname']
2271 printNicely(light_yellow('getting list members ...'))
2273 t
= Twitter(auth
=authen())
2276 while next_cursor
!= 0:
2277 m
= t
.lists
.members(
2279 owner_screen_name
=owner
,
2281 include_entities
=False)
2282 for u
in m
['users']:
2283 members
.append('@' + u
['screen_name'])
2284 next_cursor
= m
['next_cursor']
2285 printNicely(light_yellow('... done.'))
2286 # Build thread filter array
2287 args
.filter = members
2289 th
= threading
.Thread(
2299 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2301 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2305 def spawn_personal_stream(args
, stuff
=None):
2307 Spawn a new personal stream
2309 # Reset the tracked keyword and listname
2310 g
['keyword'] = g
['listname'] = ''
2312 g
['PREFIX'] = u2str(emojize(format_prefix()))
2314 th
= threading
.Thread(
2319 g
['original_name']))
2329 args
= parse_arguments()
2333 # Twitter API connection problem
2334 except TwitterHTTPError
as e
:
2337 magenta('We have connection problem with twitter REST API right now :('))
2338 detail_twitter_error(e
)
2341 # Proxy connection problem
2342 except (socks
.ProxyConnectionError
, URLError
):
2344 magenta('There seems to be a connection problem.'))
2346 magenta('You might want to check your proxy settings (host, port and type)!'))
2350 # Spawn stream thread
2351 target
= args
.stream
.split()[0]
2352 if target
== 'mine':
2353 spawn_personal_stream(args
)
2356 stuff
= args
.stream
.split()[1]
2360 'public': spawn_public_stream
,
2361 'list': spawn_list_stream
,
2363 spawn_dict
.get(target
)(args
, stuff
)
2365 # Start listen process