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).')
95 default
=os
.environ
.get('HOME', os
.environ
.get('USERPROFILE', '')) + os
.sep
+ '.rainbow_oauth',
96 help='Specify which OAuth profile to use for twitter. Default: ~/.rainbow_oauth.')
100 default
=os
.environ
.get('HOME', os
.environ
.get('USERPROFILE', '')) + os
.sep
+ '.rainbow_pckt_oauth',
101 help='Specify which OAuth profile to use for pocket. Default: ~/.rainbow_pckt_oauth.')
102 return parser
.parse_args()
105 def proxy_connect(args
):
107 Connect to specified proxy
110 # Setup proxy by monkeypatching the standard lib
111 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
112 socks
.set_default_proxy(
113 socks
.SOCKS5
, args
.proxy_host
,
114 int(args
.proxy_port
))
115 elif args
.proxy_type
.lower() == "http":
116 socks
.set_default_proxy(
117 socks
.HTTP
, args
.proxy_host
,
118 int(args
.proxy_port
))
119 elif args
.proxy_type
.lower() == "socks4":
120 socks
.set_default_proxy(
121 socks
.SOCKS4
, args
.proxy_host
,
122 int(args
.proxy_port
))
125 magenta('Sorry, wrong proxy type specified! Aborting...'))
127 socket
.socket
= socks
.socksocket
132 Authenticate with Twitter OAuth
134 # When using rainbow stream you must authorize.
135 twitter_credential
= g
['twitter_oauth_path']
136 if not os
.path
.exists(twitter_credential
):
137 oauth_dance('Rainbow Stream',
141 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
151 Authenticate with Pocket OAuth
153 pocket_credential
= g
['pocket_oauth_path']
154 if not os
.path
.exists(pocket_credential
):
155 request_token
= Pocket
.get_request_token(consumer_key
=PCKT_CONSUMER_KEY
)
156 auth_url
= Pocket
.get_auth_url(code
=request_token
, redirect_uri
="/")
157 webbrowser
.open(auth_url
)
158 printNicely(green("*** Press [ENTER] after authorization ***"))
160 user_credentials
= Pocket
.get_credentials(consumer_key
=PCKT_CONSUMER_KEY
, code
=request_token
)
161 access_token
= user_credentials
['access_token']
162 f
= open(pocket_credential
, 'w')
163 f
.write(access_token
)
166 with
open(pocket_credential
, 'r') as f
:
167 access_token
= str(f
.readlines()[0])
170 return Pocket(PCKT_CONSUMER_KEY
, access_token
)
173 def build_mute_dict(dict_data
=False):
177 t
= Twitter(auth
=authen())
180 screen_name_list
= []
183 while next_cursor
!= 0:
184 list = t
.mutes
.users
.list(
185 screen_name
=g
['original_name'],
188 include_entities
=False,
190 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
191 name_list
+= [u
['name'] for u
in list['users']]
192 next_cursor
= list['next_cursor']
193 # Return dict or list
195 return dict(zip(screen_name_list
, name_list
))
197 return screen_name_list
202 Save traceback when run in debug mode
205 g
['traceback'].append(traceback
.format_exc())
208 def upgrade_center():
210 Check latest and notify to upgrade
213 current
= pkg_resources
.get_distribution('rainbowstream').version
214 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
215 readme
= requests
.get(url
).text
216 latest
= readme
.split('version = \'')[1].split('\'')[0]
217 g
['using_latest'] = current
== latest
218 if not g
['using_latest']:
219 notice
= light_magenta('RainbowStream latest version is ')
220 notice
+= light_green(latest
)
221 notice
+= light_magenta(' while your current version is ')
222 notice
+= light_yellow(current
) + '\n'
223 notice
+= light_magenta('You should upgrade with ')
224 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(')')
240 ctrl_c_handler
= lambda signum
, frame
: quit()
241 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
242 # Set OAuth file path (needs to happen before authen is called)
243 g
['twitter_oauth_path'] = args
.twitter_auth
244 g
['pocket_oauth_path'] = args
.pocket_auth
248 t
= Twitter(auth
=authen())
249 credential
= t
.account
.verify_credentials()
250 screen_name
= '@' + credential
['screen_name']
251 name
= credential
['name']
252 g
['id_str'] = credential
['id_str']
253 c
['original_name'] = g
['original_name'] = screen_name
[1:]
254 g
['listname'] = g
['keyword'] = ''
255 g
['PREFIX'] = u2str(emojize(format_prefix()))
256 g
['full_name'] = name
257 g
['decorated_name'] = lambda x
: color_func(
258 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
260 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
261 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
264 g
['message_threads'] = {}
267 # Debug option default = True
274 # Init tweet dict and message dict
276 c
['message_dict'] = []
278 c
['IMAGE_ON_TERM'] = args
.image_on_term
280 c
['24BIT'] = args
.color_24bit
281 # Check type of ONLY_LIST and IGNORE_LIST
282 if not isinstance(c
['ONLY_LIST'], list):
283 printNicely(red('ONLY_LIST is not a valid list value.'))
285 if not isinstance(c
['IGNORE_LIST'], list):
286 printNicely(red('IGNORE_LIST is not a valid list value.'))
287 c
['IGNORE_LIST'] = []
289 c
['IGNORE_LIST'] += build_mute_dict()
291 pckt
= pckt_authen() if c
['POCKET_SUPPORT'] else None
298 t
= Twitter(auth
=authen())
299 # Get country and town
301 country
= g
['stuff'].split()[0]
305 town
= g
['stuff'].split()[1]
308 avail
= t
.trends
.available()
311 trends
= t
.trends
.place(_id
=1)[0]['trends']
314 for location
in avail
:
315 # Search for country and Town
317 if location
['countryCode'] == country \
318 and location
['placeType']['name'] == 'Town' \
319 and location
['name'] == town
:
320 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
322 # Search for country only
324 if location
['countryCode'] == country \
325 and location
['placeType']['name'] == 'Country':
326 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
332 Fetch stream based on since_id
334 t
= Twitter(auth
=authen())
336 num
= c
['HOME_TWEET_NUM']
337 kwargs
= {'count': num
}
340 kwargs
['since_id'] = g
['since_id']
342 kwargs
= add_tweetmode_parameter(kwargs
)
343 result
= t
.statuses
.home_timeline(**kwargs
)
345 g
['since_id'] = result
[0]['id']
346 for tweet
in reversed(result
):
355 t
= Twitter(auth
=authen())
356 num
= c
['HOME_TWEET_NUM']
357 if g
['stuff'].isdigit():
358 num
= int(g
['stuff'])
359 kwargs
= {'count': num
}
360 kwargs
= add_tweetmode_parameter(kwargs
)
361 for tweet
in reversed(t
.statuses
.home_timeline(**kwargs
)):
371 for e
in c
['events']:
375 printNicely(magenta('Nothing at this time.'))
382 t
= Twitter(auth
=authen())
383 num
= c
['HOME_TWEET_NUM']
384 if g
['stuff'].isdigit():
385 num
= int(g
['stuff'])
386 kwargs
= {'count': num
}
387 kwargs
= add_tweetmode_parameter(kwargs
)
388 for tweet
in reversed(t
.statuses
.mentions_timeline(**kwargs
)):
395 Show profile of a specific user
397 t
= Twitter(auth
=authen())
399 screen_name
= g
['stuff'].split()[0]
401 printNicely(red('Sorry I can\'t understand.'))
403 if screen_name
.startswith('@'):
406 screen_name
=screen_name
[1:],
407 include_entities
=False)
411 printNicely(red('No user.'))
413 printNicely(red('A name should begin with a \'@\''))
420 t
= Twitter(auth
=authen())
422 user
= g
['stuff'].split()[0]
424 printNicely(red('Sorry I can\'t understand.'))
428 num
= int(g
['stuff'].split()[1])
430 num
= c
['HOME_TWEET_NUM']
431 kwargs
= {'count': num
, 'screen_name': user
[1:]}
432 kwargs
= add_tweetmode_parameter(kwargs
)
433 for tweet
in reversed(t
.statuses
.user_timeline(**kwargs
)):
437 printNicely(red('A name should begin with a \'@\''))
440 def view_my_tweets():
442 Display user's recent tweets.
444 t
= Twitter(auth
=authen())
446 num
= int(g
['stuff'])
448 num
= c
['HOME_TWEET_NUM']
449 kwargs
= {'count': num
, 'screen_name': g
['original_name']}
450 kwargs
= add_tweetmode_parameter(kwargs
)
451 for tweet
in reversed(
452 t
.statuses
.user_timeline(**kwargs
)):
461 t
= Twitter(auth
=authen())
463 query
= g
['stuff'].strip()
465 printNicely(red('Sorry I can\'t understand.'))
467 type = c
['SEARCH_TYPE']
468 if type not in ['mixed', 'recent', 'popular']:
470 max_record
= c
['SEARCH_MAX_RECORD']
471 count
= min(max_record
, 100)
477 kwargs
= add_tweetmode_parameter(kwargs
)
479 rel
= t
.search
.tweets(**kwargs
)['statuses']
482 printNicely('Newest tweets:')
483 for i
in reversed(xrange(min(len(rel
), count
))):
484 draw(t
=rel
[i
], keyword
=query
)
487 printNicely(magenta('I\'m afraid there is no result'))
494 t
= Twitter(auth
=authen())
495 t
.statuses
.update(status
=g
['stuff'])
500 Add new link to Pocket along with tweet id
502 if not c
['POCKET_SUPPORT']:
503 printNicely(yellow('Pocket isn\'t enabled.'))
504 printNicely(yellow('You need to "config POCKET_SUPPORT = true"'))
510 t
= Twitter(auth
=authen())
512 id = int(g
['stuff'].split()[0])
513 tid
= c
['tweet_dict'][id]
515 printNicely(red('Sorry I can\'t understand.'))
518 tweet
= t
.statuses
.show(id=tid
)
520 if len(tweet
['entities']['urls']) > 0:
521 url
= tweet
['entities']['urls'][0]['expanded_url']
523 url
= "https://twitter.com/" + \
524 tweet
['user']['screen_name'] + '/status/' + str(tid
)
528 p
.add(title
=re
.sub(r
'(http:\/\/\S+)', r
'', tweet
['text']),
532 printNicely(red('Something is wrong about your Pocket account,'+ \
533 ' please restart Rainbowstream.'))
534 pocket_credential
= os
.environ
.get(
538 '')) + os
.sep
+ '.rainbow_pckt_oauth'
539 if os
.path
.exists(pocket_credential
):
540 os
.remove(pocket_credential
)
543 printNicely(green('Pocketed !'))
551 t
= Twitter(auth
=authen())
553 id = int(g
['stuff'].split()[0])
555 printNicely(red('Sorry I can\'t understand.'))
557 tid
= c
['tweet_dict'][id]
558 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
566 t
= Twitter(auth
=authen())
568 id = int(g
['stuff'].split()[0])
570 printNicely(red('Sorry I can\'t understand.'))
572 tid
= c
['tweet_dict'][id]
574 kwargs
= add_tweetmode_parameter(kwargs
)
575 tweet
= t
.statuses
.show(**kwargs
)
577 formater
= format_quote(tweet
)
581 prefix
= light_magenta('Compose your ', rl
=True) + \
582 light_green('#comment: ', rl
=True)
583 comment
= raw_input(prefix
)
585 quote
= comment
.join(formater
.split('#comment'))
586 t
.statuses
.update(status
=quote
)
588 printNicely(light_magenta('No text added.'))
595 t
= Twitter(auth
=authen())
598 id = int(g
['stuff'].split()[0])
600 printNicely(red('Sorry I can\'t understand.'))
602 tid
= c
['tweet_dict'][id]
603 # Get display num if exist
605 num
= int(g
['stuff'].split()[1])
607 num
= c
['RETWEETS_SHOW_NUM']
608 # Get result and display
609 kwargs
= {'id': tid
, 'count': num
}
610 kwargs
= add_tweetmode_parameter(kwargs
)
611 rt_ary
= t
.statuses
.retweets(**kwargs
)
613 printNicely(magenta('This tweet has no retweet.'))
615 for tweet
in reversed(rt_ary
):
624 t
= Twitter(auth
=authen())
626 id = int(g
['stuff'].split()[0])
628 printNicely(red('Sorry I can\'t understand.'))
630 tid
= c
['tweet_dict'][id]
632 kwargs
= add_tweetmode_parameter(kwargs
)
633 tweet
= t
.statuses
.show(**kwargs
)
634 limit
= c
['CONVERSATION_MAX']
636 thread_ref
.append(tweet
)
637 prev_tid
= tweet
['in_reply_to_status_id']
638 while prev_tid
and limit
:
640 kwargs
['id'] = prev_tid
641 tweet
= t
.statuses
.show(**kwargs
)
642 prev_tid
= tweet
['in_reply_to_status_id']
643 thread_ref
.append(tweet
)
645 for tweet
in reversed(thread_ref
):
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 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
662 status
= ' '.join(g
['stuff'].split()[1:])
663 # don't include own username for tweet chains
664 # for details see issue https://github.com/DTVD/rainbowstream/issues/163
665 if user
== g
['original_name']:
666 status
= str2u(status
)
668 status
= '@' + user
+ ' ' + str2u(status
)
669 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
676 t
= Twitter(auth
=authen())
678 id = int(g
['stuff'].split()[0])
680 printNicely(red('Sorry I can\'t understand.'))
682 tid
= c
['tweet_dict'][id]
683 original_tweet
= t
.statuses
.show(id=tid
)
684 text
= original_tweet
['text']
685 nick_ary
= [original_tweet
['user']['screen_name']]
686 for user
in list(original_tweet
['entities']['user_mentions']):
687 if user
['screen_name'] not in nick_ary \
688 and user
['screen_name'] != g
['original_name']:
689 nick_ary
.append(user
['screen_name'])
690 status
= ' '.join(g
['stuff'].split()[1:])
691 status
= ' '.join(['@' + nick
for nick
in nick_ary
]) + ' ' + str2u(status
)
692 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
699 t
= Twitter(auth
=authen())
701 id = int(g
['stuff'].split()[0])
703 printNicely(red('Sorry I can\'t understand.'))
705 tid
= c
['tweet_dict'][id]
706 t
.favorites
.create(_id
=tid
, include_entities
=False)
707 printNicely(green('Favorited.'))
709 kwargs
= add_tweetmode_parameter(kwargs
)
710 draw(t
.statuses
.show(**kwargs
))
718 t
= Twitter(auth
=authen())
720 id = int(g
['stuff'].split()[0])
722 printNicely(red('Sorry I can\'t understand.'))
724 tid
= c
['tweet_dict'][id]
725 t
.favorites
.destroy(_id
=tid
)
726 printNicely(green('Okay it\'s unfavorited.'))
728 kwargs
= add_tweetmode_parameter(kwargs
)
729 draw(t
.statuses
.show(**kwargs
))
735 Copy url of a tweet to clipboard
737 t
= Twitter(auth
=authen())
739 id = int(g
['stuff'].split()[0])
740 tid
= c
['tweet_dict'][id]
742 printNicely(red('Tweet id is not valid.'))
745 kwargs
= add_tweetmode_parameter(kwargs
)
746 tweet
= t
.statuses
.show(**kwargs
)
747 url
= 'https://twitter.com/' + \
748 tweet
['user']['screen_name'] + '/status/' + str(tid
)
750 if platform
.system().lower() == 'darwin':
751 os
.system("echo '%s' | pbcopy" % url
)
752 printNicely(green('Copied tweet\'s url to clipboard.'))
754 printNicely('Direct link: ' + yellow(url
))
761 t
= Twitter(auth
=authen())
763 id = int(g
['stuff'].split()[0])
765 printNicely(red('Sorry I can\'t understand.'))
767 tid
= c
['tweet_dict'][id]
768 t
.statuses
.destroy(id=tid
)
769 printNicely(green('Okay it\'s gone.'))
776 t
= Twitter(auth
=authen())
778 target
= g
['stuff'].split()[0]
779 if target
!= 'image':
781 id = int(g
['stuff'].split()[1])
782 tid
= c
['tweet_dict'][id]
783 tweet
= t
.statuses
.show(id=tid
)
784 media
= tweet
['entities']['media']
786 res
= requests
.get(m
['media_url'])
787 img
= Image
.open(BytesIO(res
.content
))
791 printNicely(red('Sorry I can\'t show this image.'))
798 t
= Twitter(auth
=authen())
800 if not g
['stuff'].isdigit():
802 tid
= c
['tweet_dict'][int(g
['stuff'])]
803 tweet
= t
.statuses
.show(id=tid
)
804 urls
= tweet
['entities']['urls']
806 printNicely(light_magenta('No url here @.@!'))
810 expanded_url
= url
['expanded_url']
811 webbrowser
.open(expanded_url
)
814 printNicely(red('Sorry I can\'t open url in this tweet.'))
821 t
= Twitter(auth
=authen())
822 num
= c
['MESSAGES_DISPLAY']
823 if g
['stuff'].isdigit():
826 def inboxFilter(message
):
827 return message
['message_create']['sender_id'] == g
['id_str']
828 def sentFilter(message
):
829 return message
['message_create']['target']['recipient_id'] == g
['id_str']
831 def map_message(message
):
832 message_create
= message
['message_create']
833 sender
= t
.users
.show(id=int(message_create
['sender_id']),include_entities
=False)
834 recipient
= t
.users
.show(id=int(message_create
['target']['recipient_id']),include_entities
=False)
835 message
['sender_screen_name'] = sender
['screen_name']
836 message
['sender_name'] = sender
['name']
837 message
['recipient_screen_name'] = recipient
['screen_name']
838 message
['recipient_name'] = recipient
['name']
839 message
['text'] = message
['message_create']['message_data']['text']
840 message
['created_at'] = message
['created_timestamp']
844 messages
= t
.direct_messages
.events
.list()['events']
845 messages
= list(map(map_message
, messages
))
846 inbox
= list(filter(inboxFilter
, messages
))
847 sent
= list(filter(sentFilter
, messages
))
850 uniq_inbox
= list(set(
851 [(m
['sender_screen_name'], m
['sender_name']) for m
in inbox
]
853 uniq_sent
= list(set(
854 [(m
['recipient_screen_name'], m
['recipient_name']) for m
in sent
]
856 for partner
in uniq_inbox
:
857 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
859 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
860 d
[partner
] = inbox_ary
+ sent_ary
861 for partner
in uniq_sent
:
864 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
865 g
['message_threads'] = print_threads(d
)
870 View a thread of message
873 thread_id
= int(g
['stuff'])
875 g
['message_threads'][thread_id
],
880 printNicely(red('No such thread.'))
885 Send a direct message
887 t
= Twitter(auth
=authen())
889 user
= g
['stuff'].split()[0]
890 if user
[0].startswith('@'):
891 content
= ' '.join(g
['stuff'].split()[1:])
892 t
.direct_messages
.new(
893 screen_name
=user
[1:],
896 printNicely(green('Message sent.'))
898 printNicely(red('A name should begin with a \'@\''))
901 printNicely(red('Sorry I can\'t understand.'))
908 t
= Twitter(auth
=authen())
910 id = int(g
['stuff'].split()[0])
912 printNicely(red('Sorry I can\'t understand.'))
913 mid
= c
['message_dict'][id]
914 t
.direct_messages
.destroy(id=mid
)
915 printNicely(green('Message deleted.'))
920 List friends for followers
922 t
= Twitter(auth
=authen())
925 name
= g
['stuff'].split()[1]
926 if name
.startswith('@'):
929 printNicely(red('A name should begin with a \'@\''))
930 raise Exception('Invalid name')
932 name
= g
['original_name']
933 # Get list followers or friends
935 target
= g
['stuff'].split()[0]
937 printNicely(red('Omg some syntax is wrong.'))
940 d
= {'fl': 'followers', 'fr': 'friends'}
944 printNicely('All ' + d
[target
] + ':')
948 while next_cursor
!= 0:
950 list = getattr(t
, d
[target
]).list(
954 include_entities
=False,
957 for u
in list['users']:
963 + cycle_color( u
['name'] ) \
964 + color_func(c
['TWEET']['nick'])( ' @' \
968 next_cursor
= list['next_cursor']
970 # 300 users means 15 calls to the related API. The rate limit is 15
971 # calls per 15mn periods (see Twitter documentation).
972 if ( number_of_users
% 300 == 0 ):
973 printNicely(light_yellow( 'We reached the limit of Twitter API.' ))
974 printNicely(light_yellow( 'You may need to wait about 15 minutes.' ))
977 printNicely('All: ' + str(number_of_users
) + ' ' + d
[target
] + '.')
983 t
= Twitter(auth
=authen())
984 screen_name
= g
['stuff'].split()[0]
985 if screen_name
.startswith('@'):
986 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
987 printNicely(green('You are following ' + screen_name
+ ' now!'))
989 printNicely(red('A name should begin with a \'@\''))
996 t
= Twitter(auth
=authen())
997 screen_name
= g
['stuff'].split()[0]
998 if screen_name
.startswith('@'):
999 t
.friendships
.destroy(
1000 screen_name
=screen_name
[1:],
1001 include_entities
=False)
1002 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
1004 printNicely(red('A name should begin with a \'@\''))
1011 t
= Twitter(auth
=authen())
1013 screen_name
= g
['stuff'].split()[0]
1015 printNicely(red('A name should be specified. '))
1017 if screen_name
.startswith('@'):
1019 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
1020 if isinstance(rel
, dict):
1021 printNicely(green(screen_name
+ ' is muted.'))
1022 c
['IGNORE_LIST'] += [screen_name
]
1023 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
1025 printNicely(red(rel
))
1028 printNicely(red('Something is wrong, can not mute now :('))
1030 printNicely(red('A name should begin with a \'@\''))
1037 t
= Twitter(auth
=authen())
1039 screen_name
= g
['stuff'].split()[0]
1041 printNicely(red('A name should be specified. '))
1043 if screen_name
.startswith('@'):
1045 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
1046 if isinstance(rel
, dict):
1047 printNicely(green(screen_name
+ ' is unmuted.'))
1048 c
['IGNORE_LIST'].remove(screen_name
)
1050 printNicely(red(rel
))
1052 printNicely(red('Maybe you are not muting this person ?'))
1054 printNicely(red('A name should begin with a \'@\''))
1061 # Get dict of muting users
1062 md
= build_mute_dict(dict_data
=True)
1063 printNicely('All: ' + str(len(md
)) + ' people.')
1065 user
= ' ' + cycle_color(md
[name
])
1066 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
1068 # Update from Twitter
1069 c
['IGNORE_LIST'] = [n
for n
in md
]
1076 t
= Twitter(auth
=authen())
1077 screen_name
= g
['stuff'].split()[0]
1078 if screen_name
.startswith('@'):
1080 screen_name
=screen_name
[1:],
1081 include_entities
=False,
1083 printNicely(green('You blocked ' + screen_name
+ '.'))
1085 printNicely(red('A name should begin with a \'@\''))
1092 t
= Twitter(auth
=authen())
1093 screen_name
= g
['stuff'].split()[0]
1094 if screen_name
.startswith('@'):
1096 screen_name
=screen_name
[1:],
1097 include_entities
=False,
1099 printNicely(green('Unblock ' + screen_name
+ ' success!'))
1101 printNicely(red('A name should begin with a \'@\''))
1106 Report a user as a spam account
1108 t
= Twitter(auth
=authen())
1109 screen_name
= g
['stuff'].split()[0]
1110 if screen_name
.startswith('@'):
1111 t
.users
.report_spam(
1112 screen_name
=screen_name
[1:])
1113 printNicely(green('You reported ' + screen_name
+ '.'))
1115 printNicely(red('Sorry I can\'t understand.'))
1123 list_name
= raw_input(
1124 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
1125 # Get list name and owner
1127 owner
, slug
= list_name
.split('/')
1128 if slug
.startswith('@'):
1133 light_magenta('List name should follow "@owner/list_name" format.'))
1134 raise Exception('Wrong list name')
1137 def check_slug(list_name
):
1141 # Get list name and owner
1143 owner
, slug
= list_name
.split('/')
1144 if slug
.startswith('@'):
1149 light_magenta('List name should follow "@owner/list_name" format.'))
1150 raise Exception('Wrong list name')
1157 rel
= t
.lists
.list(screen_name
=g
['original_name'])
1161 printNicely(light_magenta('You belong to no lists :)'))
1168 owner
, slug
= get_slug()
1169 res
= t
.lists
.statuses(
1171 owner_screen_name
=owner
,
1172 count
=c
['LIST_MAX'],
1173 include_entities
=False)
1174 for tweet
in reversed(res
):
1179 def list_members(t
):
1183 owner
, slug
= get_slug()
1187 while next_cursor
!= 0:
1188 m
= t
.lists
.members(
1190 owner_screen_name
=owner
,
1192 include_entities
=False)
1193 for u
in m
['users']:
1194 rel
[u
['name']] = '@' + u
['screen_name']
1195 next_cursor
= m
['next_cursor']
1196 printNicely('All: ' + str(len(rel
)) + ' members.')
1198 user
= ' ' + cycle_color(name
)
1199 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1203 def list_subscribers(t
):
1207 owner
, slug
= get_slug()
1211 while next_cursor
!= 0:
1212 m
= t
.lists
.subscribers(
1214 owner_screen_name
=owner
,
1216 include_entities
=False)
1217 for u
in m
['users']:
1218 rel
[u
['name']] = '@' + u
['screen_name']
1219 next_cursor
= m
['next_cursor']
1220 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1222 user
= ' ' + cycle_color(name
)
1223 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1229 Add specific user to a list
1231 owner
, slug
= get_slug()
1233 user_name
= raw_input(
1235 'Give me name of the newbie: ',
1237 if user_name
.startswith('@'):
1238 user_name
= user_name
[1:]
1240 t
.lists
.members
.create(
1242 owner_screen_name
=owner
,
1243 screen_name
=user_name
)
1244 printNicely(green('Added.'))
1247 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1252 Remove specific user from a list
1254 owner
, slug
= get_slug()
1256 user_name
= raw_input(
1258 'Give me name of the unlucky one: ',
1260 if user_name
.startswith('@'):
1261 user_name
= user_name
[1:]
1263 t
.lists
.members
.destroy(
1265 owner_screen_name
=owner
,
1266 screen_name
=user_name
)
1267 printNicely(green('Gone.'))
1270 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1273 def list_subscribe(t
):
1277 owner
, slug
= get_slug()
1280 t
.lists
.subscribers
.create(
1282 owner_screen_name
=owner
)
1283 printNicely(green('Done.'))
1287 light_magenta('I\'m sorry you can not subscribe to this list.'))
1290 def list_unsubscribe(t
):
1294 owner
, slug
= get_slug()
1297 t
.lists
.subscribers
.destroy(
1299 owner_screen_name
=owner
)
1300 printNicely(green('Done.'))
1304 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1313 while next_cursor
!= 0:
1314 res
= t
.lists
.ownerships(
1315 screen_name
=g
['original_name'],
1318 next_cursor
= res
['next_cursor']
1322 printNicely(light_magenta('You own no lists :)'))
1329 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1332 'New list\'s mode (public/private): ',
1334 description
= raw_input(
1336 'New list\'s description: ',
1342 description
=description
)
1343 printNicely(green(name
+ ' list is created.'))
1346 printNicely(red('Oops something is wrong with Twitter :('))
1355 'Your list that you want to update: ',
1359 'Update name (leave blank to unchange): ',
1361 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1362 description
= raw_input(light_magenta('Update description: ', rl
=True))
1366 slug
='-'.join(slug
.split()),
1367 owner_screen_name
=g
['original_name'],
1370 description
=description
)
1374 owner_screen_name
=g
['original_name'],
1376 description
=description
)
1377 printNicely(green(slug
+ ' list is updated.'))
1380 printNicely(red('Oops something is wrong with Twitter :('))
1389 'Your list that you want to delete: ',
1393 slug
='-'.join(slug
.split()),
1394 owner_screen_name
=g
['original_name'])
1395 printNicely(green(slug
+ ' list is deleted.'))
1398 printNicely(red('Oops something is wrong with Twitter :('))
1405 t
= Twitter(auth
=authen())
1406 # List all lists or base on action
1408 g
['list_action'] = g
['stuff'].split()[0]
1415 'all_mem': list_members
,
1416 'all_sub': list_subscribers
,
1419 'sub': list_subscribe
,
1420 'unsub': list_unsubscribe
,
1423 'update': list_update
,
1427 return action_ary
[g
['list_action']](t
)
1429 printNicely(red('Please try again.'))
1437 target
= g
['stuff'].split()[0]
1439 args
= parse_arguments()
1441 if g
['stuff'].split()[-1] == '-f':
1442 guide
= 'To ignore an option, just hit Enter key.'
1443 printNicely(light_magenta(guide
))
1444 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1445 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1446 args
.filter = list(filter(None, only
.split(',')))
1447 args
.ignore
= list(filter(None, ignore
.split(',')))
1449 printNicely(red('Sorry, wrong format.'))
1452 g
['stream_stop'] = True
1454 stuff
= g
['stuff'].split()[1]
1459 'public': spawn_public_stream
,
1460 'list': spawn_list_stream
,
1461 'mine': spawn_personal_stream
,
1463 spawn_dict
.get(target
)(args
, stuff
)
1466 printNicely(red('Sorry I can\'t understand.'))
1471 Unix's command `cal`
1474 rel
= os
.popen('cal').read().split('\n')
1477 show_calendar(month
, date
, rel
)
1482 List and change theme
1486 for theme
in g
['themes']:
1487 line
= light_magenta(theme
)
1488 if c
['THEME'] == theme
:
1489 line
= ' ' * 2 + light_yellow('* ') + line
1491 line
= ' ' * 4 + line
1497 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1498 # Redefine decorated_name
1499 g
['decorated_name'] = lambda x
: color_func(
1500 c
['DECORATED_NAME'])(
1501 '[' + x
+ ']: ', rl
=True)
1502 printNicely(green('Theme changed.'))
1504 printNicely(red('No such theme exists.'))
1509 Browse and change config
1511 all_config
= get_all_config()
1512 g
['stuff'] = g
['stuff'].strip()
1515 for k
in all_config
:
1517 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1519 guide
= 'Detailed explanation can be found at ' + \
1520 color_func(c
['TWEET']['link'])(
1521 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1523 # Print specific config
1524 elif len(g
['stuff'].split()) == 1:
1525 if g
['stuff'] in all_config
:
1528 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1531 printNicely(red('No such config key.'))
1532 # Print specific config's default value
1533 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1534 key
= g
['stuff'].split()[0]
1536 value
= get_default_config(key
)
1537 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1541 printNicely(red('Just can not get the default.'))
1542 # Delete specific config key in config file
1543 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1544 key
= g
['stuff'].split()[0]
1547 printNicely(green('Config key is dropped.'))
1550 printNicely(red('Just can not drop the key.'))
1551 # Set specific config
1552 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1553 key
= g
['stuff'].split()[0]
1554 value
= g
['stuff'].split()[-1]
1555 if key
== 'THEME' and not validate_theme(value
):
1556 printNicely(red('Invalid theme\'s value.'))
1559 set_config(key
, value
)
1560 # Keys that needs to be apply immediately
1562 c
['THEME'] = reload_theme(value
, c
['THEME'])
1563 g
['decorated_name'] = lambda x
: color_func(
1564 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
1565 elif key
== 'PREFIX':
1566 g
['PREFIX'] = u2str(emojize(format_prefix(
1567 listname
=g
['listname'],
1568 keyword
=g
['keyword']
1571 printNicely(green('Updated successfully.'))
1574 printNicely(red('Just can not set the key.'))
1576 printNicely(light_magenta('Sorry I can\'t understand.'))
1579 def help_discover():
1584 # Discover the world
1586 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1587 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1588 'You can try ' + light_green('trend US') + ' or ' + \
1589 light_green('trend JP Tokyo') + '.\n'
1590 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1591 light_green('home 7') + ' will show 7 tweets.\n'
1592 usage
+= s
* 2 + light_green('me') + ' will show your latest tweets. ' + \
1593 light_green('me 2') + ' will show your last 2 tweets.\n'
1595 light_green('notification') + ' will show your recent notification.\n'
1596 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1597 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1598 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1599 magenta('@mdo') + '.\n'
1600 usage
+= s
* 2 + light_green('view @mdo') + \
1601 ' will show ' + magenta('@mdo') + '\'s home.\n'
1602 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1603 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1604 'Search can be performed with or without hashtag.\n'
1615 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1616 usage
+= s
* 2 + light_green('t oops ') + \
1617 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1619 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1620 light_yellow('[id=12]') + '.\n'
1622 light_green('quote 12 ') + ' will quote the tweet with ' + \
1623 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1624 'the quote will be canceled.\n'
1626 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1627 light_yellow('[id=12]') + '.\n'
1628 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1629 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1630 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1631 light_yellow('oops') + '" to the owner of the tweet with ' + \
1632 light_yellow('[id=12]') + '.\n'
1633 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1634 light_yellow('oops') + '" to all people in the tweet with ' + \
1635 light_yellow('[id=12]') + '.\n'
1637 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1638 light_yellow('[id=12]') + '.\n'
1640 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1641 light_yellow('[id=12]') + '.\n'
1643 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1644 light_yellow('[id=12]') + '.\n'
1646 light_green('del 12 ') + ' will delete tweet with ' + \
1647 light_yellow('[id=12]') + '.\n'
1648 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1649 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1650 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1651 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1652 usage
+= s
* 2 + light_green('pt 12') + ' will add tweet with ' + \
1653 light_yellow('[id=12]') + ' in your Pocket list.\n'
1657 def help_messages():
1664 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1665 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1666 light_green('inbox 7') + ' will show newest 7 messages.\n'
1667 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1668 light_yellow('[thread_id=2]') + '.\n'
1669 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1670 magenta('@dtvd88') + '.\n'
1671 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1672 light_yellow('[message_id=5]') + '.\n'
1676 def help_friends_and_followers():
1678 Friends and Followers
1681 # Follower and following
1683 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1685 light_green('ls fl') + \
1686 ' will list all followers (people who are following you).\n'
1688 light_green('ls fr') + \
1689 ' will list all friends (people who you are following).\n'
1690 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1691 magenta('@dtvd88') + '.\n'
1692 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1693 magenta('@dtvd88') + '.\n'
1694 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1695 magenta('@dtvd88') + '.\n'
1696 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1697 magenta('@dtvd88') + '.\n'
1698 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1699 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1700 magenta('@dtvd88') + '.\n'
1701 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1702 magenta('@dtvd88') + '.\n'
1703 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1704 magenta('@dtvd88') + ' as a spam account.\n'
1715 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1716 usage
+= s
* 2 + light_green('list') + \
1717 ' will show all lists you are belong to.\n'
1718 usage
+= s
* 2 + light_green('list home') + \
1719 ' will show timeline of list. You will be asked for list\'s name.\n'
1720 usage
+= s
* 2 + light_green('list all_mem') + \
1721 ' will show list\'s all members.\n'
1722 usage
+= s
* 2 + light_green('list all_sub') + \
1723 ' will show list\'s all subscribers.\n'
1724 usage
+= s
* 2 + light_green('list add') + \
1725 ' will add specific person to a list owned by you.' + \
1726 ' You will be asked for list\'s name and person\'s name.\n'
1727 usage
+= s
* 2 + light_green('list rm') + \
1728 ' will remove specific person from a list owned by you.' + \
1729 ' You will be asked for list\'s name and person\'s name.\n'
1730 usage
+= s
* 2 + light_green('list sub') + \
1731 ' will subscribe you to a specific list.\n'
1732 usage
+= s
* 2 + light_green('list unsub') + \
1733 ' will unsubscribe you from a specific list.\n'
1734 usage
+= s
* 2 + light_green('list own') + \
1735 ' will show all list owned by you.\n'
1736 usage
+= s
* 2 + light_green('list new') + \
1737 ' will create a new list.\n'
1738 usage
+= s
* 2 + light_green('list update') + \
1739 ' will update a list owned by you.\n'
1740 usage
+= s
* 2 + light_green('list del') + \
1741 ' will delete a list owned by you.\n'
1752 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1753 usage
+= s
* 2 + light_green('switch public #AKB') + \
1754 ' will switch to public stream and follow "' + \
1755 light_yellow('AKB') + '" keyword.\n'
1756 usage
+= s
* 2 + light_green('switch mine') + \
1757 ' will switch to your personal stream.\n'
1758 usage
+= s
* 2 + light_green('switch mine -f ') + \
1759 ' will prompt to enter the filter.\n'
1760 usage
+= s
* 3 + light_yellow('Only nicks') + \
1761 ' filter will decide nicks will be INCLUDE ONLY.\n'
1762 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1763 ' filter will decide nicks will be EXCLUDE.\n'
1764 usage
+= s
* 2 + light_green('switch list') + \
1765 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1774 h
, w
= os
.popen('stty size', 'r').read().split()
1777 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1778 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1779 usage
+= s
+ 'You are ' + \
1780 light_yellow('already') + ' on your personal stream.\n'
1781 usage
+= s
+ 'Any update from Twitter will show up ' + \
1782 light_yellow('immediately') + '.\n'
1783 usage
+= s
+ 'In addition, following commands are available right now:\n'
1784 # Twitter help section
1786 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1787 usage
+= s
* 2 + light_green('h discover') + \
1788 ' will show help for discover commands.\n'
1789 usage
+= s
* 2 + light_green('h tweets') + \
1790 ' will show help for tweets commands.\n'
1791 usage
+= s
* 2 + light_green('h messages') + \
1792 ' will show help for messages commands.\n'
1793 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1794 ' will show help for friends and followers commands.\n'
1795 usage
+= s
* 2 + light_green('h list') + \
1796 ' will show help for list commands.\n'
1797 usage
+= s
* 2 + light_green('h stream') + \
1798 ' will show help for stream commands.\n'
1801 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1802 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1803 'will be evaluate by Python interpreter.\n'
1804 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1805 ' for current month.\n'
1808 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1809 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1810 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1811 ' theme immediately.\n'
1812 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1814 light_green('config ASCII_ART') + ' will output current value of ' +\
1815 light_yellow('ASCII_ART') + ' config key.\n'
1817 light_green('config TREND_MAX default') + ' will output default value of ' + \
1818 light_yellow('TREND_MAX') + ' config key.\n'
1820 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1821 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1823 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1824 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1825 light_yellow('True') + '.\n'
1828 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1829 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1830 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1831 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1832 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1833 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1834 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1837 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1838 usage
+= s
+ 'Have fun and hang tight! \n'
1841 'discover': help_discover
,
1842 'tweets': help_tweets
,
1843 'messages': help_messages
,
1844 'friends_and_followers': help_friends_and_followers
,
1846 'stream': help_stream
,
1851 lambda: printNicely(red('No such command.'))
1859 Pause stream display
1862 printNicely(green('Stream is paused'))
1870 printNicely(green('Stream is running back now'))
1886 printNicely(green('See you next time :)'))
1894 Reset prefix of line
1897 if c
.get('USER_JSON_ERROR'):
1898 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1899 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1901 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1904 printNicely(str(eval(g
['cmd'])))
1959 # Handle function set
2014 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
2019 Listen to user's input
2024 ['public', 'mine', 'list'], # switch
2033 [], # view_my_tweets
2044 ['image'], # show image
2046 ['fl', 'fr'], # list
2048 [i
for i
in g
['message_threads']], # sent
2073 [key
for key
in dict(get_all_config())], # config
2074 g
['themes'], # theme
2079 'friends_and_followers',
2091 init_interactive_shell(d
)
2098 # Only use PREFIX as a string with raw_input
2099 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
2102 # Save cmd to compare with readline buffer
2103 g
['cmd'] = line
.strip()
2104 # Get short cmd to pass to handle function
2106 cmd
= line
.split()[0]
2109 # Lock the semaphore
2111 # Save cmd to global variable and call process
2112 g
['stuff'] = ' '.join(line
.split()[1:])
2113 # Check tweet length
2114 # Process the command
2117 if cmd
in ['switch', 't', 'rt', 'rep']:
2123 except TwitterHTTPError
as e
:
2124 detail_twitter_error(e
)
2127 printNicely(red('OMG something is wrong with Twitter API right now.'))
2129 # Release the semaphore lock
2133 def reconn_notice():
2135 Notice when Hangup or Timeout
2137 guide
= light_magenta('You can use ') + \
2138 light_green('switch') + \
2139 light_magenta(' command to return to your stream.\n')
2140 guide
+= light_magenta('Type ') + \
2141 light_green('h stream') + \
2142 light_magenta(' for more details.')
2144 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2148 def stream(domain
, args
, name
='Rainbow Stream'):
2154 c
['USER_DOMAIN']: name
,
2155 c
['PUBLIC_DOMAIN']: args
.track_keywords
or 'Global',
2156 c
['SITE_DOMAIN']: name
,
2159 ascii_art(art_dict
.get(domain
, name
))
2160 # These arguments are optional:
2162 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2164 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2167 if args
.track_keywords
:
2168 query_args
['track'] = args
.track_keywords
2172 time
.sleep(polling_time
)
2175 def spawn_public_stream(args
, keyword
=None):
2177 Spawn a new public stream
2179 # Only set keyword if specified
2181 if keyword
[0] == '#':
2182 keyword
= keyword
[1:]
2183 args
.track_keywords
= keyword
2184 g
['keyword'] = keyword
2186 g
['keyword'] = 'Global'
2187 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
2190 th
= threading
.Thread(
2199 def spawn_list_stream(args
, stuff
=None):
2201 Spawn a new list stream
2204 owner
, slug
= check_slug(stuff
)
2206 owner
, slug
= get_slug()
2208 # Force python 2 not redraw readline buffer
2209 listname
= '/'.join([owner
, slug
])
2210 # Set the listname variable
2211 # and reset tracked keyword
2212 g
['listname'] = listname
2214 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
2215 listname
=g
['listname']
2217 printNicely(light_yellow('getting list members ...'))
2219 t
= Twitter(auth
=authen())
2222 while next_cursor
!= 0:
2223 m
= t
.lists
.members(
2225 owner_screen_name
=owner
,
2227 include_entities
=False)
2228 for u
in m
['users']:
2229 members
.append('@' + u
['screen_name'])
2230 next_cursor
= m
['next_cursor']
2231 printNicely(light_yellow('... done.'))
2232 # Build thread filter array
2233 args
.filter = members
2235 th
= threading
.Thread(
2245 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
2247 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
2251 def spawn_personal_stream(args
, stuff
=None):
2253 Spawn a new personal stream
2255 # Reset the tracked keyword and listname
2256 g
['keyword'] = g
['listname'] = ''
2258 g
['PREFIX'] = u2str(emojize(format_prefix()))
2260 th
= threading
.Thread(
2265 g
['original_name']))
2275 args
= parse_arguments()
2279 # Twitter API connection problem
2280 except TwitterHTTPError
as e
:
2283 magenta('We have connection problem with twitter REST API right now :('))
2284 detail_twitter_error(e
)
2287 # Proxy connection problem
2288 except (socks
.ProxyConnectionError
, URLError
):
2290 magenta('There seems to be a connection problem.'))
2292 magenta('You might want to check your proxy settings (host, port and type)!'))
2296 # Spawn stream thread
2297 target
= args
.stream
.split()[0]
2298 if target
== 'mine':
2299 spawn_personal_stream(args
)
2302 stuff
= args
.stream
.split()[1]
2306 'public': spawn_public_stream
,
2307 'list': spawn_list_stream
,
2309 spawn_dict
.get(target
)(args
, stuff
)
2311 # Start listen process