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(red('Pocket isn\'t enabled.'))
474 t
= Twitter(auth
=authen())
476 id = int(g
['stuff'].split()[0])
477 tid
= c
['tweet_dict'][id]
479 printNicely(red('Sorry I can\'t understand.'))
482 tweet
= t
.statuses
.show(id=tid
)
484 if len(tweet
['entities']['urls']) > 0:
485 url
= tweet
['entities']['urls'][0]['expanded_url']
487 url
= "https://twitter.com/" + \
488 tweet
['user']['screen_name'] + '/status/' + str(tid
)
492 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
496 printNicely(red('Something is wrong about your Pocket account,'+ \
497 ' please restart Rainbowstream.'))
498 pocket_credential
= os
.environ
.get(
502 '')) + os
.sep
+ '.rainbow_pckt_oauth'
503 if os
.path
.exists(pocket_credential
):
504 os
.remove(pocket_credential
)
507 printNicely(green('Pocketed !'))
515 t
= Twitter(auth
=authen())
517 id = int(g
['stuff'].split()[0])
519 printNicely(red('Sorry I can\'t understand.'))
521 tid
= c
['tweet_dict'][id]
522 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
530 t
= Twitter(auth
=authen())
532 id = int(g
['stuff'].split()[0])
534 printNicely(red('Sorry I can\'t understand.'))
536 tid
= c
['tweet_dict'][id]
537 tweet
= t
.statuses
.show(id=tid
)
539 formater
= format_quote(tweet
)
543 prefix
= light_magenta('Compose your ', rl
=True) + \
544 light_green('#comment: ', rl
=True)
545 comment
= raw_input(prefix
)
547 quote
= comment
.join(formater
.split('#comment'))
548 t
.statuses
.update(status
=quote
)
550 printNicely(light_magenta('No text added.'))
557 t
= Twitter(auth
=authen())
560 id = int(g
['stuff'].split()[0])
562 printNicely(red('Sorry I can\'t understand.'))
564 tid
= c
['tweet_dict'][id]
565 # Get display num if exist
567 num
= int(g
['stuff'].split()[1])
569 num
= c
['RETWEETS_SHOW_NUM']
570 # Get result and display
571 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
573 printNicely(magenta('This tweet has no retweet.'))
575 for tweet
in reversed(rt_ary
):
584 t
= Twitter(auth
=authen())
586 id = int(g
['stuff'].split()[0])
588 printNicely(red('Sorry I can\'t understand.'))
590 tid
= c
['tweet_dict'][id]
591 tweet
= t
.statuses
.show(id=tid
)
592 limit
= c
['CONVERSATION_MAX']
594 thread_ref
.append(tweet
)
595 prev_tid
= tweet
['in_reply_to_status_id']
596 while prev_tid
and limit
:
598 tweet
= t
.statuses
.show(id=prev_tid
)
599 prev_tid
= tweet
['in_reply_to_status_id']
600 thread_ref
.append(tweet
)
602 for tweet
in reversed(thread_ref
):
611 t
= Twitter(auth
=authen())
613 id = int(g
['stuff'].split()[0])
615 printNicely(red('Sorry I can\'t understand.'))
617 tid
= c
['tweet_dict'][id]
618 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
619 status
= ' '.join(g
['stuff'].split()[1:])
620 status
= '@' + user
+ ' ' + str2u(status
)
621 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
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 original_tweet
= t
.statuses
.show(id=tid
)
636 text
= original_tweet
['text']
637 nick_ary
= [original_tweet
['user']['screen_name']]
638 for user
in list(original_tweet
['entities']['user_mentions']):
639 if user
['screen_name'] not in nick_ary \
640 and user
['screen_name'] != g
['original_name']:
641 nick_ary
.append(user
['screen_name'])
642 status
= ' '.join(g
['stuff'].split()[1:])
643 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
644 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
651 t
= Twitter(auth
=authen())
653 id = int(g
['stuff'].split()[0])
655 printNicely(red('Sorry I can\'t understand.'))
657 tid
= c
['tweet_dict'][id]
658 t
.favorites
.create(_id
=tid
, include_entities
=False)
659 printNicely(green('Favorited.'))
660 draw(t
.statuses
.show(id=tid
))
668 t
= Twitter(auth
=authen())
670 id = int(g
['stuff'].split()[0])
672 printNicely(red('Sorry I can\'t understand.'))
674 tid
= c
['tweet_dict'][id]
675 t
.favorites
.destroy(_id
=tid
)
676 printNicely(green('Okay it\'s unfavorited.'))
677 draw(t
.statuses
.show(id=tid
))
683 Copy url of a tweet to clipboard
685 t
= Twitter(auth
=authen())
687 id = int(g
['stuff'].split()[0])
688 tid
= c
['tweet_dict'][id]
690 printNicely(red('Tweet id is not valid.'))
692 tweet
= t
.statuses
.show(id=tid
)
693 url
= 'https://twitter.com/' + \
694 tweet
['user']['screen_name'] + '/status/' + str(tid
)
696 if platform
.system().lower() == 'darwin':
697 os
.system("echo '%s' | pbcopy" % url
)
698 printNicely(green('Copied tweet\'s url to clipboard.'))
700 printNicely('Direct link: ' + yellow(url
))
707 t
= Twitter(auth
=authen())
709 id = int(g
['stuff'].split()[0])
711 printNicely(red('Sorry I can\'t understand.'))
713 tid
= c
['tweet_dict'][id]
714 t
.statuses
.destroy(id=tid
)
715 printNicely(green('Okay it\'s gone.'))
722 t
= Twitter(auth
=authen())
724 target
= g
['stuff'].split()[0]
725 if target
!= 'image':
727 id = int(g
['stuff'].split()[1])
728 tid
= c
['tweet_dict'][id]
729 tweet
= t
.statuses
.show(id=tid
)
730 media
= tweet
['entities']['media']
732 res
= requests
.get(m
['media_url'])
733 img
= Image
.open(BytesIO(res
.content
))
737 printNicely(red('Sorry I can\'t show this image.'))
744 t
= Twitter(auth
=authen())
746 if not g
['stuff'].isdigit():
748 tid
= c
['tweet_dict'][int(g
['stuff'])]
749 tweet
= t
.statuses
.show(id=tid
)
750 urls
= tweet
['entities']['urls']
752 printNicely(light_magenta('No url here @.@!'))
756 expanded_url
= url
['expanded_url']
757 webbrowser
.open(expanded_url
)
760 printNicely(red('Sorry I can\'t open url in this tweet.'))
767 t
= Twitter(auth
=authen())
768 num
= c
['MESSAGES_DISPLAY']
769 if g
['stuff'].isdigit():
775 inbox
= inbox
+ t
.direct_messages(
778 include_entities
=False,
783 inbox
= inbox
+ t
.direct_messages(
786 include_entities
=False,
790 num
= c
['MESSAGES_DISPLAY']
791 if g
['stuff'].isdigit():
796 sent
= sent
+ t
.direct_messages
.sent(
799 include_entities
=False,
804 sent
= sent
+ t
.direct_messages
.sent(
807 include_entities
=False,
812 uniq_inbox
= list(set(
813 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
815 uniq_sent
= list(set(
816 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
818 for partner
in uniq_inbox
:
819 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
821 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
822 d
[partner
] = inbox_ary
+ sent_ary
823 for partner
in uniq_sent
:
826 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
827 g
['message_threads'] = print_threads(d
)
832 View a thread of message
835 thread_id
= int(g
['stuff'])
837 g
['message_threads'][thread_id
],
842 printNicely(red('No such thread.'))
847 Send a direct message
849 t
= Twitter(auth
=authen())
851 user
= g
['stuff'].split()[0]
852 if user
[0].startswith('@'):
853 content
= ' '.join(g
['stuff'].split()[1:])
854 t
.direct_messages
.new(
855 screen_name
=user
[1:],
858 printNicely(green('Message sent.'))
860 printNicely(red('A name should begin with a \'@\''))
863 printNicely(red('Sorry I can\'t understand.'))
870 t
= Twitter(auth
=authen())
872 id = int(g
['stuff'].split()[0])
874 printNicely(red('Sorry I can\'t understand.'))
875 mid
= c
['message_dict'][id]
876 t
.direct_messages
.destroy(id=mid
)
877 printNicely(green('Message deleted.'))
882 List friends for followers
884 t
= Twitter(auth
=authen())
887 name
= g
['stuff'].split()[1]
888 if name
.startswith('@'):
891 printNicely(red('A name should begin with a \'@\''))
892 raise Exception('Invalid name')
894 name
= g
['original_name']
895 # Get list followers or friends
897 target
= g
['stuff'].split()[0]
899 printNicely(red('Omg some syntax is wrong.'))
902 d
= {'fl': 'followers', 'fr': 'friends'}
906 while next_cursor
!= 0:
907 list = getattr(t
, d
[target
]).list(
911 include_entities
=False,
913 for u
in list['users']:
914 rel
[u
['name']] = '@' + u
['screen_name']
915 next_cursor
= list['next_cursor']
917 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
919 user
= ' ' + cycle_color(name
)
920 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
928 t
= Twitter(auth
=authen())
929 screen_name
= g
['stuff'].split()[0]
930 if screen_name
.startswith('@'):
931 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
932 printNicely(green('You are following ' + screen_name
+ ' now!'))
934 printNicely(red('A name should begin with a \'@\''))
941 t
= Twitter(auth
=authen())
942 screen_name
= g
['stuff'].split()[0]
943 if screen_name
.startswith('@'):
944 t
.friendships
.destroy(
945 screen_name
=screen_name
[1:],
946 include_entities
=False)
947 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
949 printNicely(red('A name should begin with a \'@\''))
956 t
= Twitter(auth
=authen())
958 screen_name
= g
['stuff'].split()[0]
960 printNicely(red('A name should be specified. '))
962 if screen_name
.startswith('@'):
964 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
965 if isinstance(rel
, dict):
966 printNicely(green(screen_name
+ ' is muted.'))
967 c
['IGNORE_LIST'] += [screen_name
]
968 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
970 printNicely(red(rel
))
973 printNicely(red('Something is wrong, can not mute now :('))
975 printNicely(red('A name should begin with a \'@\''))
982 t
= Twitter(auth
=authen())
984 screen_name
= g
['stuff'].split()[0]
986 printNicely(red('A name should be specified. '))
988 if screen_name
.startswith('@'):
990 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
991 if isinstance(rel
, dict):
992 printNicely(green(screen_name
+ ' is unmuted.'))
993 c
['IGNORE_LIST'].remove(screen_name
)
995 printNicely(red(rel
))
997 printNicely(red('Maybe you are not muting this person ?'))
999 printNicely(red('A name should begin with a \'@\''))
1006 # Get dict of muting users
1007 md
= build_mute_dict(dict_data
=True)
1008 printNicely('All: ' + str(len(md
)) + ' people.')
1010 user
= ' ' + cycle_color(md
[name
])
1011 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1013 # Update from Twitter
1014 c
['IGNORE_LIST'] = [n
for n
in md
]
1021 t
= Twitter(auth
=authen())
1022 screen_name
= g
['stuff'].split()[0]
1023 if screen_name
.startswith('@'):
1025 screen_name
=screen_name
[1:],
1026 include_entities
=False,
1028 printNicely(green('You blocked ' + screen_name
+ '.'))
1030 printNicely(red('A name should begin with a \'@\''))
1037 t
= Twitter(auth
=authen())
1038 screen_name
= g
['stuff'].split()[0]
1039 if screen_name
.startswith('@'):
1041 screen_name
=screen_name
[1:],
1042 include_entities
=False,
1044 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1046 printNicely(red('A name should begin with a \'@\''))
1051 Report a user as a spam account
1053 t
= Twitter(auth
=authen())
1054 screen_name
= g
['stuff'].split()[0]
1055 if screen_name
.startswith('@'):
1056 t
.users
.report_spam(
1057 screen_name
=screen_name
[1:])
1058 printNicely(green('You reported ' + screen_name
+ '.'))
1060 printNicely(red('Sorry I can\'t understand.'))
1068 list_name
= raw_input(
1069 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1070 # Get list name and owner
1072 owner
, slug
= list_name
.split('/')
1073 if slug
.startswith('@'):
1078 light_magenta('List name should follow "@owner/list_name" format.'))
1079 raise Exception('Wrong list name')
1082 def check_slug(list_name
):
1086 # Get list name and owner
1088 owner
, slug
= list_name
.split('/')
1089 if slug
.startswith('@'):
1094 light_magenta('List name should follow "@owner/list_name" format.'))
1095 raise Exception('Wrong list name')
1102 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1106 printNicely(light_magenta('You belong to no lists :)'))
1113 owner
, slug
= get_slug()
1114 res
= t
.lists
.statuses(
1116 owner_screen_name
=owner
,
1117 count
=c
['LIST_MAX'],
1118 include_entities
=False)
1119 for tweet
in reversed(res
):
1124 def list_members(t
):
1128 owner
, slug
= get_slug()
1132 while next_cursor
!= 0:
1133 m
= t
.lists
.members(
1135 owner_screen_name
=owner
,
1137 include_entities
=False)
1138 for u
in m
['users']:
1139 rel
[u
['name']] = '@' + u
['screen_name']
1140 next_cursor
= m
['next_cursor']
1141 printNicely('All: ' + str(len(rel
)) + ' members.')
1143 user
= ' ' + cycle_color(name
)
1144 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1148 def list_subscribers(t
):
1152 owner
, slug
= get_slug()
1156 while next_cursor
!= 0:
1157 m
= t
.lists
.subscribers(
1159 owner_screen_name
=owner
,
1161 include_entities
=False)
1162 for u
in m
['users']:
1163 rel
[u
['name']] = '@' + u
['screen_name']
1164 next_cursor
= m
['next_cursor']
1165 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1167 user
= ' ' + cycle_color(name
)
1168 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1174 Add specific user to a list
1176 owner
, slug
= get_slug()
1178 user_name
= raw_input(
1180 'Give me name of the newbie: ',
1182 if user_name
.startswith('@'):
1183 user_name
= user_name
[1:]
1185 t
.lists
.members
.create(
1187 owner_screen_name
=owner
,
1188 screen_name
=user_name
)
1189 printNicely(green('Added.'))
1192 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1197 Remove specific user from a list
1199 owner
, slug
= get_slug()
1201 user_name
= raw_input(
1203 'Give me name of the unlucky one: ',
1205 if user_name
.startswith('@'):
1206 user_name
= user_name
[1:]
1208 t
.lists
.members
.destroy(
1210 owner_screen_name
=owner
,
1211 screen_name
=user_name
)
1212 printNicely(green('Gone.'))
1215 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1218 def list_subscribe(t
):
1222 owner
, slug
= get_slug()
1225 t
.lists
.subscribers
.create(
1227 owner_screen_name
=owner
)
1228 printNicely(green('Done.'))
1232 light_magenta('I\'m sorry you can not subscribe to this list.'))
1235 def list_unsubscribe(t
):
1239 owner
, slug
= get_slug()
1242 t
.lists
.subscribers
.destroy(
1244 owner_screen_name
=owner
)
1245 printNicely(green('Done.'))
1249 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1258 while next_cursor
!= 0:
1259 res
= t
.lists
.ownerships(
1260 screen_name
=g
['original_name'],
1263 next_cursor
= res
['next_cursor']
1267 printNicely(light_magenta('You own no lists :)'))
1274 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1277 'New list\'s mode (public/private): ',
1279 description
= raw_input(
1281 'New list\'s description: ',
1287 description
=description
)
1288 printNicely(green(name
+ ' list is created.'))
1291 printNicely(red('Oops something is wrong with Twitter :('))
1300 'Your list that you want to update: ',
1304 'Update name (leave blank to unchange): ',
1306 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1307 description
= raw_input(light_magenta('Update description: ', rl
=True))
1311 slug
='-'.join(slug
.split()),
1312 owner_screen_name
=g
['original_name'],
1315 description
=description
)
1319 owner_screen_name
=g
['original_name'],
1321 description
=description
)
1322 printNicely(green(slug
+ ' list is updated.'))
1325 printNicely(red('Oops something is wrong with Twitter :('))
1334 'Your list that you want to delete: ',
1338 slug
='-'.join(slug
.split()),
1339 owner_screen_name
=g
['original_name'])
1340 printNicely(green(slug
+ ' list is deleted.'))
1343 printNicely(red('Oops something is wrong with Twitter :('))
1350 t
= Twitter(auth
=authen())
1351 # List all lists or base on action
1353 g
['list_action'] = g
['stuff'].split()[0]
1360 'all_mem': list_members
,
1361 'all_sub': list_subscribers
,
1364 'sub': list_subscribe
,
1365 'unsub': list_unsubscribe
,
1368 'update': list_update
,
1372 return action_ary
[g
['list_action']](t
)
1374 printNicely(red('Please try again.'))
1382 target
= g
['stuff'].split()[0]
1384 args
= parse_arguments()
1386 if g
['stuff'].split()[-1] == '-f':
1387 guide
= 'To ignore an option, just hit Enter key.'
1388 printNicely(light_magenta(guide
))
1389 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1390 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1391 args
.filter = filter(None, only
.split(','))
1392 args
.ignore
= filter(None, ignore
.split(','))
1394 printNicely(red('Sorry, wrong format.'))
1397 g
['stream_stop'] = True
1399 stuff
= g
['stuff'].split()[1]
1404 'public': spawn_public_stream
,
1405 'list': spawn_list_stream
,
1406 'mine': spawn_personal_stream
,
1408 spawn_dict
.get(target
)(args
, stuff
)
1411 printNicely(red('Sorry I can\'t understand.'))
1416 Unix's command `cal`
1419 rel
= os
.popen('cal').read().split('\n')
1422 show_calendar(month
, date
, rel
)
1427 List and change theme
1431 for theme
in g
['themes']:
1432 line
= light_magenta(theme
)
1433 if c
['THEME'] == theme
:
1434 line
= ' ' * 2 + light_yellow('* ') + line
1436 line
= ' ' * 4 + line
1442 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1443 # Redefine decorated_name
1444 g
['decorated_name'] = lambda x
: color_func(
1445 c
['DECORATED_NAME'])(
1447 printNicely(green('Theme changed.'))
1449 printNicely(red('No such theme exists.'))
1454 Browse and change config
1456 all_config
= get_all_config()
1457 g
['stuff'] = g
['stuff'].strip()
1460 for k
in all_config
:
1462 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1464 guide
= 'Detailed explanation can be found at ' + \
1465 color_func(c
['TWEET']['link'])(
1466 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1468 # Print specific config
1469 elif len(g
['stuff'].split()) == 1:
1470 if g
['stuff'] in all_config
:
1473 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1476 printNicely(red('No such config key.'))
1477 # Print specific config's default value
1478 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1479 key
= g
['stuff'].split()[0]
1481 value
= get_default_config(key
)
1482 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1486 printNicely(red('Just can not get the default.'))
1487 # Delete specific config key in config file
1488 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1489 key
= g
['stuff'].split()[0]
1492 printNicely(green('Config key is dropped.'))
1495 printNicely(red('Just can not drop the key.'))
1496 # Set specific config
1497 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1498 key
= g
['stuff'].split()[0]
1499 value
= g
['stuff'].split()[-1]
1500 if key
== 'THEME' and not validate_theme(value
):
1501 printNicely(red('Invalid theme\'s value.'))
1504 set_config(key
, value
)
1505 # Keys that needs to be apply immediately
1507 c
['THEME'] = reload_theme(value
, c
['THEME'])
1508 g
['decorated_name'] = lambda x
: color_func(
1509 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1510 elif key
== 'PREFIX':
1511 g
['PREFIX'] = u2str(emojize(format_prefix(
1512 listname
=g
['listname'],
1513 keyword
=g
['keyword']
1516 printNicely(green('Updated successfully.'))
1519 printNicely(red('Just can not set the key.'))
1521 printNicely(light_magenta('Sorry I can\'t understand.'))
1524 def help_discover():
1529 # Discover the world
1531 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1532 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1533 'You can try ' + light_green('trend US') + ' or ' + \
1534 light_green('trend JP Tokyo') + '.\n'
1535 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1536 light_green('home 7') + ' will show 7 tweets.\n'
1537 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1538 light_green('me 2') + ' will show your last 2 tweets.\n'
1540 light_green('notification') + ' will show your recent notification.\n'
1541 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1542 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1543 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1544 magenta('@mdo') + '.\n'
1545 usage
+= s
* 2 + light_green('view @mdo') + \
1546 ' will show ' + magenta('@mdo') + '\'s home.\n'
1547 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1548 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1549 'Search can be performed with or without hashtag.\n'
1560 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1561 usage
+= s
* 2 + light_green('t oops ') + \
1562 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1564 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1565 light_yellow('[id=12]') + '.\n'
1567 light_green('quote 12 ') + ' will quote the tweet with ' + \
1568 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1569 'the quote will be canceled.\n'
1571 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1572 light_yellow('[id=12]') + '.\n'
1573 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1574 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1575 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1576 light_yellow('oops') + '" to the owner of the tweet with ' + \
1577 light_yellow('[id=12]') + '.\n'
1578 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1579 light_yellow('oops') + '" to all people in the tweet with ' + \
1580 light_yellow('[id=12]') + '.\n'
1582 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1583 light_yellow('[id=12]') + '.\n'
1585 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1586 light_yellow('[id=12]') + '.\n'
1588 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1589 light_yellow('[id=12]') + '.\n'
1591 light_green('del 12 ') + ' will delete tweet with ' + \
1592 light_yellow('[id=12]') + '.\n'
1593 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1594 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1595 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1596 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1597 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1598 light_yellow('[id=12]') + ' in your Pocket list.\n'
1602 def help_messages():
1609 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1610 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1611 light_green('inbox 7') + ' will show newest 7 messages.\n'
1612 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1613 light_yellow('[thread_id=2]') + '.\n'
1614 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1615 magenta('@dtvd88') + '.\n'
1616 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1617 light_yellow('[message_id=5]') + '.\n'
1621 def help_friends_and_followers():
1623 Friends and Followers
1626 # Follower and following
1628 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1630 light_green('ls fl') + \
1631 ' will list all followers (people who are following you).\n'
1633 light_green('ls fr') + \
1634 ' will list all friends (people who you are following).\n'
1635 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1636 magenta('@dtvd88') + '.\n'
1637 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1638 magenta('@dtvd88') + '.\n'
1639 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1640 magenta('@dtvd88') + '.\n'
1641 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1642 magenta('@dtvd88') + '.\n'
1643 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1644 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1645 magenta('@dtvd88') + '.\n'
1646 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1647 magenta('@dtvd88') + '.\n'
1648 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1649 magenta('@dtvd88') + ' as a spam account.\n'
1660 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1661 usage
+= s
* 2 + light_green('list') + \
1662 ' will show all lists you are belong to.\n'
1663 usage
+= s
* 2 + light_green('list home') + \
1664 ' will show timeline of list. You will be asked for list\'s name.\n'
1665 usage
+= s
* 2 + light_green('list all_mem') + \
1666 ' will show list\'s all members.\n'
1667 usage
+= s
* 2 + light_green('list all_sub') + \
1668 ' will show list\'s all subscribers.\n'
1669 usage
+= s
* 2 + light_green('list add') + \
1670 ' will add specific person to a list owned by you.' + \
1671 ' You will be asked for list\'s name and person\'s name.\n'
1672 usage
+= s
* 2 + light_green('list rm') + \
1673 ' will remove specific person from a list owned by you.' + \
1674 ' You will be asked for list\'s name and person\'s name.\n'
1675 usage
+= s
* 2 + light_green('list sub') + \
1676 ' will subscribe you to a specific list.\n'
1677 usage
+= s
* 2 + light_green('list unsub') + \
1678 ' will unsubscribe you from a specific list.\n'
1679 usage
+= s
* 2 + light_green('list own') + \
1680 ' will show all list owned by you.\n'
1681 usage
+= s
* 2 + light_green('list new') + \
1682 ' will create a new list.\n'
1683 usage
+= s
* 2 + light_green('list update') + \
1684 ' will update a list owned by you.\n'
1685 usage
+= s
* 2 + light_green('list del') + \
1686 ' will delete a list owned by you.\n'
1697 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1698 usage
+= s
* 2 + light_green('switch public #AKB') + \
1699 ' will switch to public stream and follow "' + \
1700 light_yellow('AKB') + '" keyword.\n'
1701 usage
+= s
* 2 + light_green('switch mine') + \
1702 ' will switch to your personal stream.\n'
1703 usage
+= s
* 2 + light_green('switch mine -f ') + \
1704 ' will prompt to enter the filter.\n'
1705 usage
+= s
* 3 + light_yellow('Only nicks') + \
1706 ' filter will decide nicks will be INCLUDE ONLY.\n'
1707 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1708 ' filter will decide nicks will be EXCLUDE.\n'
1709 usage
+= s
* 2 + light_green('switch list') + \
1710 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1719 h
, w
= os
.popen('stty size', 'r').read().split()
1722 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1723 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1724 usage
+= s
+ 'You are ' + \
1725 light_yellow('already') + ' on your personal stream.\n'
1726 usage
+= s
+ 'Any update from Twitter will show up ' + \
1727 light_yellow('immediately') + '.\n'
1728 usage
+= s
+ 'In addition, following commands are available right now:\n'
1729 # Twitter help section
1731 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1732 usage
+= s
* 2 + light_green('h discover') + \
1733 ' will show help for discover commands.\n'
1734 usage
+= s
* 2 + light_green('h tweets') + \
1735 ' will show help for tweets commands.\n'
1736 usage
+= s
* 2 + light_green('h messages') + \
1737 ' will show help for messages commands.\n'
1738 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1739 ' will show help for friends and followers commands.\n'
1740 usage
+= s
* 2 + light_green('h list') + \
1741 ' will show help for list commands.\n'
1742 usage
+= s
* 2 + light_green('h stream') + \
1743 ' will show help for stream commands.\n'
1746 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1747 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1748 'will be evaluate by Python interpreter.\n'
1749 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1750 ' for current month.\n'
1753 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1754 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1755 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1756 ' theme immediately.\n'
1757 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1759 light_green('config ASCII_ART') + ' will output current value of ' +\
1760 light_yellow('ASCII_ART') + ' config key.\n'
1762 light_green('config TREND_MAX default') + ' will output default value of ' + \
1763 light_yellow('TREND_MAX') + ' config key.\n'
1765 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1766 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1768 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1769 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1770 light_yellow('True') + '.\n'
1773 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1774 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1775 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1776 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1777 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1778 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1779 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1782 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1783 usage
+= s
+ 'Have fun and hang tight! \n'
1786 'discover': help_discover
,
1787 'tweets': help_tweets
,
1788 'messages': help_messages
,
1789 'friends_and_followers': help_friends_and_followers
,
1791 'stream': help_stream
,
1796 lambda: printNicely(red('No such command.'))
1804 Pause stream display
1807 printNicely(green('Stream is paused'))
1815 printNicely(green('Stream is running back now'))
1831 printNicely(green('See you next time :)'))
1839 Reset prefix of line
1842 if c
.get('USER_JSON_ERROR'):
1843 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1844 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1846 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1849 printNicely(str(eval(g
['cmd'])))
1904 # Handle function set
1959 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1964 Listen to user's input
1969 ['public', 'mine', 'list'], # switch
1978 [], # view_my_tweets
1989 ['image'], # show image
1991 ['fl', 'fr'], # list
1993 [i
for i
in g
['message_threads']], # sent
2018 [key
for key
in dict(get_all_config())], # config
2019 g
['themes'], # theme
2024 'friends_and_followers',
2036 init_interactive_shell(d
)
2043 # Only use PREFIX as a string with raw_input
2044 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2047 # Save cmd to compare with readline buffer
2048 g
['cmd'] = line
.strip()
2049 # Get short cmd to pass to handle function
2051 cmd
= line
.split()[0]
2054 # Lock the semaphore
2056 # Save cmd to global variable and call process
2057 g
['stuff'] = ' '.join(line
.split()[1:])
2058 # Check tweet length
2059 # Process the command
2062 if cmd
in ['switch', 't', 'rt', 'rep']:
2068 except TwitterHTTPError
as e
:
2069 detail_twitter_error(e
)
2072 printNicely(red('OMG something is wrong with Twitter API right now.'))
2074 # Release the semaphore lock
2078 def reconn_notice():
2080 Notice when Hangup or Timeout
2082 guide
= light_magenta('You can use ') + \
2083 light_green('switch') + \
2084 light_magenta(' command to return to your stream.\n')
2085 guide
+= light_magenta('Type ') + \
2086 light_green('h stream') + \
2087 light_magenta(' for more details.')
2089 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2093 def stream(domain
, args
, name
='Rainbow Stream'):
2099 c
['USER_DOMAIN']: name
,
2100 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2101 c
['SITE_DOMAIN']: name
,
2104 ascii_art(art_dict
.get(domain
, name
))
2105 # These arguments are optional:
2107 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2109 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2112 if args
.track_keywords
:
2113 query_args
['track'] = args
.track_keywords
2115 stream
= TwitterStream(
2120 if domain
== c
['USER_DOMAIN']:
2121 tweet_iter
= stream
.user(**query_args
)
2122 elif domain
== c
['SITE_DOMAIN']:
2123 tweet_iter
= stream
.site(**query_args
)
2125 if args
.track_keywords
:
2126 tweet_iter
= stream
.statuses
.filter(**query_args
)
2128 tweet_iter
= stream
.statuses
.sample()
2129 # Block new stream until other one exits
2130 StreamLock
.acquire()
2131 g
['stream_stop'] = False
2132 last_tweet_time
= time
.time()
2133 for tweet
in tweet_iter
:
2135 printNicely('-- None --')
2136 elif tweet
is Timeout
:
2137 # Because the stream check for each 0.3s
2138 # so we shouldn't output anything here
2139 if(g
['stream_stop']):
2140 StreamLock
.release()
2142 elif tweet
is HeartbeatTimeout
:
2143 printNicely('-- Heartbeat Timeout --')
2145 StreamLock
.release()
2147 elif tweet
is Hangup
:
2148 printNicely('-- Hangup --')
2150 StreamLock
.release()
2152 elif tweet
.get('text'):
2153 # Slow down the stream by STREAM_DELAY config key
2154 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2156 last_tweet_time
= time
.time()
2157 # Check the semaphore pause and lock (stream process only)
2165 keyword
=args
.track_keywords
,
2170 # Current readline buffer
2171 current_buffer
= readline
.get_line_buffer().strip()
2172 # There is an unexpected behaviour in MacOSX readline + Python 2:
2173 # after completely delete a word after typing it,
2174 # somehow readline buffer still contains
2175 # the 1st character of that word
2176 if current_buffer
and g
['cmd'] != current_buffer
:
2178 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2180 elif not c
['HIDE_PROMPT']:
2181 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2183 elif tweet
.get('direct_message'):
2184 # Check the semaphore pause and lock (stream process only)
2189 print_message(tweet
['direct_message'])
2190 elif tweet
.get('event'):
2191 c
['events'].append(tweet
)
2193 except TwitterHTTPError
as e
:
2196 magenta('We have connection problem with twitter stream API right now :('))
2197 detail_twitter_error(e
)
2198 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2202 magenta('There seems to be a connection problem.'))
2207 def spawn_public_stream(args
, keyword
=None):
2209 Spawn a new public stream
2211 # Only set keyword if specified
2213 if keyword
[0] == '#':
2214 keyword
= keyword
[1:]
2215 args
.track_keywords
= keyword
2216 g
['keyword'] = keyword
2218 g
['keyword'] = 'Global'
2219 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2222 th
= threading
.Thread(
2231 def spawn_list_stream(args
, stuff
=None):
2233 Spawn a new list stream
2236 owner
, slug
= check_slug(stuff
)
2238 owner
, slug
= get_slug()
2240 # Force python 2 not redraw readline buffer
2241 listname
= '/'.join([owner
, slug
])
2242 # Set the listname variable
2243 # and reset tracked keyword
2244 g
['listname'] = listname
2246 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2247 listname
=g
['listname']
2249 printNicely(light_yellow('getting list members ...'))
2251 t
= Twitter(auth
=authen())
2254 while next_cursor
!= 0:
2255 m
= t
.lists
.members(
2257 owner_screen_name
=owner
,
2259 include_entities
=False)
2260 for u
in m
['users']:
2261 members
.append('@' + u
['screen_name'])
2262 next_cursor
= m
['next_cursor']
2263 printNicely(light_yellow('... done.'))
2264 # Build thread filter array
2265 args
.filter = members
2267 th
= threading
.Thread(
2277 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2279 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2283 def spawn_personal_stream(args
, stuff
=None):
2285 Spawn a new personal stream
2287 # Reset the tracked keyword and listname
2288 g
['keyword'] = g
['listname'] = ''
2290 g
['PREFIX'] = u2str(emojize(format_prefix()))
2292 th
= threading
.Thread(
2297 g
['original_name']))
2307 args
= parse_arguments()
2311 # Twitter API connection problem
2312 except TwitterHTTPError
as e
:
2315 magenta('We have connection problem with twitter REST API right now :('))
2316 detail_twitter_error(e
)
2319 # Proxy connection problem
2320 except (socks
.ProxyConnectionError
, URLError
):
2322 magenta('There seems to be a connection problem.'))
2324 magenta('You might want to check your proxy settings (host, port and type)!'))
2328 # Spawn stream thread
2329 target
= args
.stream
.split()[0]
2330 if target
== 'mine':
2331 spawn_personal_stream(args
)
2334 stuff
= args
.stream
.split()[1]
2338 'public': spawn_public_stream
,
2339 'list': spawn_list_stream
,
2341 spawn_dict
.get(target
)(args
, stuff
)
2343 # Start listen process