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.')
76 help='Use HTTP/SOCKS proxy for network connections.')
81 help='HTTP/SOCKS proxy port (Default: 8080).')
86 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
87 return parser
.parse_args()
90 def proxy_connect(args
):
92 Connect to specified proxy
95 # Setup proxy by monkeypatching the standard lib
96 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
97 socks
.set_default_proxy(
98 socks
.SOCKS5
, args
.proxy_host
,
100 elif args
.proxy_type
.lower() == "http":
101 socks
.set_default_proxy(
102 socks
.HTTP
, args
.proxy_host
,
103 int(args
.proxy_port
))
104 elif args
.proxy_type
.lower() == "socks4":
105 socks
.set_default_proxy(
106 socks
.SOCKS4
, args
.proxy_host
,
107 int(args
.proxy_port
))
110 magenta('Sorry, wrong proxy type specified! Aborting...'))
112 socket
.socket
= socks
.socksocket
117 Authenticate with Twitter OAuth
119 # When using rainbow stream you must authorize.
120 twitter_credential
= os
.environ
.get(
124 '')) + os
.sep
+ '.rainbow_oauth'
125 if not os
.path
.exists(twitter_credential
):
126 oauth_dance('Rainbow Stream',
130 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
140 Authenticate with Pocket OAuth
142 pocket_credential
= os
.environ
.get(
146 '')) + os
.sep
+ '.rainbow_pckt_oauth'
148 if not os
.path
.exists(pocket_credential
):
149 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
150 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
151 webbrowser
.open(auth_url
)
152 printNicely(green("*** Press [ENTER] after authorization ***"))
154 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
155 access_token
= user_credentials
['access_token']
156 f
= open(pocket_credential
, 'w')
157 f
.write(access_token
)
160 with
open(pocket_credential
, 'r') as f
:
161 access_token
= str(f
.readlines()[0])
164 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
167 def build_mute_dict(dict_data
=False):
171 t
= Twitter(auth
=authen())
174 screen_name_list
= []
177 while next_cursor
!= 0:
178 list = t
.mutes
.users
.list(
179 screen_name
=g
['original_name'],
182 include_entities
=False,
184 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
185 name_list
+= [u
['name'] for u
in list['users']]
186 next_cursor
= list['next_cursor']
187 # Return dict or list
189 return dict(zip(screen_name_list
, name_list
))
191 return screen_name_list
196 Save traceback when run in debug mode
199 g
['traceback'].append(traceback
.format_exc())
202 def upgrade_center():
204 Check latest and notify to upgrade
207 current
= pkg_resources
.get_distribution('rainbowstream').version
208 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
209 readme
= requests
.get(url
).text
210 latest
= readme
.split('version = \'')[1].split('\'')[0]
211 if current
!= latest
:
212 notice
= light_magenta('RainbowStream latest version is ')
213 notice
+= light_green(latest
)
214 notice
+= light_magenta(' while your current version is ')
215 notice
+= light_yellow(current
) + '\n'
216 notice
+= light_magenta('You should upgrade with ')
217 notice
+= light_green('pip install -U rainbowstream')
220 notice
= light_yellow('You are running latest version (')
221 notice
+= light_green(current
)
222 notice
+= light_yellow(')')
233 ctrl_c_handler
= lambda signum
, frame
: quit()
234 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
238 t
= Twitter(auth
=authen())
239 credential
= t
.account
.verify_credentials()
240 screen_name
= '@' + credential
['screen_name']
241 name
= credential
['name']
242 c
['original_name'] = g
['original_name'] = screen_name
[1:]
243 g
['listname'] = g
['keyword'] = ''
244 g
['PREFIX'] = u2str(emojize(format_prefix()))
245 g
['full_name'] = name
246 g
['decorated_name'] = lambda x
: color_func(
247 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
249 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
250 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
253 g
['message_threads'] = {}
256 # Debug option default = True
263 # Init tweet dict and message dict
265 c
['message_dict'] = []
267 c
['IMAGE_ON_TERM'] = args
.image_on_term
268 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
269 # Check type of ONLY_LIST and IGNORE_LIST
270 if not isinstance(c
['ONLY_LIST'], list):
271 printNicely(red('ONLY_LIST is not a valid list value.'))
273 if not isinstance(c
['IGNORE_LIST'], list):
274 printNicely(red('IGNORE_LIST is not a valid list value.'))
275 c
['IGNORE_LIST'] = []
277 c
['IGNORE_LIST'] += build_mute_dict()
279 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
286 t
= Twitter(auth
=authen())
287 # Get country and town
289 country
= g
['stuff'].split()[0]
293 town
= g
['stuff'].split()[1]
296 avail
= t
.trends
.available()
299 trends
= t
.trends
.place(_id
=1)[0]['trends']
302 for location
in avail
:
303 # Search for country and Town
305 if location
['countryCode'] == country \
306 and location
['placeType']['name'] == 'Town' \
307 and location
['name'] == town
:
308 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
310 # Search for country only
312 if location
['countryCode'] == country \
313 and location
['placeType']['name'] == 'Country':
314 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
322 t
= Twitter(auth
=authen())
323 num
= c
['HOME_TWEET_NUM']
324 if g
['stuff'].isdigit():
325 num
= int(g
['stuff'])
326 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
336 for e
in c
['events']:
340 printNicely(magenta('Nothing at this time.'))
347 t
= Twitter(auth
=authen())
348 num
= c
['HOME_TWEET_NUM']
349 if g
['stuff'].isdigit():
350 num
= int(g
['stuff'])
351 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
358 Show profile of a specific user
360 t
= Twitter(auth
=authen())
362 screen_name
= g
['stuff'].split()[0]
364 printNicely(red('Sorry I can\'t understand.'))
366 if screen_name
.startswith('@'):
369 screen_name
=screen_name
[1:],
370 include_entities
=False)
374 printNicely(red('No user.'))
376 printNicely(red('A name should begin with a \'@\''))
383 t
= Twitter(auth
=authen())
385 user
= g
['stuff'].split()[0]
387 printNicely(red('Sorry I can\'t understand.'))
391 num
= int(g
['stuff'].split()[1])
393 num
= c
['HOME_TWEET_NUM']
394 for tweet
in reversed(
395 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
399 printNicely(red('A name should begin with a \'@\''))
406 t
= Twitter(auth
=authen())
408 query
= g
['stuff'].strip()
410 printNicely(red('Sorry I can\'t understand.'))
412 type = c
['SEARCH_TYPE']
413 if type not in ['mixed', 'recent', 'popular']:
415 max_record
= c
['SEARCH_MAX_RECORD']
416 count
= min(max_record
, 100)
418 rel
= t
.search
.tweets(
425 printNicely('Newest tweets:')
426 for i
in reversed(xrange(count
)):
427 draw(t
=rel
[i
], keyword
=query
)
430 printNicely(magenta('I\'m afraid there is no result'))
437 t
= Twitter(auth
=authen())
438 t
.statuses
.update(status
=g
['stuff'])
443 Add new link to Pocket along with tweet id
445 if not c
['POCKET_SUPPORT']:
446 printNicely(red('Pocket isn\'t enabled.'))
452 t
= Twitter(auth
=authen())
454 id = int(g
['stuff'].split()[0])
455 tid
= c
['tweet_dict'][id]
457 printNicely(red('Sorry I can\'t understand.'))
460 tweet
= t
.statuses
.show(id=tid
)
462 if len(tweet
['entities']['urls']) > 0:
463 url
= tweet
['entities']['urls'][0]['expanded_url']
465 url
= "https://twitter.com/" + \
466 tweet
['user']['screen_name'] + '/status/' + str(tid
)
470 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
474 printNicely(red('Something is wrong about your Pocket account,'+ \
475 ' please restart Rainbowstream.'))
476 pocket_credential
= os
.environ
.get(
480 '')) + os
.sep
+ '.rainbow_pckt_oauth'
481 if os
.path
.exists(pocket_credential
):
482 os
.remove(pocket_credential
)
485 printNicely(green('Pocketed !'))
493 t
= Twitter(auth
=authen())
495 id = int(g
['stuff'].split()[0])
497 printNicely(red('Sorry I can\'t understand.'))
499 tid
= c
['tweet_dict'][id]
500 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
508 t
= Twitter(auth
=authen())
510 id = int(g
['stuff'].split()[0])
512 printNicely(red('Sorry I can\'t understand.'))
514 tid
= c
['tweet_dict'][id]
515 tweet
= t
.statuses
.show(id=tid
)
517 formater
= format_quote(tweet
)
521 prefix
= light_magenta('Compose your ', rl
=True) + \
522 light_green('#comment: ', rl
=True)
523 comment
= raw_input(prefix
)
525 quote
= comment
.join(formater
.split('#comment'))
526 t
.statuses
.update(status
=quote
)
528 printNicely(light_magenta('No text added.'))
535 t
= Twitter(auth
=authen())
538 id = int(g
['stuff'].split()[0])
540 printNicely(red('Sorry I can\'t understand.'))
542 tid
= c
['tweet_dict'][id]
543 # Get display num if exist
545 num
= int(g
['stuff'].split()[1])
547 num
= c
['RETWEETS_SHOW_NUM']
548 # Get result and display
549 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
551 printNicely(magenta('This tweet has no retweet.'))
553 for tweet
in reversed(rt_ary
):
562 t
= Twitter(auth
=authen())
564 id = int(g
['stuff'].split()[0])
566 printNicely(red('Sorry I can\'t understand.'))
568 tid
= c
['tweet_dict'][id]
569 tweet
= t
.statuses
.show(id=tid
)
570 limit
= c
['CONVERSATION_MAX']
572 thread_ref
.append(tweet
)
573 prev_tid
= tweet
['in_reply_to_status_id']
574 while prev_tid
and limit
:
576 tweet
= t
.statuses
.show(id=prev_tid
)
577 prev_tid
= tweet
['in_reply_to_status_id']
578 thread_ref
.append(tweet
)
580 for tweet
in reversed(thread_ref
):
589 t
= Twitter(auth
=authen())
591 id = int(g
['stuff'].split()[0])
593 printNicely(red('Sorry I can\'t understand.'))
595 tid
= c
['tweet_dict'][id]
596 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
597 status
= ' '.join(g
['stuff'].split()[1:])
598 status
= '@' + user
+ ' ' + str2u(status
)
599 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
606 t
= Twitter(auth
=authen())
608 id = int(g
['stuff'].split()[0])
610 printNicely(red('Sorry I can\'t understand.'))
612 tid
= c
['tweet_dict'][id]
613 original_tweet
= t
.statuses
.show(id=tid
)
614 text
= original_tweet
['text']
615 nick_ary
= [original_tweet
['user']['screen_name']]
616 for user
in list(original_tweet
['entities']['user_mentions']):
617 if user
['screen_name'] not in nick_ary \
618 and user
['screen_name'] != g
['original_name']:
619 nick_ary
.append(user
['screen_name'])
620 status
= ' '.join(g
['stuff'].split()[1:])
621 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
622 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
629 t
= Twitter(auth
=authen())
631 id = int(g
['stuff'].split()[0])
633 printNicely(red('Sorry I can\'t understand.'))
635 tid
= c
['tweet_dict'][id]
636 t
.favorites
.create(_id
=tid
, include_entities
=False)
637 printNicely(green('Favorited.'))
638 draw(t
.statuses
.show(id=tid
))
646 t
= Twitter(auth
=authen())
648 id = int(g
['stuff'].split()[0])
650 printNicely(red('Sorry I can\'t understand.'))
652 tid
= c
['tweet_dict'][id]
653 t
.favorites
.destroy(_id
=tid
)
654 printNicely(green('Okay it\'s unfavorited.'))
655 draw(t
.statuses
.show(id=tid
))
661 Copy url of a tweet to clipboard
663 t
= Twitter(auth
=authen())
665 id = int(g
['stuff'].split()[0])
666 tid
= c
['tweet_dict'][id]
668 printNicely(red('Tweet id is not valid.'))
670 tweet
= t
.statuses
.show(id=tid
)
671 url
= 'https://twitter.com/' + \
672 tweet
['user']['screen_name'] + '/status/' + str(tid
)
674 if platform
.system().lower() == 'darwin':
675 os
.system("echo '%s' | pbcopy" % url
)
676 printNicely(green('Copied tweet\'s url to clipboard.'))
678 printNicely('Direct link: ' + yellow(url
))
685 t
= Twitter(auth
=authen())
687 id = int(g
['stuff'].split()[0])
689 printNicely(red('Sorry I can\'t understand.'))
691 tid
= c
['tweet_dict'][id]
692 t
.statuses
.destroy(id=tid
)
693 printNicely(green('Okay it\'s gone.'))
700 t
= Twitter(auth
=authen())
702 target
= g
['stuff'].split()[0]
703 if target
!= 'image':
705 id = int(g
['stuff'].split()[1])
706 tid
= c
['tweet_dict'][id]
707 tweet
= t
.statuses
.show(id=tid
)
708 media
= tweet
['entities']['media']
710 res
= requests
.get(m
['media_url'])
711 img
= Image
.open(BytesIO(res
.content
))
715 printNicely(red('Sorry I can\'t show this image.'))
722 t
= Twitter(auth
=authen())
724 if not g
['stuff'].isdigit():
726 tid
= c
['tweet_dict'][int(g
['stuff'])]
727 tweet
= t
.statuses
.show(id=tid
)
728 link_prefix
= ('http://', 'https://')
729 link_ary
= [u
for u
in tweet
['text'].split()
730 if u
.startswith(link_prefix
)]
732 printNicely(light_magenta('No url here @.@!'))
734 for link
in link_ary
:
735 webbrowser
.open(link
)
738 printNicely(red('Sorry I can\'t open url in this tweet.'))
745 t
= Twitter(auth
=authen())
746 num
= c
['MESSAGES_DISPLAY']
747 if g
['stuff'].isdigit():
753 inbox
= inbox
+ t
.direct_messages(
756 include_entities
=False,
761 inbox
= inbox
+ t
.direct_messages(
764 include_entities
=False,
768 num
= c
['MESSAGES_DISPLAY']
769 if g
['stuff'].isdigit():
774 sent
= sent
+ t
.direct_messages
.sent(
777 include_entities
=False,
782 sent
= sent
+ t
.direct_messages
.sent(
785 include_entities
=False,
790 uniq_inbox
= list(set(
791 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
793 uniq_sent
= list(set(
794 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
796 for partner
in uniq_inbox
:
797 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
799 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
800 d
[partner
] = inbox_ary
+ sent_ary
801 for partner
in uniq_sent
:
804 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
805 g
['message_threads'] = print_threads(d
)
810 View a thread of message
813 thread_id
= int(g
['stuff'])
815 g
['message_threads'][thread_id
],
820 printNicely(red('No such thread.'))
825 Send a direct message
827 t
= Twitter(auth
=authen())
829 user
= g
['stuff'].split()[0]
830 if user
[0].startswith('@'):
831 content
= ' '.join(g
['stuff'].split()[1:])
832 t
.direct_messages
.new(
833 screen_name
=user
[1:],
836 printNicely(green('Message sent.'))
838 printNicely(red('A name should begin with a \'@\''))
841 printNicely(red('Sorry I can\'t understand.'))
848 t
= Twitter(auth
=authen())
850 id = int(g
['stuff'].split()[0])
852 printNicely(red('Sorry I can\'t understand.'))
853 mid
= c
['message_dict'][id]
854 t
.direct_messages
.destroy(id=mid
)
855 printNicely(green('Message deleted.'))
860 List friends for followers
862 t
= Twitter(auth
=authen())
865 name
= g
['stuff'].split()[1]
866 if name
.startswith('@'):
869 printNicely(red('A name should begin with a \'@\''))
870 raise Exception('Invalid name')
872 name
= g
['original_name']
873 # Get list followers or friends
875 target
= g
['stuff'].split()[0]
877 printNicely(red('Omg some syntax is wrong.'))
880 d
= {'fl': 'followers', 'fr': 'friends'}
884 while next_cursor
!= 0:
885 list = getattr(t
, d
[target
]).list(
889 include_entities
=False,
891 for u
in list['users']:
892 rel
[u
['name']] = '@' + u
['screen_name']
893 next_cursor
= list['next_cursor']
895 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
897 user
= ' ' + cycle_color(name
)
898 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
906 t
= Twitter(auth
=authen())
907 screen_name
= g
['stuff'].split()[0]
908 if screen_name
.startswith('@'):
909 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
910 printNicely(green('You are following ' + screen_name
+ ' now!'))
912 printNicely(red('A name should begin with a \'@\''))
919 t
= Twitter(auth
=authen())
920 screen_name
= g
['stuff'].split()[0]
921 if screen_name
.startswith('@'):
922 t
.friendships
.destroy(
923 screen_name
=screen_name
[1:],
924 include_entities
=False)
925 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
927 printNicely(red('A name should begin with a \'@\''))
934 t
= Twitter(auth
=authen())
936 screen_name
= g
['stuff'].split()[0]
938 printNicely(red('A name should be specified. '))
940 if screen_name
.startswith('@'):
942 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
943 if isinstance(rel
, dict):
944 printNicely(green(screen_name
+ ' is muted.'))
945 c
['IGNORE_LIST'] += [unc(screen_name
)]
946 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
948 printNicely(red(rel
))
951 printNicely(red('Something is wrong, can not mute now :('))
953 printNicely(red('A name should begin with a \'@\''))
960 t
= Twitter(auth
=authen())
962 screen_name
= g
['stuff'].split()[0]
964 printNicely(red('A name should be specified. '))
966 if screen_name
.startswith('@'):
968 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
969 if isinstance(rel
, dict):
970 printNicely(green(screen_name
+ ' is unmuted.'))
971 c
['IGNORE_LIST'].remove(screen_name
)
973 printNicely(red(rel
))
975 printNicely(red('Maybe you are not muting this person ?'))
977 printNicely(red('A name should begin with a \'@\''))
984 # Get dict of muting users
985 md
= build_mute_dict(dict_data
=True)
986 printNicely('All: ' + str(len(md
)) + ' people.')
988 user
= ' ' + cycle_color(md
[name
])
989 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
991 # Update from Twitter
992 c
['IGNORE_LIST'] = [n
for n
in md
]
999 t
= Twitter(auth
=authen())
1000 screen_name
= g
['stuff'].split()[0]
1001 if screen_name
.startswith('@'):
1003 screen_name
=screen_name
[1:],
1004 include_entities
=False,
1006 printNicely(green('You blocked ' + screen_name
+ '.'))
1008 printNicely(red('A name should begin with a \'@\''))
1015 t
= Twitter(auth
=authen())
1016 screen_name
= g
['stuff'].split()[0]
1017 if screen_name
.startswith('@'):
1019 screen_name
=screen_name
[1:],
1020 include_entities
=False,
1022 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1024 printNicely(red('A name should begin with a \'@\''))
1029 Report a user as a spam account
1031 t
= Twitter(auth
=authen())
1032 screen_name
= g
['stuff'].split()[0]
1033 if screen_name
.startswith('@'):
1034 t
.users
.report_spam(
1035 screen_name
=screen_name
[1:])
1036 printNicely(green('You reported ' + screen_name
+ '.'))
1038 printNicely(red('Sorry I can\'t understand.'))
1046 list_name
= raw_input(
1047 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1048 # Get list name and owner
1050 owner
, slug
= list_name
.split('/')
1051 if slug
.startswith('@'):
1056 light_magenta('List name should follow "@owner/list_name" format.'))
1057 raise Exception('Wrong list name')
1060 def check_slug(list_name
):
1064 # Get list name and owner
1066 owner
, slug
= list_name
.split('/')
1067 if slug
.startswith('@'):
1072 light_magenta('List name should follow "@owner/list_name" format.'))
1073 raise Exception('Wrong list name')
1080 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1084 printNicely(light_magenta('You belong to no lists :)'))
1091 owner
, slug
= get_slug()
1092 res
= t
.lists
.statuses(
1094 owner_screen_name
=owner
,
1095 count
=c
['LIST_MAX'],
1096 include_entities
=False)
1097 for tweet
in reversed(res
):
1102 def list_members(t
):
1106 owner
, slug
= get_slug()
1110 while next_cursor
!= 0:
1111 m
= t
.lists
.members(
1113 owner_screen_name
=owner
,
1115 include_entities
=False)
1116 for u
in m
['users']:
1117 rel
[u
['name']] = '@' + u
['screen_name']
1118 next_cursor
= m
['next_cursor']
1119 printNicely('All: ' + str(len(rel
)) + ' members.')
1121 user
= ' ' + cycle_color(name
)
1122 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1126 def list_subscribers(t
):
1130 owner
, slug
= get_slug()
1134 while next_cursor
!= 0:
1135 m
= t
.lists
.subscribers(
1137 owner_screen_name
=owner
,
1139 include_entities
=False)
1140 for u
in m
['users']:
1141 rel
[u
['name']] = '@' + u
['screen_name']
1142 next_cursor
= m
['next_cursor']
1143 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1145 user
= ' ' + cycle_color(name
)
1146 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1152 Add specific user to a list
1154 owner
, slug
= get_slug()
1156 user_name
= raw_input(
1158 'Give me name of the newbie: ',
1160 if user_name
.startswith('@'):
1161 user_name
= user_name
[1:]
1163 t
.lists
.members
.create(
1165 owner_screen_name
=owner
,
1166 screen_name
=user_name
)
1167 printNicely(green('Added.'))
1170 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1175 Remove specific user from a list
1177 owner
, slug
= get_slug()
1179 user_name
= raw_input(
1181 'Give me name of the unlucky one: ',
1183 if user_name
.startswith('@'):
1184 user_name
= user_name
[1:]
1186 t
.lists
.members
.destroy(
1188 owner_screen_name
=owner
,
1189 screen_name
=user_name
)
1190 printNicely(green('Gone.'))
1193 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1196 def list_subscribe(t
):
1200 owner
, slug
= get_slug()
1203 t
.lists
.subscribers
.create(
1205 owner_screen_name
=owner
)
1206 printNicely(green('Done.'))
1210 light_magenta('I\'m sorry you can not subscribe to this list.'))
1213 def list_unsubscribe(t
):
1217 owner
, slug
= get_slug()
1220 t
.lists
.subscribers
.destroy(
1222 owner_screen_name
=owner
)
1223 printNicely(green('Done.'))
1227 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1236 while next_cursor
!= 0:
1237 res
= t
.lists
.ownerships(
1238 screen_name
=g
['original_name'],
1241 next_cursor
= res
['next_cursor']
1245 printNicely(light_magenta('You own no lists :)'))
1252 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1255 'New list\'s mode (public/private): ',
1257 description
= raw_input(
1259 'New list\'s description: ',
1265 description
=description
)
1266 printNicely(green(name
+ ' list is created.'))
1269 printNicely(red('Oops something is wrong with Twitter :('))
1278 'Your list that you want to update: ',
1282 'Update name (leave blank to unchange): ',
1284 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1285 description
= raw_input(light_magenta('Update description: ', rl
=True))
1289 slug
='-'.join(slug
.split()),
1290 owner_screen_name
=g
['original_name'],
1293 description
=description
)
1297 owner_screen_name
=g
['original_name'],
1299 description
=description
)
1300 printNicely(green(slug
+ ' list is updated.'))
1303 printNicely(red('Oops something is wrong with Twitter :('))
1312 'Your list that you want to delete: ',
1316 slug
='-'.join(slug
.split()),
1317 owner_screen_name
=g
['original_name'])
1318 printNicely(green(slug
+ ' list is deleted.'))
1321 printNicely(red('Oops something is wrong with Twitter :('))
1328 t
= Twitter(auth
=authen())
1329 # List all lists or base on action
1331 g
['list_action'] = g
['stuff'].split()[0]
1338 'all_mem': list_members
,
1339 'all_sub': list_subscribers
,
1342 'sub': list_subscribe
,
1343 'unsub': list_unsubscribe
,
1346 'update': list_update
,
1350 return action_ary
[g
['list_action']](t
)
1352 printNicely(red('Please try again.'))
1360 target
= g
['stuff'].split()[0]
1362 args
= parse_arguments()
1364 if g
['stuff'].split()[-1] == '-f':
1365 guide
= 'To ignore an option, just hit Enter key.'
1366 printNicely(light_magenta(guide
))
1367 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1368 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1369 args
.filter = filter(None, only
.split(','))
1370 args
.ignore
= filter(None, ignore
.split(','))
1372 printNicely(red('Sorry, wrong format.'))
1375 g
['stream_stop'] = True
1377 stuff
= g
['stuff'].split()[1]
1382 'public': spawn_public_stream
,
1383 'list': spawn_list_stream
,
1384 'mine': spawn_personal_stream
,
1386 spawn_dict
.get(target
)(args
, stuff
)
1389 printNicely(red('Sorry I can\'t understand.'))
1394 Unix's command `cal`
1397 rel
= os
.popen('cal').read().split('\n')
1400 show_calendar(month
, date
, rel
)
1405 List and change theme
1409 for theme
in g
['themes']:
1410 line
= light_magenta(theme
)
1411 if c
['THEME'] == theme
:
1412 line
= ' ' * 2 + light_yellow('* ') + line
1414 line
= ' ' * 4 + line
1420 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1421 # Redefine decorated_name
1422 g
['decorated_name'] = lambda x
: color_func(
1423 c
['DECORATED_NAME'])(
1425 printNicely(green('Theme changed.'))
1427 printNicely(red('No such theme exists.'))
1432 Browse and change config
1434 all_config
= get_all_config()
1435 g
['stuff'] = g
['stuff'].strip()
1438 for k
in all_config
:
1440 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1442 guide
= 'Detailed explanation can be found at ' + \
1443 color_func(c
['TWEET']['link'])(
1444 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1446 # Print specific config
1447 elif len(g
['stuff'].split()) == 1:
1448 if g
['stuff'] in all_config
:
1451 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1454 printNicely(red('No such config key.'))
1455 # Print specific config's default value
1456 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1457 key
= g
['stuff'].split()[0]
1459 value
= get_default_config(key
)
1460 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1464 printNicely(red('Just can not get the default.'))
1465 # Delete specific config key in config file
1466 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1467 key
= g
['stuff'].split()[0]
1470 printNicely(green('Config key is dropped.'))
1473 printNicely(red('Just can not drop the key.'))
1474 # Set specific config
1475 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1476 key
= g
['stuff'].split()[0]
1477 value
= g
['stuff'].split()[-1]
1478 if key
== 'THEME' and not validate_theme(value
):
1479 printNicely(red('Invalid theme\'s value.'))
1482 set_config(key
, value
)
1483 # Keys that needs to be apply immediately
1485 c
['THEME'] = reload_theme(value
, c
['THEME'])
1486 g
['decorated_name'] = lambda x
: color_func(
1487 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1488 elif key
== 'PREFIX':
1489 g
['PREFIX'] = u2str(emojize(format_prefix(
1490 listname
=g
['listname'],
1491 keyword
=g
['keyword']
1494 printNicely(green('Updated successfully.'))
1497 printNicely(red('Just can not set the key.'))
1499 printNicely(light_magenta('Sorry I can\'t understand.'))
1502 def help_discover():
1507 # Discover the world
1509 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1510 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1511 'You can try ' + light_green('trend US') + ' or ' + \
1512 light_green('trend JP Tokyo') + '.\n'
1513 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1514 light_green('home 7') + ' will show 7 tweets.\n'
1516 light_green('notification') + ' will show your recent notification.\n'
1517 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1518 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1519 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1520 magenta('@mdo') + '.\n'
1521 usage
+= s
* 2 + light_green('view @mdo') + \
1522 ' will show ' + magenta('@mdo') + '\'s home.\n'
1523 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1524 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1525 'Search can be performed with or without hashtag.\n'
1536 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1537 usage
+= s
* 2 + light_green('t oops ') + \
1538 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1540 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1541 light_yellow('[id=12]') + '.\n'
1543 light_green('quote 12 ') + ' will quote the tweet with ' + \
1544 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1545 'the quote will be canceled.\n'
1547 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1548 light_yellow('[id=12]') + '.\n'
1549 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1550 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1551 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1552 light_yellow('oops') + '" to the owner of the tweet with ' + \
1553 light_yellow('[id=12]') + '.\n'
1554 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1555 light_yellow('oops') + '" to all people in the tweet with ' + \
1556 light_yellow('[id=12]') + '.\n'
1558 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1559 light_yellow('[id=12]') + '.\n'
1561 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1562 light_yellow('[id=12]') + '.\n'
1564 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1565 light_yellow('[id=12]') + '.\n'
1567 light_green('del 12 ') + ' will delete tweet with ' + \
1568 light_yellow('[id=12]') + '.\n'
1569 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1570 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1571 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1572 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1573 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1574 light_yellow('[id=12]') + ' in your Pocket list.\n'
1578 def help_messages():
1585 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1586 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1587 light_green('inbox 7') + ' will show newest 7 messages.\n'
1588 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1589 light_yellow('[thread_id=2]') + '.\n'
1590 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1591 magenta('@dtvd88') + '.\n'
1592 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1593 light_yellow('[message_id=5]') + '.\n'
1597 def help_friends_and_followers():
1599 Friends and Followers
1602 # Follower and following
1604 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1606 light_green('ls fl') + \
1607 ' will list all followers (people who are following you).\n'
1609 light_green('ls fr') + \
1610 ' will list all friends (people who you are following).\n'
1611 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1612 magenta('@dtvd88') + '.\n'
1613 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1614 magenta('@dtvd88') + '.\n'
1615 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1616 magenta('@dtvd88') + '.\n'
1617 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1618 magenta('@dtvd88') + '.\n'
1619 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1620 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1621 magenta('@dtvd88') + '.\n'
1622 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1623 magenta('@dtvd88') + '.\n'
1624 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1625 magenta('@dtvd88') + ' as a spam account.\n'
1636 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1637 usage
+= s
* 2 + light_green('list') + \
1638 ' will show all lists you are belong to.\n'
1639 usage
+= s
* 2 + light_green('list home') + \
1640 ' will show timeline of list. You will be asked for list\'s name.\n'
1641 usage
+= s
* 2 + light_green('list all_mem') + \
1642 ' will show list\'s all members.\n'
1643 usage
+= s
* 2 + light_green('list all_sub') + \
1644 ' will show list\'s all subscribers.\n'
1645 usage
+= s
* 2 + light_green('list add') + \
1646 ' will add specific person to a list owned by you.' + \
1647 ' You will be asked for list\'s name and person\'s name.\n'
1648 usage
+= s
* 2 + light_green('list rm') + \
1649 ' will remove specific person from a list owned by you.' + \
1650 ' You will be asked for list\'s name and person\'s name.\n'
1651 usage
+= s
* 2 + light_green('list sub') + \
1652 ' will subscribe you to a specific list.\n'
1653 usage
+= s
* 2 + light_green('list unsub') + \
1654 ' will unsubscribe you from a specific list.\n'
1655 usage
+= s
* 2 + light_green('list own') + \
1656 ' will show all list owned by you.\n'
1657 usage
+= s
* 2 + light_green('list new') + \
1658 ' will create a new list.\n'
1659 usage
+= s
* 2 + light_green('list update') + \
1660 ' will update a list owned by you.\n'
1661 usage
+= s
* 2 + light_green('list del') + \
1662 ' will delete a list owned by you.\n'
1673 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1674 usage
+= s
* 2 + light_green('switch public #AKB') + \
1675 ' will switch to public stream and follow "' + \
1676 light_yellow('AKB') + '" keyword.\n'
1677 usage
+= s
* 2 + light_green('switch mine') + \
1678 ' will switch to your personal stream.\n'
1679 usage
+= s
* 2 + light_green('switch mine -f ') + \
1680 ' will prompt to enter the filter.\n'
1681 usage
+= s
* 3 + light_yellow('Only nicks') + \
1682 ' filter will decide nicks will be INCLUDE ONLY.\n'
1683 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1684 ' filter will decide nicks will be EXCLUDE.\n'
1685 usage
+= s
* 2 + light_green('switch list') + \
1686 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1695 h
, w
= os
.popen('stty size', 'r').read().split()
1698 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1699 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1700 usage
+= s
+ 'You are ' + \
1701 light_yellow('already') + ' on your personal stream.\n'
1702 usage
+= s
+ 'Any update from Twitter will show up ' + \
1703 light_yellow('immediately') + '.\n'
1704 usage
+= s
+ 'In addition, following commands are available right now:\n'
1705 # Twitter help section
1707 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1708 usage
+= s
* 2 + light_green('h discover') + \
1709 ' will show help for discover commands.\n'
1710 usage
+= s
* 2 + light_green('h tweets') + \
1711 ' will show help for tweets commands.\n'
1712 usage
+= s
* 2 + light_green('h messages') + \
1713 ' will show help for messages commands.\n'
1714 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1715 ' will show help for friends and followers commands.\n'
1716 usage
+= s
* 2 + light_green('h list') + \
1717 ' will show help for list commands.\n'
1718 usage
+= s
* 2 + light_green('h stream') + \
1719 ' will show help for stream commands.\n'
1722 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1723 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1724 'will be evaluate by Python interpreter.\n'
1725 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1726 ' for current month.\n'
1729 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1730 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1731 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1732 ' theme immediately.\n'
1733 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1735 light_green('config ASCII_ART') + ' will output current value of ' +\
1736 light_yellow('ASCII_ART') + ' config key.\n'
1738 light_green('config TREND_MAX default') + ' will output default value of ' + \
1739 light_yellow('TREND_MAX') + ' config key.\n'
1741 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1742 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1744 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1745 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1746 light_yellow('True') + '.\n'
1749 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1750 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1751 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1752 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1753 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1754 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1755 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1758 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1759 usage
+= s
+ 'Have fun and hang tight! \n'
1762 'discover': help_discover
,
1763 'tweets': help_tweets
,
1764 'messages': help_messages
,
1765 'friends_and_followers': help_friends_and_followers
,
1767 'stream': help_stream
,
1772 lambda: printNicely(red('No such command.'))
1780 Pause stream display
1783 printNicely(green('Stream is paused'))
1791 printNicely(green('Stream is running back now'))
1807 printNicely(green('See you next time :)'))
1815 Reset prefix of line
1818 if c
.get('USER_JSON_ERROR'):
1819 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1820 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1822 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1825 printNicely(str(eval(g
['cmd'])))
1879 # Handle function set
1933 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1938 Listen to user's input
1943 ['public', 'mine', 'list'], # switch
1962 ['image'], # show image
1964 ['fl', 'fr'], # list
1966 [i
for i
in g
['message_threads']], # sent
1991 [key
for key
in dict(get_all_config())], # config
1992 g
['themes'], # theme
1997 'friends_and_followers',
2009 init_interactive_shell(d
)
2016 # Only use PREFIX as a string with raw_input
2017 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2020 # Save cmd to compare with readline buffer
2021 g
['cmd'] = line
.strip()
2022 # Get short cmd to pass to handle function
2024 cmd
= line
.split()[0]
2027 # Lock the semaphore
2029 # Save cmd to global variable and call process
2030 g
['stuff'] = ' '.join(line
.split()[1:])
2031 # Process the command
2034 if cmd
in ['switch', 't', 'rt', 'rep']:
2038 # Release the semaphore lock
2044 printNicely(red('OMG something is wrong with Twitter right now.'))
2047 def reconn_notice():
2049 Notice when Hangup or Timeout
2051 guide
= light_magenta('You can use ') + \
2052 light_green('switch') + \
2053 light_magenta(' command to return to your stream.\n')
2054 guide
+= light_magenta('Type ') + \
2055 light_green('h stream') + \
2056 light_magenta(' for more details.')
2058 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2062 def stream(domain
, args
, name
='Rainbow Stream'):
2068 c
['USER_DOMAIN']: name
,
2069 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2070 c
['SITE_DOMAIN']: name
,
2073 ascii_art(art_dict
.get(domain
, name
))
2074 # These arguments are optional:
2076 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2078 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2081 if args
.track_keywords
:
2082 query_args
['track'] = args
.track_keywords
2084 stream
= TwitterStream(
2089 if domain
== c
['USER_DOMAIN']:
2090 tweet_iter
= stream
.user(**query_args
)
2091 elif domain
== c
['SITE_DOMAIN']:
2092 tweet_iter
= stream
.site(**query_args
)
2094 if args
.track_keywords
:
2095 tweet_iter
= stream
.statuses
.filter(**query_args
)
2097 tweet_iter
= stream
.statuses
.sample()
2098 # Block new stream until other one exits
2099 StreamLock
.acquire()
2100 g
['stream_stop'] = False
2101 last_tweet_time
= time
.time()
2102 for tweet
in tweet_iter
:
2104 printNicely('-- None --')
2105 elif tweet
is Timeout
:
2106 # Because the stream check for each 0.3s
2107 # so we shouldn't output anything here
2108 if(g
['stream_stop']):
2109 StreamLock
.release()
2111 elif tweet
is HeartbeatTimeout
:
2112 printNicely('-- Heartbeat Timeout --')
2114 StreamLock
.release()
2116 elif tweet
is Hangup
:
2117 printNicely('-- Hangup --')
2119 StreamLock
.release()
2121 elif tweet
.get('text'):
2122 # Slow down the stream by STREAM_DELAY config key
2123 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2125 last_tweet_time
= time
.time()
2126 # Check the semaphore pause and lock (stream process only)
2134 keyword
=args
.track_keywords
,
2139 # Current readline buffer
2140 current_buffer
= readline
.get_line_buffer().strip()
2141 # There is an unexpected behaviour in MacOSX readline + Python 2:
2142 # after completely delete a word after typing it,
2143 # somehow readline buffer still contains
2144 # the 1st character of that word
2145 if current_buffer
and g
['cmd'] != current_buffer
:
2147 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2149 elif not c
['HIDE_PROMPT']:
2150 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2152 elif tweet
.get('direct_message'):
2153 # Check the semaphore pause and lock (stream process only)
2158 print_message(tweet
['direct_message'])
2159 elif tweet
.get('event'):
2160 c
['events'].append(tweet
)
2162 except TwitterHTTPError
as e
:
2165 magenta('We have connection problem with twitter stream API right now :('))
2166 detail_twitter_error(e
)
2167 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2171 magenta('There seems to be a connection problem.'))
2176 def spawn_public_stream(args
, keyword
=None):
2178 Spawn a new public stream
2180 # Only set keyword if specified
2182 if keyword
[0] == '#':
2183 keyword
= keyword
[1:]
2184 args
.track_keywords
= keyword
2185 g
['keyword'] = keyword
2187 g
['keyword'] = 'Global'
2188 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2191 th
= threading
.Thread(
2200 def spawn_list_stream(args
, stuff
=None):
2202 Spawn a new list stream
2205 owner
, slug
= check_slug(stuff
)
2207 owner
, slug
= get_slug()
2209 # Force python 2 not redraw readline buffer
2210 listname
= '/'.join([owner
, slug
])
2211 # Set the listname variable
2212 # and reset tracked keyword
2213 g
['listname'] = listname
2215 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2216 listname
=g
['listname']
2218 printNicely(light_yellow('getting list members ...'))
2220 t
= Twitter(auth
=authen())
2223 while next_cursor
!= 0:
2224 m
= t
.lists
.members(
2226 owner_screen_name
=owner
,
2228 include_entities
=False)
2229 for u
in m
['users']:
2230 members
.append('@' + u
['screen_name'])
2231 next_cursor
= m
['next_cursor']
2232 printNicely(light_yellow('... done.'))
2233 # Build thread filter array
2234 args
.filter = members
2236 th
= threading
.Thread(
2246 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2248 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2252 def spawn_personal_stream(args
, stuff
=None):
2254 Spawn a new personal stream
2256 # Reset the tracked keyword and listname
2257 g
['keyword'] = g
['listname'] = ''
2259 g
['PREFIX'] = u2str(emojize(format_prefix()))
2261 th
= threading
.Thread(
2266 g
['original_name']))
2276 args
= parse_arguments()
2280 # Twitter API connection problem
2281 except TwitterHTTPError
as e
:
2284 magenta('We have connection problem with twitter REST API right now :('))
2285 detail_twitter_error(e
)
2288 # Proxy connection problem
2289 except (socks
.ProxyConnectionError
, URLError
):
2291 magenta('There seems to be a connection problem.'))
2293 magenta('You might want to check your proxy settings (host, port and type)!'))
2297 # Spawn stream thread
2298 target
= args
.stream
.split()[0]
2299 if target
== 'mine' :
2300 spawn_personal_stream(args
)
2303 stuff
= args
.stream
.split()[1]
2307 'public': spawn_public_stream
,
2308 'list': spawn_list_stream
,
2310 spawn_dict
.get(target
)(args
, stuff
)
2312 # Start listen process