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']
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
)
339 g
['since_id'] = result
[0]
340 for tweet
in reversed(result
):
348 t
= Twitter(auth
=authen())
349 num
= c
['HOME_TWEET_NUM']
350 if g
['stuff'].isdigit():
351 num
= int(g
['stuff'])
352 kwargs
= {'count': num
}
353 kwargs
= add_tweetmode_parameter(kwargs
)
354 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
364 for e
in c
['events']:
368 printNicely(magenta('Nothing at this time.'))
375 t
= Twitter(auth
=authen())
376 num
= c
['HOME_TWEET_NUM']
377 if g
['stuff'].isdigit():
378 num
= int(g
['stuff'])
379 kwargs
= {'count': num
}
380 kwargs
= add_tweetmode_parameter(kwargs
)
381 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
388 Show profile of a specific user
390 t
= Twitter(auth
=authen())
392 screen_name
= g
['stuff'].split()[0]
394 printNicely(red('Sorry I can\'t understand.'))
396 if screen_name
.startswith('@'):
399 screen_name
=screen_name
[1:],
400 include_entities
=False)
404 printNicely(red('No user.'))
406 printNicely(red('A name should begin with a \'@\''))
413 t
= Twitter(auth
=authen())
415 user
= g
['stuff'].split()[0]
417 printNicely(red('Sorry I can\'t understand.'))
421 num
= int(g
['stuff'].split()[1])
423 num
= c
['HOME_TWEET_NUM']
424 kwargs
= {'count': num
, 'screen_name': user
[1:]}
425 kwargs
= add_tweetmode_parameter(kwargs
)
426 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
430 printNicely(red('A name should begin with a \'@\''))
433 def view_my_tweets():
435 Display user's recent tweets.
437 t
= Twitter(auth
=authen())
439 num
= int(g
['stuff'])
441 num
= c
['HOME_TWEET_NUM']
442 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
443 kwargs
= add_tweetmode_parameter(kwargs
)
444 for tweet
in reversed(
445 t
.statuses
.user_timeline(**kwargs
)):
454 t
= Twitter(auth
=authen())
456 query
= g
['stuff'].strip()
458 printNicely(red('Sorry I can\'t understand.'))
460 type = c
['SEARCH_TYPE']
461 if type not in ['mixed', 'recent', 'popular']:
463 max_record
= c
['SEARCH_MAX_RECORD']
464 count
= min(max_record
, 100)
470 kwargs
= add_tweetmode_parameter(kwargs
)
472 rel
= t
.search
.tweets(**kwargs
)['statuses']
475 printNicely('Newest tweets:')
476 for i
in reversed(xrange(count
)):
477 draw(t
=rel
[i
], keyword
=query
)
480 printNicely(magenta('I\'m afraid there is no result'))
487 t
= Twitter(auth
=authen())
488 t
.statuses
.update(status
=g
['stuff'])
493 Add new link to Pocket along with tweet id
495 if not c
['POCKET_SUPPORT']:
496 printNicely(yellow('Pocket isn\'t enabled.'))
497 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
503 t
= Twitter(auth
=authen())
505 id = int(g
['stuff'].split()[0])
506 tid
= c
['tweet_dict'][id]
508 printNicely(red('Sorry I can\'t understand.'))
511 tweet
= t
.statuses
.show(id=tid
)
513 if len(tweet
['entities']['urls']) > 0:
514 url
= tweet
['entities']['urls'][0]['expanded_url']
516 url
= "https://twitter.com/" + \
517 tweet
['user']['screen_name'] + '/status/' + str(tid
)
521 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
525 printNicely(red('Something is wrong about your Pocket account,'+ \
526 ' please restart Rainbowstream.'))
527 pocket_credential
= os
.environ
.get(
531 '')) + os
.sep
+ '.rainbow_pckt_oauth'
532 if os
.path
.exists(pocket_credential
):
533 os
.remove(pocket_credential
)
536 printNicely(green('Pocketed !'))
544 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 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
559 t
= Twitter(auth
=authen())
561 id = int(g
['stuff'].split()[0])
563 printNicely(red('Sorry I can\'t understand.'))
565 tid
= c
['tweet_dict'][id]
567 kwargs
= add_tweetmode_parameter(kwargs
)
568 tweet
= t
.statuses
.show(**kwargs
)
570 formater
= format_quote(tweet
)
574 prefix
= light_magenta('Compose your ', rl
=True) + \
575 light_green('#comment: ', rl
=True)
576 comment
= raw_input(prefix
)
578 quote
= comment
.join(formater
.split('#comment'))
579 t
.statuses
.update(status
=quote
)
581 printNicely(light_magenta('No text added.'))
588 t
= Twitter(auth
=authen())
591 id = int(g
['stuff'].split()[0])
593 printNicely(red('Sorry I can\'t understand.'))
595 tid
= c
['tweet_dict'][id]
596 # Get display num if exist
598 num
= int(g
['stuff'].split()[1])
600 num
= c
['RETWEETS_SHOW_NUM']
601 # Get result and display
602 kwargs
= {'id': tid
, 'count': num
}
603 kwargs
= add_tweetmode_parameter(kwargs
)
604 rt_ary
= t
.statuses
.retweets(**kwargs
)
606 printNicely(magenta('This tweet has no retweet.'))
608 for tweet
in reversed(rt_ary
):
617 t
= Twitter(auth
=authen())
619 id = int(g
['stuff'].split()[0])
621 printNicely(red('Sorry I can\'t understand.'))
623 tid
= c
['tweet_dict'][id]
625 kwargs
= add_tweetmode_parameter(kwargs
)
626 tweet
= t
.statuses
.show(**kwargs
)
627 limit
= c
['CONVERSATION_MAX']
629 thread_ref
.append(tweet
)
630 prev_tid
= tweet
['in_reply_to_status_id']
631 while prev_tid
and limit
:
633 kwargs
['id'] = prev_tid
634 tweet
= t
.statuses
.show(**kwargs
)
635 prev_tid
= tweet
['in_reply_to_status_id']
636 thread_ref
.append(tweet
)
638 for tweet
in reversed(thread_ref
):
647 t
= Twitter(auth
=authen())
649 id = int(g
['stuff'].split()[0])
651 printNicely(red('Sorry I can\'t understand.'))
653 tid
= c
['tweet_dict'][id]
654 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
655 status
= ' '.join(g
['stuff'].split()[1:])
656 # don't include own username for tweet chains
657 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
658 if user
== g
['original_name']:
659 status
= str2u(status
)
661 status
= '@' + user
+ ' ' + str2u(status
)
662 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
669 t
= Twitter(auth
=authen())
671 id = int(g
['stuff'].split()[0])
673 printNicely(red('Sorry I can\'t understand.'))
675 tid
= c
['tweet_dict'][id]
676 original_tweet
= t
.statuses
.show(id=tid
)
677 text
= original_tweet
['text']
678 nick_ary
= [original_tweet
['user']['screen_name']]
679 for user
in list(original_tweet
['entities']['user_mentions']):
680 if user
['screen_name'] not in nick_ary \
681 and user
['screen_name'] != g
['original_name']:
682 nick_ary
.append(user
['screen_name'])
683 status
= ' '.join(g
['stuff'].split()[1:])
684 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
685 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
692 t
= Twitter(auth
=authen())
694 id = int(g
['stuff'].split()[0])
696 printNicely(red('Sorry I can\'t understand.'))
698 tid
= c
['tweet_dict'][id]
699 t
.favorites
.create(_id
=tid
, include_entities
=False)
700 printNicely(green('Favorited.'))
702 kwargs
= add_tweetmode_parameter(kwargs
)
703 draw(t
.statuses
.show(**kwargs
))
711 t
= Twitter(auth
=authen())
713 id = int(g
['stuff'].split()[0])
715 printNicely(red('Sorry I can\'t understand.'))
717 tid
= c
['tweet_dict'][id]
718 t
.favorites
.destroy(_id
=tid
)
719 printNicely(green('Okay it\'s unfavorited.'))
721 kwargs
= add_tweetmode_parameter(kwargs
)
722 draw(t
.statuses
.show(**kwargs
))
728 Copy url of a tweet to clipboard
730 t
= Twitter(auth
=authen())
732 id = int(g
['stuff'].split()[0])
733 tid
= c
['tweet_dict'][id]
735 printNicely(red('Tweet id is not valid.'))
738 kwargs
= add_tweetmode_parameter(kwargs
)
739 tweet
= t
.statuses
.show(**kwargs
)
740 url
= 'https://twitter.com/' + \
741 tweet
['user']['screen_name'] + '/status/' + str(tid
)
743 if platform
.system().lower() == 'darwin':
744 os
.system("echo '%s' | pbcopy" % url
)
745 printNicely(green('Copied tweet\'s url to clipboard.'))
747 printNicely('Direct link: ' + yellow(url
))
754 t
= Twitter(auth
=authen())
756 id = int(g
['stuff'].split()[0])
758 printNicely(red('Sorry I can\'t understand.'))
760 tid
= c
['tweet_dict'][id]
761 t
.statuses
.destroy(id=tid
)
762 printNicely(green('Okay it\'s gone.'))
769 t
= Twitter(auth
=authen())
771 target
= g
['stuff'].split()[0]
772 if target
!= 'image':
774 id = int(g
['stuff'].split()[1])
775 tid
= c
['tweet_dict'][id]
776 tweet
= t
.statuses
.show(id=tid
)
777 media
= tweet
['entities']['media']
779 res
= requests
.get(m
['media_url'])
780 img
= Image
.open(BytesIO(res
.content
))
784 printNicely(red('Sorry I can\'t show this image.'))
791 t
= Twitter(auth
=authen())
793 if not g
['stuff'].isdigit():
795 tid
= c
['tweet_dict'][int(g
['stuff'])]
796 tweet
= t
.statuses
.show(id=tid
)
797 urls
= tweet
['entities']['urls']
799 printNicely(light_magenta('No url here @.@!'))
803 expanded_url
= url
['expanded_url']
804 webbrowser
.open(expanded_url
)
807 printNicely(red('Sorry I can\'t open url in this tweet.'))
814 t
= Twitter(auth
=authen())
815 num
= c
['MESSAGES_DISPLAY']
816 if g
['stuff'].isdigit():
822 inbox
= inbox
+ t
.direct_messages(
825 include_entities
=False,
830 inbox
= inbox
+ t
.direct_messages(
833 include_entities
=False,
837 num
= c
['MESSAGES_DISPLAY']
838 if g
['stuff'].isdigit():
843 sent
= sent
+ t
.direct_messages
.sent(
846 include_entities
=False,
851 sent
= sent
+ t
.direct_messages
.sent(
854 include_entities
=False,
859 uniq_inbox
= list(set(
860 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
862 uniq_sent
= list(set(
863 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
865 for partner
in uniq_inbox
:
866 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
868 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
869 d
[partner
] = inbox_ary
+ sent_ary
870 for partner
in uniq_sent
:
873 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
874 g
['message_threads'] = print_threads(d
)
879 View a thread of message
882 thread_id
= int(g
['stuff'])
884 g
['message_threads'][thread_id
],
889 printNicely(red('No such thread.'))
894 Send a direct message
896 t
= Twitter(auth
=authen())
898 user
= g
['stuff'].split()[0]
899 if user
[0].startswith('@'):
900 content
= ' '.join(g
['stuff'].split()[1:])
901 t
.direct_messages
.new(
902 screen_name
=user
[1:],
905 printNicely(green('Message sent.'))
907 printNicely(red('A name should begin with a \'@\''))
910 printNicely(red('Sorry I can\'t understand.'))
917 t
= Twitter(auth
=authen())
919 id = int(g
['stuff'].split()[0])
921 printNicely(red('Sorry I can\'t understand.'))
922 mid
= c
['message_dict'][id]
923 t
.direct_messages
.destroy(id=mid
)
924 printNicely(green('Message deleted.'))
929 List friends for followers
931 t
= Twitter(auth
=authen())
934 name
= g
['stuff'].split()[1]
935 if name
.startswith('@'):
938 printNicely(red('A name should begin with a \'@\''))
939 raise Exception('Invalid name')
941 name
= g
['original_name']
942 # Get list followers or friends
944 target
= g
['stuff'].split()[0]
946 printNicely(red('Omg some syntax is wrong.'))
949 d
= {'fl': 'followers', 'fr': 'friends'}
953 printNicely('All ' + d
[target
] + ':')
957 while next_cursor
!= 0:
959 list = getattr(t
, d
[target
]).list(
963 include_entities
=False,
966 for u
in list['users']:
972 + cycle_color( u
['name'] ) \
973 + color_func(c
['TWEET']['nick'])( ' @' \
977 next_cursor
= list['next_cursor']
979 # 300 users means 15 calls to the related API. The rate limit is 15
980 # calls per 15mn periods (see Twitter documentation).
981 if ( number_of_users
% 300 == 0 ):
982 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
983 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
986 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
992 t
= Twitter(auth
=authen())
993 screen_name
= g
['stuff'].split()[0]
994 if screen_name
.startswith('@'):
995 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
996 printNicely(green('You are following ' + screen_name
+ ' now!'))
998 printNicely(red('A name should begin with a \'@\''))
1005 t
= Twitter(auth
=authen())
1006 screen_name
= g
['stuff'].split()[0]
1007 if screen_name
.startswith('@'):
1008 t
.friendships
.destroy(
1009 screen_name
=screen_name
[1:],
1010 include_entities
=False)
1011 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
1013 printNicely(red('A name should begin with a \'@\''))
1020 t
= Twitter(auth
=authen())
1022 screen_name
= g
['stuff'].split()[0]
1024 printNicely(red('A name should be specified. '))
1026 if screen_name
.startswith('@'):
1028 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1029 if isinstance(rel
, dict):
1030 printNicely(green(screen_name
+ ' is muted.'))
1031 c
['IGNORE_LIST'] += [screen_name
]
1032 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1034 printNicely(red(rel
))
1037 printNicely(red('Something is wrong, can not mute now :('))
1039 printNicely(red('A name should begin with a \'@\''))
1046 t
= Twitter(auth
=authen())
1048 screen_name
= g
['stuff'].split()[0]
1050 printNicely(red('A name should be specified. '))
1052 if screen_name
.startswith('@'):
1054 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1055 if isinstance(rel
, dict):
1056 printNicely(green(screen_name
+ ' is unmuted.'))
1057 c
['IGNORE_LIST'].remove(screen_name
)
1059 printNicely(red(rel
))
1061 printNicely(red('Maybe you are not muting this person ?'))
1063 printNicely(red('A name should begin with a \'@\''))
1070 # Get dict of muting users
1071 md
= build_mute_dict(dict_data
=True)
1072 printNicely('All: ' + str(len(md
)) + ' people.')
1074 user
= ' ' + cycle_color(md
[name
])
1075 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1077 # Update from Twitter
1078 c
['IGNORE_LIST'] = [n
for n
in md
]
1085 t
= Twitter(auth
=authen())
1086 screen_name
= g
['stuff'].split()[0]
1087 if screen_name
.startswith('@'):
1089 screen_name
=screen_name
[1:],
1090 include_entities
=False,
1092 printNicely(green('You blocked ' + screen_name
+ '.'))
1094 printNicely(red('A name should begin with a \'@\''))
1101 t
= Twitter(auth
=authen())
1102 screen_name
= g
['stuff'].split()[0]
1103 if screen_name
.startswith('@'):
1105 screen_name
=screen_name
[1:],
1106 include_entities
=False,
1108 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1110 printNicely(red('A name should begin with a \'@\''))
1115 Report a user as a spam account
1117 t
= Twitter(auth
=authen())
1118 screen_name
= g
['stuff'].split()[0]
1119 if screen_name
.startswith('@'):
1120 t
.users
.report_spam(
1121 screen_name
=screen_name
[1:])
1122 printNicely(green('You reported ' + screen_name
+ '.'))
1124 printNicely(red('Sorry I can\'t understand.'))
1132 list_name
= raw_input(
1133 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1134 # Get list name and owner
1136 owner
, slug
= list_name
.split('/')
1137 if slug
.startswith('@'):
1142 light_magenta('List name should follow "@owner/list_name" format.'))
1143 raise Exception('Wrong list name')
1146 def check_slug(list_name
):
1150 # Get list name and owner
1152 owner
, slug
= list_name
.split('/')
1153 if slug
.startswith('@'):
1158 light_magenta('List name should follow "@owner/list_name" format.'))
1159 raise Exception('Wrong list name')
1166 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1170 printNicely(light_magenta('You belong to no lists :)'))
1177 owner
, slug
= get_slug()
1178 res
= t
.lists
.statuses(
1180 owner_screen_name
=owner
,
1181 count
=c
['LIST_MAX'],
1182 include_entities
=False)
1183 for tweet
in reversed(res
):
1188 def list_members(t
):
1192 owner
, slug
= get_slug()
1196 while next_cursor
!= 0:
1197 m
= t
.lists
.members(
1199 owner_screen_name
=owner
,
1201 include_entities
=False)
1202 for u
in m
['users']:
1203 rel
[u
['name']] = '@' + u
['screen_name']
1204 next_cursor
= m
['next_cursor']
1205 printNicely('All: ' + str(len(rel
)) + ' members.')
1207 user
= ' ' + cycle_color(name
)
1208 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1212 def list_subscribers(t
):
1216 owner
, slug
= get_slug()
1220 while next_cursor
!= 0:
1221 m
= t
.lists
.subscribers(
1223 owner_screen_name
=owner
,
1225 include_entities
=False)
1226 for u
in m
['users']:
1227 rel
[u
['name']] = '@' + u
['screen_name']
1228 next_cursor
= m
['next_cursor']
1229 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1231 user
= ' ' + cycle_color(name
)
1232 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1238 Add specific user to a list
1240 owner
, slug
= get_slug()
1242 user_name
= raw_input(
1244 'Give me name of the newbie: ',
1246 if user_name
.startswith('@'):
1247 user_name
= user_name
[1:]
1249 t
.lists
.members
.create(
1251 owner_screen_name
=owner
,
1252 screen_name
=user_name
)
1253 printNicely(green('Added.'))
1256 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1261 Remove specific user from a list
1263 owner
, slug
= get_slug()
1265 user_name
= raw_input(
1267 'Give me name of the unlucky one: ',
1269 if user_name
.startswith('@'):
1270 user_name
= user_name
[1:]
1272 t
.lists
.members
.destroy(
1274 owner_screen_name
=owner
,
1275 screen_name
=user_name
)
1276 printNicely(green('Gone.'))
1279 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1282 def list_subscribe(t
):
1286 owner
, slug
= get_slug()
1289 t
.lists
.subscribers
.create(
1291 owner_screen_name
=owner
)
1292 printNicely(green('Done.'))
1296 light_magenta('I\'m sorry you can not subscribe to this list.'))
1299 def list_unsubscribe(t
):
1303 owner
, slug
= get_slug()
1306 t
.lists
.subscribers
.destroy(
1308 owner_screen_name
=owner
)
1309 printNicely(green('Done.'))
1313 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1322 while next_cursor
!= 0:
1323 res
= t
.lists
.ownerships(
1324 screen_name
=g
['original_name'],
1327 next_cursor
= res
['next_cursor']
1331 printNicely(light_magenta('You own no lists :)'))
1338 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1341 'New list\'s mode (public/private): ',
1343 description
= raw_input(
1345 'New list\'s description: ',
1351 description
=description
)
1352 printNicely(green(name
+ ' list is created.'))
1355 printNicely(red('Oops something is wrong with Twitter :('))
1364 'Your list that you want to update: ',
1368 'Update name (leave blank to unchange): ',
1370 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1371 description
= raw_input(light_magenta('Update description: ', rl
=True))
1375 slug
='-'.join(slug
.split()),
1376 owner_screen_name
=g
['original_name'],
1379 description
=description
)
1383 owner_screen_name
=g
['original_name'],
1385 description
=description
)
1386 printNicely(green(slug
+ ' list is updated.'))
1389 printNicely(red('Oops something is wrong with Twitter :('))
1398 'Your list that you want to delete: ',
1402 slug
='-'.join(slug
.split()),
1403 owner_screen_name
=g
['original_name'])
1404 printNicely(green(slug
+ ' list is deleted.'))
1407 printNicely(red('Oops something is wrong with Twitter :('))
1414 t
= Twitter(auth
=authen())
1415 # List all lists or base on action
1417 g
['list_action'] = g
['stuff'].split()[0]
1424 'all_mem': list_members
,
1425 'all_sub': list_subscribers
,
1428 'sub': list_subscribe
,
1429 'unsub': list_unsubscribe
,
1432 'update': list_update
,
1436 return action_ary
[g
['list_action']](t
)
1438 printNicely(red('Please try again.'))
1446 target
= g
['stuff'].split()[0]
1448 args
= parse_arguments()
1450 if g
['stuff'].split()[-1] == '-f':
1451 guide
= 'To ignore an option, just hit Enter key.'
1452 printNicely(light_magenta(guide
))
1453 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1454 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1455 args
.filter = list(filter(None, only
.split(',')))
1456 args
.ignore
= list(filter(None, ignore
.split(',')))
1458 printNicely(red('Sorry, wrong format.'))
1461 g
['stream_stop'] = True
1463 stuff
= g
['stuff'].split()[1]
1468 'public': spawn_public_stream
,
1469 'list': spawn_list_stream
,
1470 'mine': spawn_personal_stream
,
1472 spawn_dict
.get(target
)(args
, stuff
)
1475 printNicely(red('Sorry I can\'t understand.'))
1480 Unix's command `cal`
1483 rel
= os
.popen('cal').read().split('\n')
1486 show_calendar(month
, date
, rel
)
1491 List and change theme
1495 for theme
in g
['themes']:
1496 line
= light_magenta(theme
)
1497 if c
['THEME'] == theme
:
1498 line
= ' ' * 2 + light_yellow('* ') + line
1500 line
= ' ' * 4 + line
1506 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1507 # Redefine decorated_name
1508 g
['decorated_name'] = lambda x
: color_func(
1509 c
['DECORATED_NAME'])(
1511 printNicely(green('Theme changed.'))
1513 printNicely(red('No such theme exists.'))
1518 Browse and change config
1520 all_config
= get_all_config()
1521 g
['stuff'] = g
['stuff'].strip()
1524 for k
in all_config
:
1526 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1528 guide
= 'Detailed explanation can be found at ' + \
1529 color_func(c
['TWEET']['link'])(
1530 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1532 # Print specific config
1533 elif len(g
['stuff'].split()) == 1:
1534 if g
['stuff'] in all_config
:
1537 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1540 printNicely(red('No such config key.'))
1541 # Print specific config's default value
1542 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1543 key
= g
['stuff'].split()[0]
1545 value
= get_default_config(key
)
1546 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1550 printNicely(red('Just can not get the default.'))
1551 # Delete specific config key in config file
1552 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1553 key
= g
['stuff'].split()[0]
1556 printNicely(green('Config key is dropped.'))
1559 printNicely(red('Just can not drop the key.'))
1560 # Set specific config
1561 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1562 key
= g
['stuff'].split()[0]
1563 value
= g
['stuff'].split()[-1]
1564 if key
== 'THEME' and not validate_theme(value
):
1565 printNicely(red('Invalid theme\'s value.'))
1568 set_config(key
, value
)
1569 # Keys that needs to be apply immediately
1571 c
['THEME'] = reload_theme(value
, c
['THEME'])
1572 g
['decorated_name'] = lambda x
: color_func(
1573 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1574 elif key
== 'PREFIX':
1575 g
['PREFIX'] = u2str(emojize(format_prefix(
1576 listname
=g
['listname'],
1577 keyword
=g
['keyword']
1580 printNicely(green('Updated successfully.'))
1583 printNicely(red('Just can not set the key.'))
1585 printNicely(light_magenta('Sorry I can\'t understand.'))
1588 def help_discover():
1593 # Discover the world
1595 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1596 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1597 'You can try ' + light_green('trend US') + ' or ' + \
1598 light_green('trend JP Tokyo') + '.\n'
1599 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1600 light_green('home 7') + ' will show 7 tweets.\n'
1601 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1602 light_green('me 2') + ' will show your last 2 tweets.\n'
1604 light_green('notification') + ' will show your recent notification.\n'
1605 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1606 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1607 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1608 magenta('@mdo') + '.\n'
1609 usage
+= s
* 2 + light_green('view @mdo') + \
1610 ' will show ' + magenta('@mdo') + '\'s home.\n'
1611 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1612 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1613 'Search can be performed with or without hashtag.\n'
1624 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1625 usage
+= s
* 2 + light_green('t oops ') + \
1626 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1628 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1629 light_yellow('[id=12]') + '.\n'
1631 light_green('quote 12 ') + ' will quote the tweet with ' + \
1632 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1633 'the quote will be canceled.\n'
1635 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1636 light_yellow('[id=12]') + '.\n'
1637 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1638 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1639 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1640 light_yellow('oops') + '" to the owner of the tweet with ' + \
1641 light_yellow('[id=12]') + '.\n'
1642 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1643 light_yellow('oops') + '" to all people in the tweet with ' + \
1644 light_yellow('[id=12]') + '.\n'
1646 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1647 light_yellow('[id=12]') + '.\n'
1649 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1650 light_yellow('[id=12]') + '.\n'
1652 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1653 light_yellow('[id=12]') + '.\n'
1655 light_green('del 12 ') + ' will delete tweet with ' + \
1656 light_yellow('[id=12]') + '.\n'
1657 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1658 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1659 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1660 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1661 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1662 light_yellow('[id=12]') + ' in your Pocket list.\n'
1666 def help_messages():
1673 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1674 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1675 light_green('inbox 7') + ' will show newest 7 messages.\n'
1676 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1677 light_yellow('[thread_id=2]') + '.\n'
1678 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1679 magenta('@dtvd88') + '.\n'
1680 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1681 light_yellow('[message_id=5]') + '.\n'
1685 def help_friends_and_followers():
1687 Friends and Followers
1690 # Follower and following
1692 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1694 light_green('ls fl') + \
1695 ' will list all followers (people who are following you).\n'
1697 light_green('ls fr') + \
1698 ' will list all friends (people who you are following).\n'
1699 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1700 magenta('@dtvd88') + '.\n'
1701 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1702 magenta('@dtvd88') + '.\n'
1703 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1704 magenta('@dtvd88') + '.\n'
1705 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1706 magenta('@dtvd88') + '.\n'
1707 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1708 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1709 magenta('@dtvd88') + '.\n'
1710 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1711 magenta('@dtvd88') + '.\n'
1712 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1713 magenta('@dtvd88') + ' as a spam account.\n'
1724 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1725 usage
+= s
* 2 + light_green('list') + \
1726 ' will show all lists you are belong to.\n'
1727 usage
+= s
* 2 + light_green('list home') + \
1728 ' will show timeline of list. You will be asked for list\'s name.\n'
1729 usage
+= s
* 2 + light_green('list all_mem') + \
1730 ' will show list\'s all members.\n'
1731 usage
+= s
* 2 + light_green('list all_sub') + \
1732 ' will show list\'s all subscribers.\n'
1733 usage
+= s
* 2 + light_green('list add') + \
1734 ' will add specific person to a list owned by you.' + \
1735 ' You will be asked for list\'s name and person\'s name.\n'
1736 usage
+= s
* 2 + light_green('list rm') + \
1737 ' will remove specific person from a list owned by you.' + \
1738 ' You will be asked for list\'s name and person\'s name.\n'
1739 usage
+= s
* 2 + light_green('list sub') + \
1740 ' will subscribe you to a specific list.\n'
1741 usage
+= s
* 2 + light_green('list unsub') + \
1742 ' will unsubscribe you from a specific list.\n'
1743 usage
+= s
* 2 + light_green('list own') + \
1744 ' will show all list owned by you.\n'
1745 usage
+= s
* 2 + light_green('list new') + \
1746 ' will create a new list.\n'
1747 usage
+= s
* 2 + light_green('list update') + \
1748 ' will update a list owned by you.\n'
1749 usage
+= s
* 2 + light_green('list del') + \
1750 ' will delete a list owned by you.\n'
1761 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1762 usage
+= s
* 2 + light_green('switch public #AKB') + \
1763 ' will switch to public stream and follow "' + \
1764 light_yellow('AKB') + '" keyword.\n'
1765 usage
+= s
* 2 + light_green('switch mine') + \
1766 ' will switch to your personal stream.\n'
1767 usage
+= s
* 2 + light_green('switch mine -f ') + \
1768 ' will prompt to enter the filter.\n'
1769 usage
+= s
* 3 + light_yellow('Only nicks') + \
1770 ' filter will decide nicks will be INCLUDE ONLY.\n'
1771 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1772 ' filter will decide nicks will be EXCLUDE.\n'
1773 usage
+= s
* 2 + light_green('switch list') + \
1774 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1783 h
, w
= os
.popen('stty size', 'r').read().split()
1786 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1787 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1788 usage
+= s
+ 'You are ' + \
1789 light_yellow('already') + ' on your personal stream.\n'
1790 usage
+= s
+ 'Any update from Twitter will show up ' + \
1791 light_yellow('immediately') + '.\n'
1792 usage
+= s
+ 'In addition, following commands are available right now:\n'
1793 # Twitter help section
1795 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1796 usage
+= s
* 2 + light_green('h discover') + \
1797 ' will show help for discover commands.\n'
1798 usage
+= s
* 2 + light_green('h tweets') + \
1799 ' will show help for tweets commands.\n'
1800 usage
+= s
* 2 + light_green('h messages') + \
1801 ' will show help for messages commands.\n'
1802 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1803 ' will show help for friends and followers commands.\n'
1804 usage
+= s
* 2 + light_green('h list') + \
1805 ' will show help for list commands.\n'
1806 usage
+= s
* 2 + light_green('h stream') + \
1807 ' will show help for stream commands.\n'
1810 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1811 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1812 'will be evaluate by Python interpreter.\n'
1813 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1814 ' for current month.\n'
1817 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1818 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1819 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1820 ' theme immediately.\n'
1821 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1823 light_green('config ASCII_ART') + ' will output current value of ' +\
1824 light_yellow('ASCII_ART') + ' config key.\n'
1826 light_green('config TREND_MAX default') + ' will output default value of ' + \
1827 light_yellow('TREND_MAX') + ' config key.\n'
1829 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1830 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1832 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1833 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1834 light_yellow('True') + '.\n'
1837 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1838 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1839 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1840 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1841 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1842 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1843 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1846 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1847 usage
+= s
+ 'Have fun and hang tight! \n'
1850 'discover': help_discover
,
1851 'tweets': help_tweets
,
1852 'messages': help_messages
,
1853 'friends_and_followers': help_friends_and_followers
,
1855 'stream': help_stream
,
1860 lambda: printNicely(red('No such command.'))
1868 Pause stream display
1871 printNicely(green('Stream is paused'))
1879 printNicely(green('Stream is running back now'))
1895 printNicely(green('See you next time :)'))
1903 Reset prefix of line
1906 if c
.get('USER_JSON_ERROR'):
1907 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1908 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1910 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1913 printNicely(str(eval(g
['cmd'])))
1968 # Handle function set
2023 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2028 Listen to user's input
2033 ['public', 'mine', 'list'], # switch
2042 [], # view_my_tweets
2053 ['image'], # show image
2055 ['fl', 'fr'], # list
2057 [i
for i
in g
['message_threads']], # sent
2082 [key
for key
in dict(get_all_config())], # config
2083 g
['themes'], # theme
2088 'friends_and_followers',
2100 init_interactive_shell(d
)
2107 # Only use PREFIX as a string with raw_input
2108 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2111 # Save cmd to compare with readline buffer
2112 g
['cmd'] = line
.strip()
2113 # Get short cmd to pass to handle function
2115 cmd
= line
.split()[0]
2118 # Lock the semaphore
2120 # Save cmd to global variable and call process
2121 g
['stuff'] = ' '.join(line
.split()[1:])
2122 # Check tweet length
2123 # Process the command
2126 if cmd
in ['switch', 't', 'rt', 'rep']:
2132 except TwitterHTTPError
as e
:
2133 detail_twitter_error(e
)
2136 printNicely(red('OMG something is wrong with Twitter API right now.'))
2138 # Release the semaphore lock
2142 def reconn_notice():
2144 Notice when Hangup or Timeout
2146 guide
= light_magenta('You can use ') + \
2147 light_green('switch') + \
2148 light_magenta(' command to return to your stream.\n')
2149 guide
+= light_magenta('Type ') + \
2150 light_green('h stream') + \
2151 light_magenta(' for more details.')
2153 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2157 def stream(domain
, args
, name
='Rainbow Stream'):
2163 c
['USER_DOMAIN']: name
,
2164 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2165 c
['SITE_DOMAIN']: name
,
2168 ascii_art(art_dict
.get(domain
, name
))
2169 # These arguments are optional:
2171 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2173 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2176 if args
.track_keywords
:
2177 query_args
['track'] = args
.track_keywords
2181 time
.sleep(polling_time
)
2184 def spawn_public_stream(args
, keyword
=None):
2186 Spawn a new public stream
2188 # Only set keyword if specified
2190 if keyword
[0] == '#':
2191 keyword
= keyword
[1:]
2192 args
.track_keywords
= keyword
2193 g
['keyword'] = keyword
2195 g
['keyword'] = 'Global'
2196 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2199 th
= threading
.Thread(
2208 def spawn_list_stream(args
, stuff
=None):
2210 Spawn a new list stream
2213 owner
, slug
= check_slug(stuff
)
2215 owner
, slug
= get_slug()
2217 # Force python 2 not redraw readline buffer
2218 listname
= '/'.join([owner
, slug
])
2219 # Set the listname variable
2220 # and reset tracked keyword
2221 g
['listname'] = listname
2223 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2224 listname
=g
['listname']
2226 printNicely(light_yellow('getting list members ...'))
2228 t
= Twitter(auth
=authen())
2231 while next_cursor
!= 0:
2232 m
= t
.lists
.members(
2234 owner_screen_name
=owner
,
2236 include_entities
=False)
2237 for u
in m
['users']:
2238 members
.append('@' + u
['screen_name'])
2239 next_cursor
= m
['next_cursor']
2240 printNicely(light_yellow('... done.'))
2241 # Build thread filter array
2242 args
.filter = members
2244 th
= threading
.Thread(
2254 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2256 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2260 def spawn_personal_stream(args
, stuff
=None):
2262 Spawn a new personal stream
2264 # Reset the tracked keyword and listname
2265 g
['keyword'] = g
['listname'] = ''
2267 g
['PREFIX'] = u2str(emojize(format_prefix()))
2269 th
= threading
.Thread(
2274 g
['original_name']))
2284 args
= parse_arguments()
2288 # Twitter API connection problem
2289 except TwitterHTTPError
as e
:
2292 magenta('We have connection problem with twitter REST API right now :('))
2293 detail_twitter_error(e
)
2296 # Proxy connection problem
2297 except (socks
.ProxyConnectionError
, URLError
):
2299 magenta('There seems to be a connection problem.'))
2301 magenta('You might want to check your proxy settings (host, port and type)!'))
2305 # Spawn stream thread
2306 target
= args
.stream
.split()[0]
2307 if target
== 'mine':
2308 spawn_personal_stream(args
)
2311 stuff
= args
.stream
.split()[1]
2315 'public': spawn_public_stream
,
2316 'list': spawn_list_stream
,
2318 spawn_dict
.get(target
)(args
, stuff
)
2320 # Start listen process