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')
226 notice
= light_yellow('You are running latest version (')
227 notice
+= light_green(current
)
228 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
274 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
276 c
['24BIT'] = args
.color_24bit
277 # Check type of ONLY_LIST and IGNORE_LIST
278 if not isinstance(c
['ONLY_LIST'], list):
279 printNicely(red('ONLY_LIST is not a valid list value.'))
281 if not isinstance(c
['IGNORE_LIST'], list):
282 printNicely(red('IGNORE_LIST is not a valid list value.'))
283 c
['IGNORE_LIST'] = []
285 c
['IGNORE_LIST'] += build_mute_dict()
287 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
294 t
= Twitter(auth
=authen())
295 # Get country and town
297 country
= g
['stuff'].split()[0]
301 town
= g
['stuff'].split()[1]
304 avail
= t
.trends
.available()
307 trends
= t
.trends
.place(_id
=1)[0]['trends']
310 for location
in avail
:
311 # Search for country and Town
313 if location
['countryCode'] == country \
314 and location
['placeType']['name'] == 'Town' \
315 and location
['name'] == town
:
316 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
318 # Search for country only
320 if location
['countryCode'] == country \
321 and location
['placeType']['name'] == 'Country':
322 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
330 t
= Twitter(auth
=authen())
331 num
= c
['HOME_TWEET_NUM']
332 if g
['stuff'].isdigit():
333 num
= int(g
['stuff'])
334 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
344 for e
in c
['events']:
348 printNicely(magenta('Nothing at this time.'))
355 t
= Twitter(auth
=authen())
356 num
= c
['HOME_TWEET_NUM']
357 if g
['stuff'].isdigit():
358 num
= int(g
['stuff'])
359 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
366 Show profile of a specific user
368 t
= Twitter(auth
=authen())
370 screen_name
= g
['stuff'].split()[0]
372 printNicely(red('Sorry I can\'t understand.'))
374 if screen_name
.startswith('@'):
377 screen_name
=screen_name
[1:],
378 include_entities
=False)
382 printNicely(red('No user.'))
384 printNicely(red('A name should begin with a \'@\''))
391 t
= Twitter(auth
=authen())
393 user
= g
['stuff'].split()[0]
395 printNicely(red('Sorry I can\'t understand.'))
399 num
= int(g
['stuff'].split()[1])
401 num
= c
['HOME_TWEET_NUM']
402 for tweet
in reversed(
403 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
407 printNicely(red('A name should begin with a \'@\''))
414 t
= Twitter(auth
=authen())
416 query
= g
['stuff'].strip()
418 printNicely(red('Sorry I can\'t understand.'))
420 type = c
['SEARCH_TYPE']
421 if type not in ['mixed', 'recent', 'popular']:
423 max_record
= c
['SEARCH_MAX_RECORD']
424 count
= min(max_record
, 100)
426 rel
= t
.search
.tweets(
433 printNicely('Newest tweets:')
434 for i
in reversed(xrange(count
)):
435 draw(t
=rel
[i
], keyword
=query
)
438 printNicely(magenta('I\'m afraid there is no result'))
445 t
= Twitter(auth
=authen())
446 t
.statuses
.update(status
=g
['stuff'])
451 Add new link to Pocket along with tweet id
453 if not c
['POCKET_SUPPORT']:
454 printNicely(red('Pocket isn\'t enabled.'))
460 t
= Twitter(auth
=authen())
462 id = int(g
['stuff'].split()[0])
463 tid
= c
['tweet_dict'][id]
465 printNicely(red('Sorry I can\'t understand.'))
468 tweet
= t
.statuses
.show(id=tid
)
470 if len(tweet
['entities']['urls']) > 0:
471 url
= tweet
['entities']['urls'][0]['expanded_url']
473 url
= "https://twitter.com/" + \
474 tweet
['user']['screen_name'] + '/status/' + str(tid
)
478 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
482 printNicely(red('Something is wrong about your Pocket account,'+ \
483 ' please restart Rainbowstream.'))
484 pocket_credential
= os
.environ
.get(
488 '')) + os
.sep
+ '.rainbow_pckt_oauth'
489 if os
.path
.exists(pocket_credential
):
490 os
.remove(pocket_credential
)
493 printNicely(green('Pocketed !'))
501 t
= Twitter(auth
=authen())
503 id = int(g
['stuff'].split()[0])
505 printNicely(red('Sorry I can\'t understand.'))
507 tid
= c
['tweet_dict'][id]
508 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
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 tweet
= t
.statuses
.show(id=tid
)
525 formater
= format_quote(tweet
)
529 prefix
= light_magenta('Compose your ', rl
=True) + \
530 light_green('#comment: ', rl
=True)
531 comment
= raw_input(prefix
)
533 quote
= comment
.join(formater
.split('#comment'))
534 t
.statuses
.update(status
=quote
)
536 printNicely(light_magenta('No text added.'))
543 t
= Twitter(auth
=authen())
546 id = int(g
['stuff'].split()[0])
548 printNicely(red('Sorry I can\'t understand.'))
550 tid
= c
['tweet_dict'][id]
551 # Get display num if exist
553 num
= int(g
['stuff'].split()[1])
555 num
= c
['RETWEETS_SHOW_NUM']
556 # Get result and display
557 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
559 printNicely(magenta('This tweet has no retweet.'))
561 for tweet
in reversed(rt_ary
):
570 t
= Twitter(auth
=authen())
572 id = int(g
['stuff'].split()[0])
574 printNicely(red('Sorry I can\'t understand.'))
576 tid
= c
['tweet_dict'][id]
577 tweet
= t
.statuses
.show(id=tid
)
578 limit
= c
['CONVERSATION_MAX']
580 thread_ref
.append(tweet
)
581 prev_tid
= tweet
['in_reply_to_status_id']
582 while prev_tid
and limit
:
584 tweet
= t
.statuses
.show(id=prev_tid
)
585 prev_tid
= tweet
['in_reply_to_status_id']
586 thread_ref
.append(tweet
)
588 for tweet
in reversed(thread_ref
):
597 t
= Twitter(auth
=authen())
599 id = int(g
['stuff'].split()[0])
601 printNicely(red('Sorry I can\'t understand.'))
603 tid
= c
['tweet_dict'][id]
604 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
605 status
= ' '.join(g
['stuff'].split()[1:])
606 status
= '@' + user
+ ' ' + str2u(status
)
607 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
614 t
= Twitter(auth
=authen())
616 id = int(g
['stuff'].split()[0])
618 printNicely(red('Sorry I can\'t understand.'))
620 tid
= c
['tweet_dict'][id]
621 original_tweet
= t
.statuses
.show(id=tid
)
622 text
= original_tweet
['text']
623 nick_ary
= [original_tweet
['user']['screen_name']]
624 for user
in list(original_tweet
['entities']['user_mentions']):
625 if user
['screen_name'] not in nick_ary \
626 and user
['screen_name'] != g
['original_name']:
627 nick_ary
.append(user
['screen_name'])
628 status
= ' '.join(g
['stuff'].split()[1:])
629 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
630 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
637 t
= Twitter(auth
=authen())
639 id = int(g
['stuff'].split()[0])
641 printNicely(red('Sorry I can\'t understand.'))
643 tid
= c
['tweet_dict'][id]
644 t
.favorites
.create(_id
=tid
, include_entities
=False)
645 printNicely(green('Favorited.'))
646 draw(t
.statuses
.show(id=tid
))
654 t
= Twitter(auth
=authen())
656 id = int(g
['stuff'].split()[0])
658 printNicely(red('Sorry I can\'t understand.'))
660 tid
= c
['tweet_dict'][id]
661 t
.favorites
.destroy(_id
=tid
)
662 printNicely(green('Okay it\'s unfavorited.'))
663 draw(t
.statuses
.show(id=tid
))
669 Copy url of a tweet to clipboard
671 t
= Twitter(auth
=authen())
673 id = int(g
['stuff'].split()[0])
674 tid
= c
['tweet_dict'][id]
676 printNicely(red('Tweet id is not valid.'))
678 tweet
= t
.statuses
.show(id=tid
)
679 url
= 'https://twitter.com/' + \
680 tweet
['user']['screen_name'] + '/status/' + str(tid
)
682 if platform
.system().lower() == 'darwin':
683 os
.system("echo '%s' | pbcopy" % url
)
684 printNicely(green('Copied tweet\'s url to clipboard.'))
686 printNicely('Direct link: ' + yellow(url
))
693 t
= Twitter(auth
=authen())
695 id = int(g
['stuff'].split()[0])
697 printNicely(red('Sorry I can\'t understand.'))
699 tid
= c
['tweet_dict'][id]
700 t
.statuses
.destroy(id=tid
)
701 printNicely(green('Okay it\'s gone.'))
708 t
= Twitter(auth
=authen())
710 target
= g
['stuff'].split()[0]
711 if target
!= 'image':
713 id = int(g
['stuff'].split()[1])
714 tid
= c
['tweet_dict'][id]
715 tweet
= t
.statuses
.show(id=tid
)
716 media
= tweet
['entities']['media']
718 res
= requests
.get(m
['media_url'])
719 img
= Image
.open(BytesIO(res
.content
))
723 printNicely(red('Sorry I can\'t show this image.'))
730 t
= Twitter(auth
=authen())
732 if not g
['stuff'].isdigit():
734 tid
= c
['tweet_dict'][int(g
['stuff'])]
735 tweet
= t
.statuses
.show(id=tid
)
736 urls
= tweet
['entities']['urls']
738 printNicely(light_magenta('No url here @.@!'))
742 expanded_url
= url
['expanded_url']
743 webbrowser
.open(expanded_url
)
746 printNicely(red('Sorry I can\'t open url in this tweet.'))
753 t
= Twitter(auth
=authen())
754 num
= c
['MESSAGES_DISPLAY']
755 if g
['stuff'].isdigit():
761 inbox
= inbox
+ t
.direct_messages(
764 include_entities
=False,
769 inbox
= inbox
+ t
.direct_messages(
772 include_entities
=False,
776 num
= c
['MESSAGES_DISPLAY']
777 if g
['stuff'].isdigit():
782 sent
= sent
+ t
.direct_messages
.sent(
785 include_entities
=False,
790 sent
= sent
+ t
.direct_messages
.sent(
793 include_entities
=False,
798 uniq_inbox
= list(set(
799 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
801 uniq_sent
= list(set(
802 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
804 for partner
in uniq_inbox
:
805 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
807 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
808 d
[partner
] = inbox_ary
+ sent_ary
809 for partner
in uniq_sent
:
812 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
813 g
['message_threads'] = print_threads(d
)
818 View a thread of message
821 thread_id
= int(g
['stuff'])
823 g
['message_threads'][thread_id
],
828 printNicely(red('No such thread.'))
833 Send a direct message
835 t
= Twitter(auth
=authen())
837 user
= g
['stuff'].split()[0]
838 if user
[0].startswith('@'):
839 content
= ' '.join(g
['stuff'].split()[1:])
840 t
.direct_messages
.new(
841 screen_name
=user
[1:],
844 printNicely(green('Message sent.'))
846 printNicely(red('A name should begin with a \'@\''))
849 printNicely(red('Sorry I can\'t understand.'))
856 t
= Twitter(auth
=authen())
858 id = int(g
['stuff'].split()[0])
860 printNicely(red('Sorry I can\'t understand.'))
861 mid
= c
['message_dict'][id]
862 t
.direct_messages
.destroy(id=mid
)
863 printNicely(green('Message deleted.'))
868 List friends for followers
870 t
= Twitter(auth
=authen())
873 name
= g
['stuff'].split()[1]
874 if name
.startswith('@'):
877 printNicely(red('A name should begin with a \'@\''))
878 raise Exception('Invalid name')
880 name
= g
['original_name']
881 # Get list followers or friends
883 target
= g
['stuff'].split()[0]
885 printNicely(red('Omg some syntax is wrong.'))
888 d
= {'fl': 'followers', 'fr': 'friends'}
892 while next_cursor
!= 0:
893 list = getattr(t
, d
[target
]).list(
897 include_entities
=False,
899 for u
in list['users']:
900 rel
[u
['name']] = '@' + u
['screen_name']
901 next_cursor
= list['next_cursor']
903 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
905 user
= ' ' + cycle_color(name
)
906 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
914 t
= Twitter(auth
=authen())
915 screen_name
= g
['stuff'].split()[0]
916 if screen_name
.startswith('@'):
917 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
918 printNicely(green('You are following ' + screen_name
+ ' now!'))
920 printNicely(red('A name should begin with a \'@\''))
927 t
= Twitter(auth
=authen())
928 screen_name
= g
['stuff'].split()[0]
929 if screen_name
.startswith('@'):
930 t
.friendships
.destroy(
931 screen_name
=screen_name
[1:],
932 include_entities
=False)
933 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
935 printNicely(red('A name should begin with a \'@\''))
942 t
= Twitter(auth
=authen())
944 screen_name
= g
['stuff'].split()[0]
946 printNicely(red('A name should be specified. '))
948 if screen_name
.startswith('@'):
950 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
951 if isinstance(rel
, dict):
952 printNicely(green(screen_name
+ ' is muted.'))
953 c
['IGNORE_LIST'] += [unc(screen_name
)]
954 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
956 printNicely(red(rel
))
959 printNicely(red('Something is wrong, can not mute now :('))
961 printNicely(red('A name should begin with a \'@\''))
968 t
= Twitter(auth
=authen())
970 screen_name
= g
['stuff'].split()[0]
972 printNicely(red('A name should be specified. '))
974 if screen_name
.startswith('@'):
976 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
977 if isinstance(rel
, dict):
978 printNicely(green(screen_name
+ ' is unmuted.'))
979 c
['IGNORE_LIST'].remove(screen_name
)
981 printNicely(red(rel
))
983 printNicely(red('Maybe you are not muting this person ?'))
985 printNicely(red('A name should begin with a \'@\''))
992 # Get dict of muting users
993 md
= build_mute_dict(dict_data
=True)
994 printNicely('All: ' + str(len(md
)) + ' people.')
996 user
= ' ' + cycle_color(md
[name
])
997 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
999 # Update from Twitter
1000 c
['IGNORE_LIST'] = [n
for n
in md
]
1007 t
= Twitter(auth
=authen())
1008 screen_name
= g
['stuff'].split()[0]
1009 if screen_name
.startswith('@'):
1011 screen_name
=screen_name
[1:],
1012 include_entities
=False,
1014 printNicely(green('You blocked ' + screen_name
+ '.'))
1016 printNicely(red('A name should begin with a \'@\''))
1023 t
= Twitter(auth
=authen())
1024 screen_name
= g
['stuff'].split()[0]
1025 if screen_name
.startswith('@'):
1027 screen_name
=screen_name
[1:],
1028 include_entities
=False,
1030 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1032 printNicely(red('A name should begin with a \'@\''))
1037 Report a user as a spam account
1039 t
= Twitter(auth
=authen())
1040 screen_name
= g
['stuff'].split()[0]
1041 if screen_name
.startswith('@'):
1042 t
.users
.report_spam(
1043 screen_name
=screen_name
[1:])
1044 printNicely(green('You reported ' + screen_name
+ '.'))
1046 printNicely(red('Sorry I can\'t understand.'))
1054 list_name
= raw_input(
1055 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1056 # Get list name and owner
1058 owner
, slug
= list_name
.split('/')
1059 if slug
.startswith('@'):
1064 light_magenta('List name should follow "@owner/list_name" format.'))
1065 raise Exception('Wrong list name')
1068 def check_slug(list_name
):
1072 # Get list name and owner
1074 owner
, slug
= list_name
.split('/')
1075 if slug
.startswith('@'):
1080 light_magenta('List name should follow "@owner/list_name" format.'))
1081 raise Exception('Wrong list name')
1088 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1092 printNicely(light_magenta('You belong to no lists :)'))
1099 owner
, slug
= get_slug()
1100 res
= t
.lists
.statuses(
1102 owner_screen_name
=owner
,
1103 count
=c
['LIST_MAX'],
1104 include_entities
=False)
1105 for tweet
in reversed(res
):
1110 def list_members(t
):
1114 owner
, slug
= get_slug()
1118 while next_cursor
!= 0:
1119 m
= t
.lists
.members(
1121 owner_screen_name
=owner
,
1123 include_entities
=False)
1124 for u
in m
['users']:
1125 rel
[u
['name']] = '@' + u
['screen_name']
1126 next_cursor
= m
['next_cursor']
1127 printNicely('All: ' + str(len(rel
)) + ' members.')
1129 user
= ' ' + cycle_color(name
)
1130 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1134 def list_subscribers(t
):
1138 owner
, slug
= get_slug()
1142 while next_cursor
!= 0:
1143 m
= t
.lists
.subscribers(
1145 owner_screen_name
=owner
,
1147 include_entities
=False)
1148 for u
in m
['users']:
1149 rel
[u
['name']] = '@' + u
['screen_name']
1150 next_cursor
= m
['next_cursor']
1151 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1153 user
= ' ' + cycle_color(name
)
1154 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1160 Add specific user to a list
1162 owner
, slug
= get_slug()
1164 user_name
= raw_input(
1166 'Give me name of the newbie: ',
1168 if user_name
.startswith('@'):
1169 user_name
= user_name
[1:]
1171 t
.lists
.members
.create(
1173 owner_screen_name
=owner
,
1174 screen_name
=user_name
)
1175 printNicely(green('Added.'))
1178 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1183 Remove specific user from a list
1185 owner
, slug
= get_slug()
1187 user_name
= raw_input(
1189 'Give me name of the unlucky one: ',
1191 if user_name
.startswith('@'):
1192 user_name
= user_name
[1:]
1194 t
.lists
.members
.destroy(
1196 owner_screen_name
=owner
,
1197 screen_name
=user_name
)
1198 printNicely(green('Gone.'))
1201 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1204 def list_subscribe(t
):
1208 owner
, slug
= get_slug()
1211 t
.lists
.subscribers
.create(
1213 owner_screen_name
=owner
)
1214 printNicely(green('Done.'))
1218 light_magenta('I\'m sorry you can not subscribe to this list.'))
1221 def list_unsubscribe(t
):
1225 owner
, slug
= get_slug()
1228 t
.lists
.subscribers
.destroy(
1230 owner_screen_name
=owner
)
1231 printNicely(green('Done.'))
1235 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1244 while next_cursor
!= 0:
1245 res
= t
.lists
.ownerships(
1246 screen_name
=g
['original_name'],
1249 next_cursor
= res
['next_cursor']
1253 printNicely(light_magenta('You own no lists :)'))
1260 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1263 'New list\'s mode (public/private): ',
1265 description
= raw_input(
1267 'New list\'s description: ',
1273 description
=description
)
1274 printNicely(green(name
+ ' list is created.'))
1277 printNicely(red('Oops something is wrong with Twitter :('))
1286 'Your list that you want to update: ',
1290 'Update name (leave blank to unchange): ',
1292 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1293 description
= raw_input(light_magenta('Update description: ', rl
=True))
1297 slug
='-'.join(slug
.split()),
1298 owner_screen_name
=g
['original_name'],
1301 description
=description
)
1305 owner_screen_name
=g
['original_name'],
1307 description
=description
)
1308 printNicely(green(slug
+ ' list is updated.'))
1311 printNicely(red('Oops something is wrong with Twitter :('))
1320 'Your list that you want to delete: ',
1324 slug
='-'.join(slug
.split()),
1325 owner_screen_name
=g
['original_name'])
1326 printNicely(green(slug
+ ' list is deleted.'))
1329 printNicely(red('Oops something is wrong with Twitter :('))
1336 t
= Twitter(auth
=authen())
1337 # List all lists or base on action
1339 g
['list_action'] = g
['stuff'].split()[0]
1346 'all_mem': list_members
,
1347 'all_sub': list_subscribers
,
1350 'sub': list_subscribe
,
1351 'unsub': list_unsubscribe
,
1354 'update': list_update
,
1358 return action_ary
[g
['list_action']](t
)
1360 printNicely(red('Please try again.'))
1368 target
= g
['stuff'].split()[0]
1370 args
= parse_arguments()
1372 if g
['stuff'].split()[-1] == '-f':
1373 guide
= 'To ignore an option, just hit Enter key.'
1374 printNicely(light_magenta(guide
))
1375 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1376 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1377 args
.filter = filter(None, only
.split(','))
1378 args
.ignore
= filter(None, ignore
.split(','))
1380 printNicely(red('Sorry, wrong format.'))
1383 g
['stream_stop'] = True
1385 stuff
= g
['stuff'].split()[1]
1390 'public': spawn_public_stream
,
1391 'list': spawn_list_stream
,
1392 'mine': spawn_personal_stream
,
1394 spawn_dict
.get(target
)(args
, stuff
)
1397 printNicely(red('Sorry I can\'t understand.'))
1402 Unix's command `cal`
1405 rel
= os
.popen('cal').read().split('\n')
1408 show_calendar(month
, date
, rel
)
1413 List and change theme
1417 for theme
in g
['themes']:
1418 line
= light_magenta(theme
)
1419 if c
['THEME'] == theme
:
1420 line
= ' ' * 2 + light_yellow('* ') + line
1422 line
= ' ' * 4 + line
1428 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1429 # Redefine decorated_name
1430 g
['decorated_name'] = lambda x
: color_func(
1431 c
['DECORATED_NAME'])(
1433 printNicely(green('Theme changed.'))
1435 printNicely(red('No such theme exists.'))
1440 Browse and change config
1442 all_config
= get_all_config()
1443 g
['stuff'] = g
['stuff'].strip()
1446 for k
in all_config
:
1448 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1450 guide
= 'Detailed explanation can be found at ' + \
1451 color_func(c
['TWEET']['link'])(
1452 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1454 # Print specific config
1455 elif len(g
['stuff'].split()) == 1:
1456 if g
['stuff'] in all_config
:
1459 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1462 printNicely(red('No such config key.'))
1463 # Print specific config's default value
1464 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1465 key
= g
['stuff'].split()[0]
1467 value
= get_default_config(key
)
1468 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1472 printNicely(red('Just can not get the default.'))
1473 # Delete specific config key in config file
1474 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1475 key
= g
['stuff'].split()[0]
1478 printNicely(green('Config key is dropped.'))
1481 printNicely(red('Just can not drop the key.'))
1482 # Set specific config
1483 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1484 key
= g
['stuff'].split()[0]
1485 value
= g
['stuff'].split()[-1]
1486 if key
== 'THEME' and not validate_theme(value
):
1487 printNicely(red('Invalid theme\'s value.'))
1490 set_config(key
, value
)
1491 # Keys that needs to be apply immediately
1493 c
['THEME'] = reload_theme(value
, c
['THEME'])
1494 g
['decorated_name'] = lambda x
: color_func(
1495 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1496 elif key
== 'PREFIX':
1497 g
['PREFIX'] = u2str(emojize(format_prefix(
1498 listname
=g
['listname'],
1499 keyword
=g
['keyword']
1502 printNicely(green('Updated successfully.'))
1505 printNicely(red('Just can not set the key.'))
1507 printNicely(light_magenta('Sorry I can\'t understand.'))
1510 def help_discover():
1515 # Discover the world
1517 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1518 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1519 'You can try ' + light_green('trend US') + ' or ' + \
1520 light_green('trend JP Tokyo') + '.\n'
1521 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1522 light_green('home 7') + ' will show 7 tweets.\n'
1524 light_green('notification') + ' will show your recent notification.\n'
1525 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1526 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1527 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1528 magenta('@mdo') + '.\n'
1529 usage
+= s
* 2 + light_green('view @mdo') + \
1530 ' will show ' + magenta('@mdo') + '\'s home.\n'
1531 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1532 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1533 'Search can be performed with or without hashtag.\n'
1544 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1545 usage
+= s
* 2 + light_green('t oops ') + \
1546 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1548 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1549 light_yellow('[id=12]') + '.\n'
1551 light_green('quote 12 ') + ' will quote the tweet with ' + \
1552 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1553 'the quote will be canceled.\n'
1555 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1556 light_yellow('[id=12]') + '.\n'
1557 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1558 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1559 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1560 light_yellow('oops') + '" to the owner of the tweet with ' + \
1561 light_yellow('[id=12]') + '.\n'
1562 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1563 light_yellow('oops') + '" to all people in the tweet with ' + \
1564 light_yellow('[id=12]') + '.\n'
1566 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1567 light_yellow('[id=12]') + '.\n'
1569 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1570 light_yellow('[id=12]') + '.\n'
1572 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1573 light_yellow('[id=12]') + '.\n'
1575 light_green('del 12 ') + ' will delete tweet with ' + \
1576 light_yellow('[id=12]') + '.\n'
1577 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1578 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1579 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1580 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1581 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1582 light_yellow('[id=12]') + ' in your Pocket list.\n'
1586 def help_messages():
1593 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1594 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1595 light_green('inbox 7') + ' will show newest 7 messages.\n'
1596 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1597 light_yellow('[thread_id=2]') + '.\n'
1598 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1599 magenta('@dtvd88') + '.\n'
1600 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1601 light_yellow('[message_id=5]') + '.\n'
1605 def help_friends_and_followers():
1607 Friends and Followers
1610 # Follower and following
1612 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1614 light_green('ls fl') + \
1615 ' will list all followers (people who are following you).\n'
1617 light_green('ls fr') + \
1618 ' will list all friends (people who you are following).\n'
1619 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1620 magenta('@dtvd88') + '.\n'
1621 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1622 magenta('@dtvd88') + '.\n'
1623 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1624 magenta('@dtvd88') + '.\n'
1625 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1626 magenta('@dtvd88') + '.\n'
1627 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1628 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1629 magenta('@dtvd88') + '.\n'
1630 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1631 magenta('@dtvd88') + '.\n'
1632 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1633 magenta('@dtvd88') + ' as a spam account.\n'
1644 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1645 usage
+= s
* 2 + light_green('list') + \
1646 ' will show all lists you are belong to.\n'
1647 usage
+= s
* 2 + light_green('list home') + \
1648 ' will show timeline of list. You will be asked for list\'s name.\n'
1649 usage
+= s
* 2 + light_green('list all_mem') + \
1650 ' will show list\'s all members.\n'
1651 usage
+= s
* 2 + light_green('list all_sub') + \
1652 ' will show list\'s all subscribers.\n'
1653 usage
+= s
* 2 + light_green('list add') + \
1654 ' will add specific person to a list owned by you.' + \
1655 ' You will be asked for list\'s name and person\'s name.\n'
1656 usage
+= s
* 2 + light_green('list rm') + \
1657 ' will remove specific person from a list owned by you.' + \
1658 ' You will be asked for list\'s name and person\'s name.\n'
1659 usage
+= s
* 2 + light_green('list sub') + \
1660 ' will subscribe you to a specific list.\n'
1661 usage
+= s
* 2 + light_green('list unsub') + \
1662 ' will unsubscribe you from a specific list.\n'
1663 usage
+= s
* 2 + light_green('list own') + \
1664 ' will show all list owned by you.\n'
1665 usage
+= s
* 2 + light_green('list new') + \
1666 ' will create a new list.\n'
1667 usage
+= s
* 2 + light_green('list update') + \
1668 ' will update a list owned by you.\n'
1669 usage
+= s
* 2 + light_green('list del') + \
1670 ' will delete a list owned by you.\n'
1681 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1682 usage
+= s
* 2 + light_green('switch public #AKB') + \
1683 ' will switch to public stream and follow "' + \
1684 light_yellow('AKB') + '" keyword.\n'
1685 usage
+= s
* 2 + light_green('switch mine') + \
1686 ' will switch to your personal stream.\n'
1687 usage
+= s
* 2 + light_green('switch mine -f ') + \
1688 ' will prompt to enter the filter.\n'
1689 usage
+= s
* 3 + light_yellow('Only nicks') + \
1690 ' filter will decide nicks will be INCLUDE ONLY.\n'
1691 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1692 ' filter will decide nicks will be EXCLUDE.\n'
1693 usage
+= s
* 2 + light_green('switch list') + \
1694 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1703 h
, w
= os
.popen('stty size', 'r').read().split()
1706 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1707 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1708 usage
+= s
+ 'You are ' + \
1709 light_yellow('already') + ' on your personal stream.\n'
1710 usage
+= s
+ 'Any update from Twitter will show up ' + \
1711 light_yellow('immediately') + '.\n'
1712 usage
+= s
+ 'In addition, following commands are available right now:\n'
1713 # Twitter help section
1715 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1716 usage
+= s
* 2 + light_green('h discover') + \
1717 ' will show help for discover commands.\n'
1718 usage
+= s
* 2 + light_green('h tweets') + \
1719 ' will show help for tweets commands.\n'
1720 usage
+= s
* 2 + light_green('h messages') + \
1721 ' will show help for messages commands.\n'
1722 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1723 ' will show help for friends and followers commands.\n'
1724 usage
+= s
* 2 + light_green('h list') + \
1725 ' will show help for list commands.\n'
1726 usage
+= s
* 2 + light_green('h stream') + \
1727 ' will show help for stream commands.\n'
1730 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1731 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1732 'will be evaluate by Python interpreter.\n'
1733 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1734 ' for current month.\n'
1737 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1738 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1739 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1740 ' theme immediately.\n'
1741 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1743 light_green('config ASCII_ART') + ' will output current value of ' +\
1744 light_yellow('ASCII_ART') + ' config key.\n'
1746 light_green('config TREND_MAX default') + ' will output default value of ' + \
1747 light_yellow('TREND_MAX') + ' config key.\n'
1749 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1750 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1752 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1753 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1754 light_yellow('True') + '.\n'
1757 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1758 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1759 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1760 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1761 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1762 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1763 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1766 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1767 usage
+= s
+ 'Have fun and hang tight! \n'
1770 'discover': help_discover
,
1771 'tweets': help_tweets
,
1772 'messages': help_messages
,
1773 'friends_and_followers': help_friends_and_followers
,
1775 'stream': help_stream
,
1780 lambda: printNicely(red('No such command.'))
1788 Pause stream display
1791 printNicely(green('Stream is paused'))
1799 printNicely(green('Stream is running back now'))
1815 printNicely(green('See you next time :)'))
1823 Reset prefix of line
1826 if c
.get('USER_JSON_ERROR'):
1827 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1828 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1830 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1833 printNicely(str(eval(g
['cmd'])))
1887 # Handle function set
1941 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1946 Listen to user's input
1951 ['public', 'mine', 'list'], # switch
1970 ['image'], # show image
1972 ['fl', 'fr'], # list
1974 [i
for i
in g
['message_threads']], # sent
1999 [key
for key
in dict(get_all_config())], # config
2000 g
['themes'], # theme
2005 'friends_and_followers',
2017 init_interactive_shell(d
)
2024 # Only use PREFIX as a string with raw_input
2025 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2028 # Save cmd to compare with readline buffer
2029 g
['cmd'] = line
.strip()
2030 # Get short cmd to pass to handle function
2032 cmd
= line
.split()[0]
2035 # Lock the semaphore
2037 # Save cmd to global variable and call process
2038 g
['stuff'] = ' '.join(line
.split()[1:])
2039 # Check tweet length
2040 # Process the command
2043 if cmd
in ['switch', 't', 'rt', 'rep']:
2047 # Release the semaphore lock
2051 except TwitterHTTPError
as e
:
2052 detail_twitter_error(e
)
2055 printNicely(red('OMG something is wrong with Twitter API right now.'))
2058 def reconn_notice():
2060 Notice when Hangup or Timeout
2062 guide
= light_magenta('You can use ') + \
2063 light_green('switch') + \
2064 light_magenta(' command to return to your stream.\n')
2065 guide
+= light_magenta('Type ') + \
2066 light_green('h stream') + \
2067 light_magenta(' for more details.')
2069 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2073 def stream(domain
, args
, name
='Rainbow Stream'):
2079 c
['USER_DOMAIN']: name
,
2080 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2081 c
['SITE_DOMAIN']: name
,
2084 ascii_art(art_dict
.get(domain
, name
))
2085 # These arguments are optional:
2087 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2089 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2092 if args
.track_keywords
:
2093 query_args
['track'] = args
.track_keywords
2095 stream
= TwitterStream(
2100 if domain
== c
['USER_DOMAIN']:
2101 tweet_iter
= stream
.user(**query_args
)
2102 elif domain
== c
['SITE_DOMAIN']:
2103 tweet_iter
= stream
.site(**query_args
)
2105 if args
.track_keywords
:
2106 tweet_iter
= stream
.statuses
.filter(**query_args
)
2108 tweet_iter
= stream
.statuses
.sample()
2109 # Block new stream until other one exits
2110 StreamLock
.acquire()
2111 g
['stream_stop'] = False
2112 last_tweet_time
= time
.time()
2113 for tweet
in tweet_iter
:
2115 printNicely('-- None --')
2116 elif tweet
is Timeout
:
2117 # Because the stream check for each 0.3s
2118 # so we shouldn't output anything here
2119 if(g
['stream_stop']):
2120 StreamLock
.release()
2122 elif tweet
is HeartbeatTimeout
:
2123 printNicely('-- Heartbeat Timeout --')
2125 StreamLock
.release()
2127 elif tweet
is Hangup
:
2128 printNicely('-- Hangup --')
2130 StreamLock
.release()
2132 elif tweet
.get('text'):
2133 # Slow down the stream by STREAM_DELAY config key
2134 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2136 last_tweet_time
= time
.time()
2137 # Check the semaphore pause and lock (stream process only)
2145 keyword
=args
.track_keywords
,
2150 # Current readline buffer
2151 current_buffer
= readline
.get_line_buffer().strip()
2152 # There is an unexpected behaviour in MacOSX readline + Python 2:
2153 # after completely delete a word after typing it,
2154 # somehow readline buffer still contains
2155 # the 1st character of that word
2156 if current_buffer
and g
['cmd'] != current_buffer
:
2158 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2160 elif not c
['HIDE_PROMPT']:
2161 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2163 elif tweet
.get('direct_message'):
2164 # Check the semaphore pause and lock (stream process only)
2169 print_message(tweet
['direct_message'])
2170 elif tweet
.get('event'):
2171 c
['events'].append(tweet
)
2173 except TwitterHTTPError
as e
:
2176 magenta('We have connection problem with twitter stream API right now :('))
2177 detail_twitter_error(e
)
2178 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2182 magenta('There seems to be a connection problem.'))
2187 def spawn_public_stream(args
, keyword
=None):
2189 Spawn a new public stream
2191 # Only set keyword if specified
2193 if keyword
[0] == '#':
2194 keyword
= keyword
[1:]
2195 args
.track_keywords
= keyword
2196 g
['keyword'] = keyword
2198 g
['keyword'] = 'Global'
2199 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2202 th
= threading
.Thread(
2211 def spawn_list_stream(args
, stuff
=None):
2213 Spawn a new list stream
2216 owner
, slug
= check_slug(stuff
)
2218 owner
, slug
= get_slug()
2220 # Force python 2 not redraw readline buffer
2221 listname
= '/'.join([owner
, slug
])
2222 # Set the listname variable
2223 # and reset tracked keyword
2224 g
['listname'] = listname
2226 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2227 listname
=g
['listname']
2229 printNicely(light_yellow('getting list members ...'))
2231 t
= Twitter(auth
=authen())
2234 while next_cursor
!= 0:
2235 m
= t
.lists
.members(
2237 owner_screen_name
=owner
,
2239 include_entities
=False)
2240 for u
in m
['users']:
2241 members
.append('@' + u
['screen_name'])
2242 next_cursor
= m
['next_cursor']
2243 printNicely(light_yellow('... done.'))
2244 # Build thread filter array
2245 args
.filter = members
2247 th
= threading
.Thread(
2257 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2259 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2263 def spawn_personal_stream(args
, stuff
=None):
2265 Spawn a new personal stream
2267 # Reset the tracked keyword and listname
2268 g
['keyword'] = g
['listname'] = ''
2270 g
['PREFIX'] = u2str(emojize(format_prefix()))
2272 th
= threading
.Thread(
2277 g
['original_name']))
2287 args
= parse_arguments()
2291 # Twitter API connection problem
2292 except TwitterHTTPError
as e
:
2295 magenta('We have connection problem with twitter REST API right now :('))
2296 detail_twitter_error(e
)
2299 # Proxy connection problem
2300 except (socks
.ProxyConnectionError
, URLError
):
2302 magenta('There seems to be a connection problem.'))
2304 magenta('You might want to check your proxy settings (host, port and type)!'))
2308 # Spawn stream thread
2309 target
= args
.stream
.split()[0]
2310 if target
== 'mine':
2311 spawn_personal_stream(args
)
2314 stuff
= args
.stream
.split()[1]
2318 'public': spawn_public_stream
,
2319 'list': spawn_list_stream
,
2321 spawn_dict
.get(target
)(args
, stuff
)
2323 # Start listen process