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
+ ']: ')
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']
327 Fetch stream based on since_id
329 t
= Twitter(auth
=authen())
331 num
= c
['HOME_TWEET_NUM']
332 kwargs
= {'count': num
}
335 kwargs
['since_id'] = g
['since_id']
337 kwargs
= add_tweetmode_parameter(kwargs
)
338 result
= t
.statuses
.home_timeline(**kwargs
)
340 g
['since_id'] = result
[0]['id']
341 for tweet
in reversed(result
):
349 t
= Twitter(auth
=authen())
350 num
= c
['HOME_TWEET_NUM']
351 if g
['stuff'].isdigit():
352 num
= int(g
['stuff'])
353 kwargs
= {'count': num
}
354 kwargs
= add_tweetmode_parameter(kwargs
)
355 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
365 for e
in c
['events']:
369 printNicely(magenta('Nothing at this time.'))
376 t
= Twitter(auth
=authen())
377 num
= c
['HOME_TWEET_NUM']
378 if g
['stuff'].isdigit():
379 num
= int(g
['stuff'])
380 kwargs
= {'count': num
}
381 kwargs
= add_tweetmode_parameter(kwargs
)
382 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
389 Show profile of a specific user
391 t
= Twitter(auth
=authen())
393 screen_name
= g
['stuff'].split()[0]
395 printNicely(red('Sorry I can\'t understand.'))
397 if screen_name
.startswith('@'):
400 screen_name
=screen_name
[1:],
401 include_entities
=False)
405 printNicely(red('No user.'))
407 printNicely(red('A name should begin with a \'@\''))
414 t
= Twitter(auth
=authen())
416 user
= g
['stuff'].split()[0]
418 printNicely(red('Sorry I can\'t understand.'))
422 num
= int(g
['stuff'].split()[1])
424 num
= c
['HOME_TWEET_NUM']
425 kwargs
= {'count': num
, 'screen_name': user
[1:]}
426 kwargs
= add_tweetmode_parameter(kwargs
)
427 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
431 printNicely(red('A name should begin with a \'@\''))
434 def view_my_tweets():
436 Display user's recent tweets.
438 t
= Twitter(auth
=authen())
440 num
= int(g
['stuff'])
442 num
= c
['HOME_TWEET_NUM']
443 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
444 kwargs
= add_tweetmode_parameter(kwargs
)
445 for tweet
in reversed(
446 t
.statuses
.user_timeline(**kwargs
)):
455 t
= Twitter(auth
=authen())
457 query
= g
['stuff'].strip()
459 printNicely(red('Sorry I can\'t understand.'))
461 type = c
['SEARCH_TYPE']
462 if type not in ['mixed', 'recent', 'popular']:
464 max_record
= c
['SEARCH_MAX_RECORD']
465 count
= min(max_record
, 100)
471 kwargs
= add_tweetmode_parameter(kwargs
)
473 rel
= t
.search
.tweets(**kwargs
)['statuses']
476 printNicely('Newest tweets:')
477 for i
in reversed(xrange(count
)):
478 draw(t
=rel
[i
], keyword
=query
)
481 printNicely(magenta('I\'m afraid there is no result'))
488 t
= Twitter(auth
=authen())
489 t
.statuses
.update(status
=g
['stuff'])
494 Add new link to Pocket along with tweet id
496 if not c
['POCKET_SUPPORT']:
497 printNicely(yellow('Pocket isn\'t enabled.'))
498 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
504 t
= Twitter(auth
=authen())
506 id = int(g
['stuff'].split()[0])
507 tid
= c
['tweet_dict'][id]
509 printNicely(red('Sorry I can\'t understand.'))
512 tweet
= t
.statuses
.show(id=tid
)
514 if len(tweet
['entities']['urls']) > 0:
515 url
= tweet
['entities']['urls'][0]['expanded_url']
517 url
= "https://twitter.com/" + \
518 tweet
['user']['screen_name'] + '/status/' + str(tid
)
522 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
526 printNicely(red('Something is wrong about your Pocket account,'+ \
527 ' please restart Rainbowstream.'))
528 pocket_credential
= os
.environ
.get(
532 '')) + os
.sep
+ '.rainbow_pckt_oauth'
533 if os
.path
.exists(pocket_credential
):
534 os
.remove(pocket_credential
)
537 printNicely(green('Pocketed !'))
545 t
= Twitter(auth
=authen())
547 id = int(g
['stuff'].split()[0])
549 printNicely(red('Sorry I can\'t understand.'))
551 tid
= c
['tweet_dict'][id]
552 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
560 t
= Twitter(auth
=authen())
562 id = int(g
['stuff'].split()[0])
564 printNicely(red('Sorry I can\'t understand.'))
566 tid
= c
['tweet_dict'][id]
568 kwargs
= add_tweetmode_parameter(kwargs
)
569 tweet
= t
.statuses
.show(**kwargs
)
571 formater
= format_quote(tweet
)
575 prefix
= light_magenta('Compose your ', rl
=True) + \
576 light_green('#comment: ', rl
=True)
577 comment
= raw_input(prefix
)
579 quote
= comment
.join(formater
.split('#comment'))
580 t
.statuses
.update(status
=quote
)
582 printNicely(light_magenta('No text added.'))
589 t
= Twitter(auth
=authen())
592 id = int(g
['stuff'].split()[0])
594 printNicely(red('Sorry I can\'t understand.'))
596 tid
= c
['tweet_dict'][id]
597 # Get display num if exist
599 num
= int(g
['stuff'].split()[1])
601 num
= c
['RETWEETS_SHOW_NUM']
602 # Get result and display
603 kwargs
= {'id': tid
, 'count': num
}
604 kwargs
= add_tweetmode_parameter(kwargs
)
605 rt_ary
= t
.statuses
.retweets(**kwargs
)
607 printNicely(magenta('This tweet has no retweet.'))
609 for tweet
in reversed(rt_ary
):
618 t
= Twitter(auth
=authen())
620 id = int(g
['stuff'].split()[0])
622 printNicely(red('Sorry I can\'t understand.'))
624 tid
= c
['tweet_dict'][id]
626 kwargs
= add_tweetmode_parameter(kwargs
)
627 tweet
= t
.statuses
.show(**kwargs
)
628 limit
= c
['CONVERSATION_MAX']
630 thread_ref
.append(tweet
)
631 prev_tid
= tweet
['in_reply_to_status_id']
632 while prev_tid
and limit
:
634 kwargs
['id'] = prev_tid
635 tweet
= t
.statuses
.show(**kwargs
)
636 prev_tid
= tweet
['in_reply_to_status_id']
637 thread_ref
.append(tweet
)
639 for tweet
in reversed(thread_ref
):
648 t
= Twitter(auth
=authen())
650 id = int(g
['stuff'].split()[0])
652 printNicely(red('Sorry I can\'t understand.'))
654 tid
= c
['tweet_dict'][id]
655 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
656 status
= ' '.join(g
['stuff'].split()[1:])
657 # don't include own username for tweet chains
658 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
659 if user
== g
['original_name']:
660 status
= str2u(status
)
662 status
= '@' + user
+ ' ' + str2u(status
)
663 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
670 t
= Twitter(auth
=authen())
672 id = int(g
['stuff'].split()[0])
674 printNicely(red('Sorry I can\'t understand.'))
676 tid
= c
['tweet_dict'][id]
677 original_tweet
= t
.statuses
.show(id=tid
)
678 text
= original_tweet
['text']
679 nick_ary
= [original_tweet
['user']['screen_name']]
680 for user
in list(original_tweet
['entities']['user_mentions']):
681 if user
['screen_name'] not in nick_ary \
682 and user
['screen_name'] != g
['original_name']:
683 nick_ary
.append(user
['screen_name'])
684 status
= ' '.join(g
['stuff'].split()[1:])
685 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
686 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
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
.favorites
.create(_id
=tid
, include_entities
=False)
701 printNicely(green('Favorited.'))
703 kwargs
= add_tweetmode_parameter(kwargs
)
704 draw(t
.statuses
.show(**kwargs
))
712 t
= Twitter(auth
=authen())
714 id = int(g
['stuff'].split()[0])
716 printNicely(red('Sorry I can\'t understand.'))
718 tid
= c
['tweet_dict'][id]
719 t
.favorites
.destroy(_id
=tid
)
720 printNicely(green('Okay it\'s unfavorited.'))
722 kwargs
= add_tweetmode_parameter(kwargs
)
723 draw(t
.statuses
.show(**kwargs
))
729 Copy url of a tweet to clipboard
731 t
= Twitter(auth
=authen())
733 id = int(g
['stuff'].split()[0])
734 tid
= c
['tweet_dict'][id]
736 printNicely(red('Tweet id is not valid.'))
739 kwargs
= add_tweetmode_parameter(kwargs
)
740 tweet
= t
.statuses
.show(**kwargs
)
741 url
= 'https://twitter.com/' + \
742 tweet
['user']['screen_name'] + '/status/' + str(tid
)
744 if platform
.system().lower() == 'darwin':
745 os
.system("echo '%s' | pbcopy" % url
)
746 printNicely(green('Copied tweet\'s url to clipboard.'))
748 printNicely('Direct link: ' + yellow(url
))
755 t
= Twitter(auth
=authen())
757 id = int(g
['stuff'].split()[0])
759 printNicely(red('Sorry I can\'t understand.'))
761 tid
= c
['tweet_dict'][id]
762 t
.statuses
.destroy(id=tid
)
763 printNicely(green('Okay it\'s gone.'))
770 t
= Twitter(auth
=authen())
772 target
= g
['stuff'].split()[0]
773 if target
!= 'image':
775 id = int(g
['stuff'].split()[1])
776 tid
= c
['tweet_dict'][id]
777 tweet
= t
.statuses
.show(id=tid
)
778 media
= tweet
['entities']['media']
780 res
= requests
.get(m
['media_url'])
781 img
= Image
.open(BytesIO(res
.content
))
785 printNicely(red('Sorry I can\'t show this image.'))
792 t
= Twitter(auth
=authen())
794 if not g
['stuff'].isdigit():
796 tid
= c
['tweet_dict'][int(g
['stuff'])]
797 tweet
= t
.statuses
.show(id=tid
)
798 urls
= tweet
['entities']['urls']
800 printNicely(light_magenta('No url here @.@!'))
804 expanded_url
= url
['expanded_url']
805 webbrowser
.open(expanded_url
)
808 printNicely(red('Sorry I can\'t open url in this tweet.'))
815 t
= Twitter(auth
=authen())
816 num
= c
['MESSAGES_DISPLAY']
817 if g
['stuff'].isdigit():
820 def inboxFilter(message
):
821 return message
['sender_screen_name'] == g
['original_name']
822 def sentFilter(message
):
823 return message
['recipient_screen_name'] == g
['original_name']
827 messages
= messages
+ t
.direct_messages
.events
.list()['events']
828 inbox
= filter(inboxFilter
, messages
)
829 sent
= filter(inboxFilter
, messages
)
832 uniq_inbox
= list(set(
833 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
835 uniq_sent
= list(set(
836 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
838 for partner
in uniq_inbox
:
839 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
841 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
842 d
[partner
] = inbox_ary
+ sent_ary
843 for partner
in uniq_sent
:
846 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
847 g
['message_threads'] = print_threads(d
)
852 View a thread of message
855 thread_id
= int(g
['stuff'])
857 g
['message_threads'][thread_id
],
862 printNicely(red('No such thread.'))
867 Send a direct message
869 t
= Twitter(auth
=authen())
871 user
= g
['stuff'].split()[0]
872 if user
[0].startswith('@'):
873 content
= ' '.join(g
['stuff'].split()[1:])
874 t
.direct_messages
.new(
875 screen_name
=user
[1:],
878 printNicely(green('Message sent.'))
880 printNicely(red('A name should begin with a \'@\''))
883 printNicely(red('Sorry I can\'t understand.'))
890 t
= Twitter(auth
=authen())
892 id = int(g
['stuff'].split()[0])
894 printNicely(red('Sorry I can\'t understand.'))
895 mid
= c
['message_dict'][id]
896 t
.direct_messages
.destroy(id=mid
)
897 printNicely(green('Message deleted.'))
902 List friends for followers
904 t
= Twitter(auth
=authen())
907 name
= g
['stuff'].split()[1]
908 if name
.startswith('@'):
911 printNicely(red('A name should begin with a \'@\''))
912 raise Exception('Invalid name')
914 name
= g
['original_name']
915 # Get list followers or friends
917 target
= g
['stuff'].split()[0]
919 printNicely(red('Omg some syntax is wrong.'))
922 d
= {'fl': 'followers', 'fr': 'friends'}
926 printNicely('All ' + d
[target
] + ':')
930 while next_cursor
!= 0:
932 list = getattr(t
, d
[target
]).list(
936 include_entities
=False,
939 for u
in list['users']:
945 + cycle_color( u
['name'] ) \
946 + color_func(c
['TWEET']['nick'])( ' @' \
950 next_cursor
= list['next_cursor']
952 # 300 users means 15 calls to the related API. The rate limit is 15
953 # calls per 15mn periods (see Twitter documentation).
954 if ( number_of_users
% 300 == 0 ):
955 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
956 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
959 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
965 t
= Twitter(auth
=authen())
966 screen_name
= g
['stuff'].split()[0]
967 if screen_name
.startswith('@'):
968 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
969 printNicely(green('You are following ' + screen_name
+ ' now!'))
971 printNicely(red('A name should begin with a \'@\''))
978 t
= Twitter(auth
=authen())
979 screen_name
= g
['stuff'].split()[0]
980 if screen_name
.startswith('@'):
981 t
.friendships
.destroy(
982 screen_name
=screen_name
[1:],
983 include_entities
=False)
984 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
986 printNicely(red('A name should begin with a \'@\''))
993 t
= Twitter(auth
=authen())
995 screen_name
= g
['stuff'].split()[0]
997 printNicely(red('A name should be specified. '))
999 if screen_name
.startswith('@'):
1001 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1002 if isinstance(rel
, dict):
1003 printNicely(green(screen_name
+ ' is muted.'))
1004 c
['IGNORE_LIST'] += [screen_name
]
1005 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1007 printNicely(red(rel
))
1010 printNicely(red('Something is wrong, can not mute now :('))
1012 printNicely(red('A name should begin with a \'@\''))
1019 t
= Twitter(auth
=authen())
1021 screen_name
= g
['stuff'].split()[0]
1023 printNicely(red('A name should be specified. '))
1025 if screen_name
.startswith('@'):
1027 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1028 if isinstance(rel
, dict):
1029 printNicely(green(screen_name
+ ' is unmuted.'))
1030 c
['IGNORE_LIST'].remove(screen_name
)
1032 printNicely(red(rel
))
1034 printNicely(red('Maybe you are not muting this person ?'))
1036 printNicely(red('A name should begin with a \'@\''))
1043 # Get dict of muting users
1044 md
= build_mute_dict(dict_data
=True)
1045 printNicely('All: ' + str(len(md
)) + ' people.')
1047 user
= ' ' + cycle_color(md
[name
])
1048 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1050 # Update from Twitter
1051 c
['IGNORE_LIST'] = [n
for n
in md
]
1058 t
= Twitter(auth
=authen())
1059 screen_name
= g
['stuff'].split()[0]
1060 if screen_name
.startswith('@'):
1062 screen_name
=screen_name
[1:],
1063 include_entities
=False,
1065 printNicely(green('You blocked ' + screen_name
+ '.'))
1067 printNicely(red('A name should begin with a \'@\''))
1074 t
= Twitter(auth
=authen())
1075 screen_name
= g
['stuff'].split()[0]
1076 if screen_name
.startswith('@'):
1078 screen_name
=screen_name
[1:],
1079 include_entities
=False,
1081 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1083 printNicely(red('A name should begin with a \'@\''))
1088 Report a user as a spam account
1090 t
= Twitter(auth
=authen())
1091 screen_name
= g
['stuff'].split()[0]
1092 if screen_name
.startswith('@'):
1093 t
.users
.report_spam(
1094 screen_name
=screen_name
[1:])
1095 printNicely(green('You reported ' + screen_name
+ '.'))
1097 printNicely(red('Sorry I can\'t understand.'))
1105 list_name
= raw_input(
1106 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1107 # Get list name and owner
1109 owner
, slug
= list_name
.split('/')
1110 if slug
.startswith('@'):
1115 light_magenta('List name should follow "@owner/list_name" format.'))
1116 raise Exception('Wrong list name')
1119 def check_slug(list_name
):
1123 # Get list name and owner
1125 owner
, slug
= list_name
.split('/')
1126 if slug
.startswith('@'):
1131 light_magenta('List name should follow "@owner/list_name" format.'))
1132 raise Exception('Wrong list name')
1139 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1143 printNicely(light_magenta('You belong to no lists :)'))
1150 owner
, slug
= get_slug()
1151 res
= t
.lists
.statuses(
1153 owner_screen_name
=owner
,
1154 count
=c
['LIST_MAX'],
1155 include_entities
=False)
1156 for tweet
in reversed(res
):
1161 def list_members(t
):
1165 owner
, slug
= get_slug()
1169 while next_cursor
!= 0:
1170 m
= t
.lists
.members(
1172 owner_screen_name
=owner
,
1174 include_entities
=False)
1175 for u
in m
['users']:
1176 rel
[u
['name']] = '@' + u
['screen_name']
1177 next_cursor
= m
['next_cursor']
1178 printNicely('All: ' + str(len(rel
)) + ' members.')
1180 user
= ' ' + cycle_color(name
)
1181 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1185 def list_subscribers(t
):
1189 owner
, slug
= get_slug()
1193 while next_cursor
!= 0:
1194 m
= t
.lists
.subscribers(
1196 owner_screen_name
=owner
,
1198 include_entities
=False)
1199 for u
in m
['users']:
1200 rel
[u
['name']] = '@' + u
['screen_name']
1201 next_cursor
= m
['next_cursor']
1202 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1204 user
= ' ' + cycle_color(name
)
1205 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1211 Add specific user to a list
1213 owner
, slug
= get_slug()
1215 user_name
= raw_input(
1217 'Give me name of the newbie: ',
1219 if user_name
.startswith('@'):
1220 user_name
= user_name
[1:]
1222 t
.lists
.members
.create(
1224 owner_screen_name
=owner
,
1225 screen_name
=user_name
)
1226 printNicely(green('Added.'))
1229 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1234 Remove specific user from a list
1236 owner
, slug
= get_slug()
1238 user_name
= raw_input(
1240 'Give me name of the unlucky one: ',
1242 if user_name
.startswith('@'):
1243 user_name
= user_name
[1:]
1245 t
.lists
.members
.destroy(
1247 owner_screen_name
=owner
,
1248 screen_name
=user_name
)
1249 printNicely(green('Gone.'))
1252 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1255 def list_subscribe(t
):
1259 owner
, slug
= get_slug()
1262 t
.lists
.subscribers
.create(
1264 owner_screen_name
=owner
)
1265 printNicely(green('Done.'))
1269 light_magenta('I\'m sorry you can not subscribe to this list.'))
1272 def list_unsubscribe(t
):
1276 owner
, slug
= get_slug()
1279 t
.lists
.subscribers
.destroy(
1281 owner_screen_name
=owner
)
1282 printNicely(green('Done.'))
1286 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1295 while next_cursor
!= 0:
1296 res
= t
.lists
.ownerships(
1297 screen_name
=g
['original_name'],
1300 next_cursor
= res
['next_cursor']
1304 printNicely(light_magenta('You own no lists :)'))
1311 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1314 'New list\'s mode (public/private): ',
1316 description
= raw_input(
1318 'New list\'s description: ',
1324 description
=description
)
1325 printNicely(green(name
+ ' list is created.'))
1328 printNicely(red('Oops something is wrong with Twitter :('))
1337 'Your list that you want to update: ',
1341 'Update name (leave blank to unchange): ',
1343 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1344 description
= raw_input(light_magenta('Update description: ', rl
=True))
1348 slug
='-'.join(slug
.split()),
1349 owner_screen_name
=g
['original_name'],
1352 description
=description
)
1356 owner_screen_name
=g
['original_name'],
1358 description
=description
)
1359 printNicely(green(slug
+ ' list is updated.'))
1362 printNicely(red('Oops something is wrong with Twitter :('))
1371 'Your list that you want to delete: ',
1375 slug
='-'.join(slug
.split()),
1376 owner_screen_name
=g
['original_name'])
1377 printNicely(green(slug
+ ' list is deleted.'))
1380 printNicely(red('Oops something is wrong with Twitter :('))
1387 t
= Twitter(auth
=authen())
1388 # List all lists or base on action
1390 g
['list_action'] = g
['stuff'].split()[0]
1397 'all_mem': list_members
,
1398 'all_sub': list_subscribers
,
1401 'sub': list_subscribe
,
1402 'unsub': list_unsubscribe
,
1405 'update': list_update
,
1409 return action_ary
[g
['list_action']](t
)
1411 printNicely(red('Please try again.'))
1419 target
= g
['stuff'].split()[0]
1421 args
= parse_arguments()
1423 if g
['stuff'].split()[-1] == '-f':
1424 guide
= 'To ignore an option, just hit Enter key.'
1425 printNicely(light_magenta(guide
))
1426 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1427 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1428 args
.filter = list(filter(None, only
.split(',')))
1429 args
.ignore
= list(filter(None, ignore
.split(',')))
1431 printNicely(red('Sorry, wrong format.'))
1434 g
['stream_stop'] = True
1436 stuff
= g
['stuff'].split()[1]
1441 'public': spawn_public_stream
,
1442 'list': spawn_list_stream
,
1443 'mine': spawn_personal_stream
,
1445 spawn_dict
.get(target
)(args
, stuff
)
1448 printNicely(red('Sorry I can\'t understand.'))
1453 Unix's command `cal`
1456 rel
= os
.popen('cal').read().split('\n')
1459 show_calendar(month
, date
, rel
)
1464 List and change theme
1468 for theme
in g
['themes']:
1469 line
= light_magenta(theme
)
1470 if c
['THEME'] == theme
:
1471 line
= ' ' * 2 + light_yellow('* ') + line
1473 line
= ' ' * 4 + line
1479 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1480 # Redefine decorated_name
1481 g
['decorated_name'] = lambda x
: color_func(
1482 c
['DECORATED_NAME'])(
1484 printNicely(green('Theme changed.'))
1486 printNicely(red('No such theme exists.'))
1491 Browse and change config
1493 all_config
= get_all_config()
1494 g
['stuff'] = g
['stuff'].strip()
1497 for k
in all_config
:
1499 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1501 guide
= 'Detailed explanation can be found at ' + \
1502 color_func(c
['TWEET']['link'])(
1503 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1505 # Print specific config
1506 elif len(g
['stuff'].split()) == 1:
1507 if g
['stuff'] in all_config
:
1510 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1513 printNicely(red('No such config key.'))
1514 # Print specific config's default value
1515 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1516 key
= g
['stuff'].split()[0]
1518 value
= get_default_config(key
)
1519 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1523 printNicely(red('Just can not get the default.'))
1524 # Delete specific config key in config file
1525 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1526 key
= g
['stuff'].split()[0]
1529 printNicely(green('Config key is dropped.'))
1532 printNicely(red('Just can not drop the key.'))
1533 # Set specific config
1534 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1535 key
= g
['stuff'].split()[0]
1536 value
= g
['stuff'].split()[-1]
1537 if key
== 'THEME' and not validate_theme(value
):
1538 printNicely(red('Invalid theme\'s value.'))
1541 set_config(key
, value
)
1542 # Keys that needs to be apply immediately
1544 c
['THEME'] = reload_theme(value
, c
['THEME'])
1545 g
['decorated_name'] = lambda x
: color_func(
1546 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1547 elif key
== 'PREFIX':
1548 g
['PREFIX'] = u2str(emojize(format_prefix(
1549 listname
=g
['listname'],
1550 keyword
=g
['keyword']
1553 printNicely(green('Updated successfully.'))
1556 printNicely(red('Just can not set the key.'))
1558 printNicely(light_magenta('Sorry I can\'t understand.'))
1561 def help_discover():
1566 # Discover the world
1568 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1569 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1570 'You can try ' + light_green('trend US') + ' or ' + \
1571 light_green('trend JP Tokyo') + '.\n'
1572 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1573 light_green('home 7') + ' will show 7 tweets.\n'
1574 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1575 light_green('me 2') + ' will show your last 2 tweets.\n'
1577 light_green('notification') + ' will show your recent notification.\n'
1578 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1579 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1580 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1581 magenta('@mdo') + '.\n'
1582 usage
+= s
* 2 + light_green('view @mdo') + \
1583 ' will show ' + magenta('@mdo') + '\'s home.\n'
1584 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1585 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1586 'Search can be performed with or without hashtag.\n'
1597 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1598 usage
+= s
* 2 + light_green('t oops ') + \
1599 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1601 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1602 light_yellow('[id=12]') + '.\n'
1604 light_green('quote 12 ') + ' will quote the tweet with ' + \
1605 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1606 'the quote will be canceled.\n'
1608 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1609 light_yellow('[id=12]') + '.\n'
1610 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1611 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1612 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1613 light_yellow('oops') + '" to the owner of the tweet with ' + \
1614 light_yellow('[id=12]') + '.\n'
1615 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1616 light_yellow('oops') + '" to all people in the tweet with ' + \
1617 light_yellow('[id=12]') + '.\n'
1619 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1620 light_yellow('[id=12]') + '.\n'
1622 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1623 light_yellow('[id=12]') + '.\n'
1625 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1626 light_yellow('[id=12]') + '.\n'
1628 light_green('del 12 ') + ' will delete tweet with ' + \
1629 light_yellow('[id=12]') + '.\n'
1630 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1631 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1632 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1633 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1634 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1635 light_yellow('[id=12]') + ' in your Pocket list.\n'
1639 def help_messages():
1646 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1647 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1648 light_green('inbox 7') + ' will show newest 7 messages.\n'
1649 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1650 light_yellow('[thread_id=2]') + '.\n'
1651 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1652 magenta('@dtvd88') + '.\n'
1653 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1654 light_yellow('[message_id=5]') + '.\n'
1658 def help_friends_and_followers():
1660 Friends and Followers
1663 # Follower and following
1665 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1667 light_green('ls fl') + \
1668 ' will list all followers (people who are following you).\n'
1670 light_green('ls fr') + \
1671 ' will list all friends (people who you are following).\n'
1672 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1673 magenta('@dtvd88') + '.\n'
1674 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1675 magenta('@dtvd88') + '.\n'
1676 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1677 magenta('@dtvd88') + '.\n'
1678 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1679 magenta('@dtvd88') + '.\n'
1680 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1681 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1682 magenta('@dtvd88') + '.\n'
1683 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1684 magenta('@dtvd88') + '.\n'
1685 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1686 magenta('@dtvd88') + ' as a spam account.\n'
1697 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1698 usage
+= s
* 2 + light_green('list') + \
1699 ' will show all lists you are belong to.\n'
1700 usage
+= s
* 2 + light_green('list home') + \
1701 ' will show timeline of list. You will be asked for list\'s name.\n'
1702 usage
+= s
* 2 + light_green('list all_mem') + \
1703 ' will show list\'s all members.\n'
1704 usage
+= s
* 2 + light_green('list all_sub') + \
1705 ' will show list\'s all subscribers.\n'
1706 usage
+= s
* 2 + light_green('list add') + \
1707 ' will add specific person to a list owned by you.' + \
1708 ' You will be asked for list\'s name and person\'s name.\n'
1709 usage
+= s
* 2 + light_green('list rm') + \
1710 ' will remove specific person from a list owned by you.' + \
1711 ' You will be asked for list\'s name and person\'s name.\n'
1712 usage
+= s
* 2 + light_green('list sub') + \
1713 ' will subscribe you to a specific list.\n'
1714 usage
+= s
* 2 + light_green('list unsub') + \
1715 ' will unsubscribe you from a specific list.\n'
1716 usage
+= s
* 2 + light_green('list own') + \
1717 ' will show all list owned by you.\n'
1718 usage
+= s
* 2 + light_green('list new') + \
1719 ' will create a new list.\n'
1720 usage
+= s
* 2 + light_green('list update') + \
1721 ' will update a list owned by you.\n'
1722 usage
+= s
* 2 + light_green('list del') + \
1723 ' will delete a list owned by you.\n'
1734 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1735 usage
+= s
* 2 + light_green('switch public #AKB') + \
1736 ' will switch to public stream and follow "' + \
1737 light_yellow('AKB') + '" keyword.\n'
1738 usage
+= s
* 2 + light_green('switch mine') + \
1739 ' will switch to your personal stream.\n'
1740 usage
+= s
* 2 + light_green('switch mine -f ') + \
1741 ' will prompt to enter the filter.\n'
1742 usage
+= s
* 3 + light_yellow('Only nicks') + \
1743 ' filter will decide nicks will be INCLUDE ONLY.\n'
1744 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1745 ' filter will decide nicks will be EXCLUDE.\n'
1746 usage
+= s
* 2 + light_green('switch list') + \
1747 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1756 h
, w
= os
.popen('stty size', 'r').read().split()
1759 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1760 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1761 usage
+= s
+ 'You are ' + \
1762 light_yellow('already') + ' on your personal stream.\n'
1763 usage
+= s
+ 'Any update from Twitter will show up ' + \
1764 light_yellow('immediately') + '.\n'
1765 usage
+= s
+ 'In addition, following commands are available right now:\n'
1766 # Twitter help section
1768 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1769 usage
+= s
* 2 + light_green('h discover') + \
1770 ' will show help for discover commands.\n'
1771 usage
+= s
* 2 + light_green('h tweets') + \
1772 ' will show help for tweets commands.\n'
1773 usage
+= s
* 2 + light_green('h messages') + \
1774 ' will show help for messages commands.\n'
1775 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1776 ' will show help for friends and followers commands.\n'
1777 usage
+= s
* 2 + light_green('h list') + \
1778 ' will show help for list commands.\n'
1779 usage
+= s
* 2 + light_green('h stream') + \
1780 ' will show help for stream commands.\n'
1783 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1784 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1785 'will be evaluate by Python interpreter.\n'
1786 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1787 ' for current month.\n'
1790 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1791 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1792 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1793 ' theme immediately.\n'
1794 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1796 light_green('config ASCII_ART') + ' will output current value of ' +\
1797 light_yellow('ASCII_ART') + ' config key.\n'
1799 light_green('config TREND_MAX default') + ' will output default value of ' + \
1800 light_yellow('TREND_MAX') + ' config key.\n'
1802 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1803 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1805 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1806 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1807 light_yellow('True') + '.\n'
1810 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1811 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1812 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1813 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1814 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1815 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1816 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1819 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1820 usage
+= s
+ 'Have fun and hang tight! \n'
1823 'discover': help_discover
,
1824 'tweets': help_tweets
,
1825 'messages': help_messages
,
1826 'friends_and_followers': help_friends_and_followers
,
1828 'stream': help_stream
,
1833 lambda: printNicely(red('No such command.'))
1841 Pause stream display
1844 printNicely(green('Stream is paused'))
1852 printNicely(green('Stream is running back now'))
1868 printNicely(green('See you next time :)'))
1876 Reset prefix of line
1879 if c
.get('USER_JSON_ERROR'):
1880 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1881 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1883 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1886 printNicely(str(eval(g
['cmd'])))
1941 # Handle function set
1996 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2001 Listen to user's input
2006 ['public', 'mine', 'list'], # switch
2015 [], # view_my_tweets
2026 ['image'], # show image
2028 ['fl', 'fr'], # list
2030 [i
for i
in g
['message_threads']], # sent
2055 [key
for key
in dict(get_all_config())], # config
2056 g
['themes'], # theme
2061 'friends_and_followers',
2073 init_interactive_shell(d
)
2080 # Only use PREFIX as a string with raw_input
2081 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2084 # Save cmd to compare with readline buffer
2085 g
['cmd'] = line
.strip()
2086 # Get short cmd to pass to handle function
2088 cmd
= line
.split()[0]
2091 # Lock the semaphore
2093 # Save cmd to global variable and call process
2094 g
['stuff'] = ' '.join(line
.split()[1:])
2095 # Check tweet length
2096 # Process the command
2099 if cmd
in ['switch', 't', 'rt', 'rep']:
2105 except TwitterHTTPError
as e
:
2106 detail_twitter_error(e
)
2109 printNicely(red('OMG something is wrong with Twitter API right now.'))
2111 # Release the semaphore lock
2115 def reconn_notice():
2117 Notice when Hangup or Timeout
2119 guide
= light_magenta('You can use ') + \
2120 light_green('switch') + \
2121 light_magenta(' command to return to your stream.\n')
2122 guide
+= light_magenta('Type ') + \
2123 light_green('h stream') + \
2124 light_magenta(' for more details.')
2126 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2130 def stream(domain
, args
, name
='Rainbow Stream'):
2136 c
['USER_DOMAIN']: name
,
2137 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2138 c
['SITE_DOMAIN']: name
,
2141 ascii_art(art_dict
.get(domain
, name
))
2142 # These arguments are optional:
2144 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2146 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2149 if args
.track_keywords
:
2150 query_args
['track'] = args
.track_keywords
2154 time
.sleep(polling_time
)
2157 def spawn_public_stream(args
, keyword
=None):
2159 Spawn a new public stream
2161 # Only set keyword if specified
2163 if keyword
[0] == '#':
2164 keyword
= keyword
[1:]
2165 args
.track_keywords
= keyword
2166 g
['keyword'] = keyword
2168 g
['keyword'] = 'Global'
2169 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2172 th
= threading
.Thread(
2181 def spawn_list_stream(args
, stuff
=None):
2183 Spawn a new list stream
2186 owner
, slug
= check_slug(stuff
)
2188 owner
, slug
= get_slug()
2190 # Force python 2 not redraw readline buffer
2191 listname
= '/'.join([owner
, slug
])
2192 # Set the listname variable
2193 # and reset tracked keyword
2194 g
['listname'] = listname
2196 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2197 listname
=g
['listname']
2199 printNicely(light_yellow('getting list members ...'))
2201 t
= Twitter(auth
=authen())
2204 while next_cursor
!= 0:
2205 m
= t
.lists
.members(
2207 owner_screen_name
=owner
,
2209 include_entities
=False)
2210 for u
in m
['users']:
2211 members
.append('@' + u
['screen_name'])
2212 next_cursor
= m
['next_cursor']
2213 printNicely(light_yellow('... done.'))
2214 # Build thread filter array
2215 args
.filter = members
2217 th
= threading
.Thread(
2227 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2229 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2233 def spawn_personal_stream(args
, stuff
=None):
2235 Spawn a new personal stream
2237 # Reset the tracked keyword and listname
2238 g
['keyword'] = g
['listname'] = ''
2240 g
['PREFIX'] = u2str(emojize(format_prefix()))
2242 th
= threading
.Thread(
2247 g
['original_name']))
2257 args
= parse_arguments()
2261 # Twitter API connection problem
2262 except TwitterHTTPError
as e
:
2265 magenta('We have connection problem with twitter REST API right now :('))
2266 detail_twitter_error(e
)
2269 # Proxy connection problem
2270 except (socks
.ProxyConnectionError
, URLError
):
2272 magenta('There seems to be a connection problem.'))
2274 magenta('You might want to check your proxy settings (host, port and type)!'))
2278 # Spawn stream thread
2279 target
= args
.stream
.split()[0]
2280 if target
== 'mine':
2281 spawn_personal_stream(args
)
2284 stuff
= args
.stream
.split()[1]
2288 'public': spawn_public_stream
,
2289 'list': spawn_list_stream
,
2291 spawn_dict
.get(target
)(args
, stuff
)
2293 # Start listen process