15 from io
import BytesIO
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
25 from .consumer
import *
26 from .interactive
import *
27 from .c_image
import *
28 from .py3patch
import *
36 StreamLock
= threading
.Lock()
39 def parse_arguments():
43 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
47 help='Timeout for the stream (seconds).')
51 help='Search the stream for specific text.')
55 help='Filter specific screen_name.')
59 help='Ignore specific screen_name.')
64 help='Display all image on terminal.')
68 help='Use HTTP/SOCKS proxy for network connections.')
73 help='HTTP/SOCKS proxy port (Default: 8080).')
78 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
79 return parser
.parse_args()
82 def proxy_connect(args
):
84 Connect to specified proxy
87 # Setup proxy by monkeypatching the standard lib
88 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
89 socks
.set_default_proxy(
90 socks
.SOCKS5
, args
.proxy_host
,
92 elif args
.proxy_type
.lower() == "http":
93 socks
.set_default_proxy(
94 socks
.HTTP
, args
.proxy_host
,
96 elif args
.proxy_type
.lower() == "socks4":
97 socks
.set_default_proxy(
98 socks
.SOCKS4
, args
.proxy_host
,
102 magenta("Sorry, wrong proxy type specified! Aborting..."))
104 socket
.socket
= socks
.socksocket
109 Authenticate with Twitter OAuth
111 # When using rainbow stream you must authorize.
112 twitter_credential
= os
.environ
.get(
116 '')) + os
.sep
+ '.rainbow_oauth'
117 if not os
.path
.exists(twitter_credential
):
118 oauth_dance("Rainbow Stream",
122 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
130 def build_mute_dict(dict_data
=False):
134 t
= Twitter(auth
=authen())
137 screen_name_list
= []
140 while next_cursor
!= 0:
141 list = t
.mutes
.users
.list(
142 screen_name
=g
['original_name'],
145 include_entities
=False,
147 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
148 name_list
+= [u
['name'] for u
in list['users']]
149 next_cursor
= list['next_cursor']
150 # Return dict or list
152 return dict(zip(screen_name_list
, name_list
))
154 return screen_name_list
159 Save traceback when run in debug mode
162 g
['traceback'].append(traceback
.format_exc())
165 def upgrade_center():
167 Check latest and notify to upgrade
170 current
= pkg_resources
.get_distribution("rainbowstream").version
171 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
172 readme
= requests
.get(url
).text
173 latest
= readme
.split("version = \'")[1].split("\'")[0]
174 if current
!= latest
:
175 notice
= light_magenta('RainbowStream latest version is ')
176 notice
+= light_green(latest
)
177 notice
+= light_magenta(' while your current version is ')
178 notice
+= light_yellow(current
) + '\n'
179 notice
+= light_magenta('You should upgrade with ')
180 notice
+= light_green('pip install -U rainbowstream')
183 notice
= light_yellow('You are running latest version (')
184 notice
+= light_green(current
)
185 notice
+= light_yellow(')')
196 ctrl_c_handler
= lambda signum
, frame
: quit()
197 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
201 t
= Twitter(auth
=authen())
202 credential
= t
.account
.verify_credentials()
203 screen_name
= '@' + credential
['screen_name']
204 name
= credential
['name']
205 if not get_config('PREFIX'):
206 set_config('PREFIX', screen_name
)
207 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
208 c
['original_name'] = g
['original_name'] = screen_name
[1:]
209 g
['full_name'] = name
210 g
['decorated_name'] = lambda x
: color_func(
211 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
213 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
214 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
217 g
['message_threads'] = {}
220 # Debug option default = True
227 # Init tweet dict and message dict
229 c
['message_dict'] = []
231 c
['IMAGE_ON_TERM'] = args
.image_on_term
232 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
233 # Check type of ONLY_LIST and IGNORE_LIST
234 if not isinstance(c
['ONLY_LIST'], list):
235 printNicely(red('ONLY_LIST is not a valid list value.'))
237 if not isinstance(c
['IGNORE_LIST'], list):
238 printNicely(red('IGNORE_LIST is not a valid list value.'))
239 c
['IGNORE_LIST'] = []
241 c
['IGNORE_LIST'] += build_mute_dict()
248 t
= Twitter(auth
=authen())
249 # Get country and town
251 country
= g
['stuff'].split()[0]
255 town
= g
['stuff'].split()[1]
258 avail
= t
.trends
.available()
261 trends
= t
.trends
.place(_id
=1)[0]['trends']
264 for location
in avail
:
265 # Search for country and Town
267 if location
['countryCode'] == country \
268 and location
['placeType']['name'] == 'Town' \
269 and location
['name'] == town
:
270 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
272 # Search for country only
274 if location
['countryCode'] == country \
275 and location
['placeType']['name'] == 'Country':
276 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
284 t
= Twitter(auth
=authen())
285 num
= c
['HOME_TWEET_NUM']
286 if g
['stuff'].isdigit():
287 num
= int(g
['stuff'])
288 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
298 for e
in c
['events']:
302 printNicely(magenta('Nothing at this time.'))
309 t
= Twitter(auth
=authen())
310 num
= c
['HOME_TWEET_NUM']
311 if g
['stuff'].isdigit():
312 num
= int(g
['stuff'])
313 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
320 Show profile of a specific user
322 t
= Twitter(auth
=authen())
323 screen_name
= g
['stuff'].split()[0]
324 if screen_name
.startswith('@'):
327 screen_name
=screen_name
[1:],
328 include_entities
=False)
332 printNicely(red('No user.'))
334 printNicely(red('A name should begin with a \'@\''))
341 t
= Twitter(auth
=authen())
342 user
= g
['stuff'].split()[0]
345 num
= int(g
['stuff'].split()[1])
347 num
= c
['HOME_TWEET_NUM']
348 for tweet
in reversed(
349 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
353 printNicely(red('A name should begin with a \'@\''))
360 t
= Twitter(auth
=authen())
362 query
= g
['stuff'].strip()
363 type = c
['SEARCH_TYPE']
364 if type not in ['mixed', 'recent', 'popular']:
366 max_record
= c
['SEARCH_MAX_RECORD']
367 count
= min(max_record
, 100)
369 rel
= t
.search
.tweets(
376 printNicely('Newest tweets:')
377 for i
in reversed(xrange(count
)):
378 draw(t
=rel
[i
], keyword
=query
)
381 printNicely(magenta('I\'m afraid there is no result'))
388 t
= Twitter(auth
=authen())
389 t
.statuses
.update(status
=g
['stuff'])
396 t
= Twitter(auth
=authen())
398 id = int(g
['stuff'].split()[0])
400 printNicely(red('Sorry I can\'t understand.'))
402 tid
= c
['tweet_dict'][id]
403 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
411 t
= Twitter(auth
=authen())
413 id = int(g
['stuff'].split()[0])
415 printNicely(red('Sorry I can\'t understand.'))
417 tid
= c
['tweet_dict'][id]
418 tweet
= t
.statuses
.show(id=tid
)
420 formater
= format_quote(tweet
)
424 prefix
= light_magenta('Compose your ', rl
=True) + \
425 light_green('#comment: ', rl
=True)
426 comment
= raw_input(prefix
)
428 quote
= comment
.join(formater
.split('#comment'))
429 t
.statuses
.update(status
=quote
)
431 printNicely(light_magenta('No text added.'))
438 t
= Twitter(auth
=authen())
441 id = int(g
['stuff'].split()[0])
443 printNicely(red('Sorry I can\'t understand.'))
445 tid
= c
['tweet_dict'][id]
446 # Get display num if exist
448 num
= int(g
['stuff'].split()[1])
450 num
= c
['RETWEETS_SHOW_NUM']
451 # Get result and display
452 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
454 printNicely(magenta('This tweet has no retweet.'))
456 for tweet
in reversed(rt_ary
):
465 t
= Twitter(auth
=authen())
467 id = int(g
['stuff'].split()[0])
469 printNicely(red('Sorry I can\'t understand.'))
471 tid
= c
['tweet_dict'][id]
472 tweet
= t
.statuses
.show(id=tid
)
473 limit
= c
['CONVERSATION_MAX']
475 thread_ref
.append(tweet
)
476 prev_tid
= tweet
['in_reply_to_status_id']
477 while prev_tid
and limit
:
479 tweet
= t
.statuses
.show(id=prev_tid
)
480 prev_tid
= tweet
['in_reply_to_status_id']
481 thread_ref
.append(tweet
)
483 for tweet
in reversed(thread_ref
):
492 t
= Twitter(auth
=authen())
494 id = int(g
['stuff'].split()[0])
496 printNicely(red('Sorry I can\'t understand.'))
498 tid
= c
['tweet_dict'][id]
499 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
500 status
= ' '.join(g
['stuff'].split()[1:])
501 status
= '@' + user
+ ' ' + str2u(status
)
502 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
509 t
= Twitter(auth
=authen())
511 id = int(g
['stuff'].split()[0])
513 printNicely(red('Sorry I can\'t understand.'))
515 tid
= c
['tweet_dict'][id]
516 t
.favorites
.create(_id
=tid
, include_entities
=False)
517 printNicely(green('Favorited.'))
518 draw(t
.statuses
.show(id=tid
))
526 t
= Twitter(auth
=authen())
528 id = int(g
['stuff'].split()[0])
530 printNicely(red('Sorry I can\'t understand.'))
532 tid
= c
['tweet_dict'][id]
533 t
.favorites
.destroy(_id
=tid
)
534 printNicely(green('Okay it\'s unfavorited.'))
535 draw(t
.statuses
.show(id=tid
))
541 Copy url of a tweet to clipboard
543 t
= Twitter(auth
=authen())
545 id = int(g
['stuff'].split()[0])
546 tid
= c
['tweet_dict'][id]
548 printNicely(red('Tweet id is not valid.'))
550 tweet
= t
.statuses
.show(id=tid
)
551 url
= 'https://twitter.com/' + \
552 tweet
['user']['screen_name'] + '/status/' + str(tid
)
554 if platform
.system().lower() == 'darwin':
555 os
.system("echo '%s' | pbcopy" % url
)
556 printNicely(green('Copied tweet\'s url to clipboard.'))
558 printNicely('Direct link: ' + yellow(url
))
565 t
= Twitter(auth
=authen())
567 id = int(g
['stuff'].split()[0])
569 printNicely(red('Sorry I can\'t understand.'))
571 tid
= c
['tweet_dict'][id]
572 t
.statuses
.destroy(id=tid
)
573 printNicely(green('Okay it\'s gone.'))
580 t
= Twitter(auth
=authen())
582 target
= g
['stuff'].split()[0]
583 if target
!= 'image':
585 id = int(g
['stuff'].split()[1])
586 tid
= c
['tweet_dict'][id]
587 tweet
= t
.statuses
.show(id=tid
)
588 media
= tweet
['entities']['media']
590 res
= requests
.get(m
['media_url'])
591 img
= Image
.open(BytesIO(res
.content
))
595 printNicely(red('Sorry I can\'t show this image.'))
602 t
= Twitter(auth
=authen())
604 if not g
['stuff'].isdigit():
606 tid
= c
['tweet_dict'][int(g
['stuff'])]
607 tweet
= t
.statuses
.show(id=tid
)
608 link_prefix
= ('http://', 'https://')
609 link_ary
= [u
for u
in tweet
['text'].split()
610 if u
.startswith(link_prefix
)]
612 printNicely(light_magenta('No url here @.@!'))
614 for link
in link_ary
:
615 webbrowser
.open(link
)
618 printNicely(red('Sorry I can\'t open url in this tweet.'))
625 t
= Twitter(auth
=authen())
626 num
= c
['MESSAGES_DISPLAY']
627 if g
['stuff'].isdigit():
633 inbox
= inbox
+ t
.direct_messages(
636 include_entities
=False,
641 inbox
= inbox
+ t
.direct_messages(
644 include_entities
=False,
648 num
= c
['MESSAGES_DISPLAY']
649 if g
['stuff'].isdigit():
654 sent
= sent
+ t
.direct_messages
.sent(
657 include_entities
=False,
662 sent
= sent
+ t
.direct_messages
.sent(
665 include_entities
=False,
670 uniq_inbox
= list(set(
671 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
673 uniq_sent
= list(set(
674 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
676 for partner
in uniq_inbox
:
677 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
679 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
680 d
[partner
] = inbox_ary
+ sent_ary
681 for partner
in uniq_sent
:
684 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
685 g
['message_threads'] = print_threads(d
)
690 View a thread of message
693 thread_id
= int(g
['stuff'])
695 g
['message_threads'][thread_id
],
700 printNicely(red('No such thread.'))
705 Send a direct message
707 t
= Twitter(auth
=authen())
709 user
= g
['stuff'].split()[0]
710 if user
[0].startswith('@'):
711 content
= ' '.join(g
['stuff'].split()[1:])
712 t
.direct_messages
.new(
713 screen_name
=user
[1:],
716 printNicely(green('Message sent.'))
718 printNicely(red('A name should begin with a \'@\''))
721 printNicely(red('Sorry I can\'t understand.'))
728 t
= Twitter(auth
=authen())
730 id = int(g
['stuff'].split()[0])
732 printNicely(red('Sorry I can\'t understand.'))
733 mid
= c
['message_dict'][id]
734 t
.direct_messages
.destroy(id=mid
)
735 printNicely(green('Message deleted.'))
740 List friends for followers
742 t
= Twitter(auth
=authen())
745 name
= g
['stuff'].split()[1]
746 if name
.startswith('@'):
749 printNicely(red('A name should begin with a \'@\''))
750 raise Exception('Invalid name')
752 name
= g
['original_name']
753 # Get list followers or friends
755 target
= g
['stuff'].split()[0]
757 printNicely(red('Omg some syntax is wrong.'))
759 d
= {'fl': 'followers', 'fr': 'friends'}
763 while next_cursor
!= 0:
764 list = getattr(t
, d
[target
]).list(
768 include_entities
=False,
770 for u
in list['users']:
771 rel
[u
['name']] = '@' + u
['screen_name']
772 next_cursor
= list['next_cursor']
774 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
776 user
= ' ' + cycle_color(name
)
777 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
785 t
= Twitter(auth
=authen())
786 screen_name
= g
['stuff'].split()[0]
787 if screen_name
.startswith('@'):
788 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
789 printNicely(green('You are following ' + screen_name
+ ' now!'))
791 printNicely(red('A name should begin with a \'@\''))
798 t
= Twitter(auth
=authen())
799 screen_name
= g
['stuff'].split()[0]
800 if screen_name
.startswith('@'):
801 t
.friendships
.destroy(
802 screen_name
=screen_name
[1:],
803 include_entities
=False)
804 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
806 printNicely(red('A name should begin with a \'@\''))
813 t
= Twitter(auth
=authen())
815 screen_name
= g
['stuff'].split()[0]
817 printNicely(red('A name should be specified. '))
819 if screen_name
.startswith('@'):
821 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
822 if isinstance(rel
, dict):
823 printNicely(green(screen_name
+ ' is muted.'))
824 c
['IGNORE_LIST'] += [unc(screen_name
)]
825 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
827 printNicely(red(rel
))
830 printNicely(red('Something is wrong, can not mute now :('))
832 printNicely(red('A name should begin with a \'@\''))
839 t
= Twitter(auth
=authen())
841 screen_name
= g
['stuff'].split()[0]
843 printNicely(red('A name should be specified. '))
845 if screen_name
.startswith('@'):
847 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
848 if isinstance(rel
, dict):
849 printNicely(green(screen_name
+ ' is unmuted.'))
850 c
['IGNORE_LIST'].remove(screen_name
)
852 printNicely(red(rel
))
854 printNicely(red('Maybe you are not muting this person ?'))
856 printNicely(red('A name should begin with a \'@\''))
863 # Get dict of muting users
864 md
= build_mute_dict(dict_data
=True)
865 printNicely('All: ' + str(len(md
)) + ' people.')
867 user
= ' ' + cycle_color(md
[name
])
868 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
870 # Update from Twitter
871 c
['IGNORE_LIST'] = [n
for n
in md
]
878 t
= Twitter(auth
=authen())
879 screen_name
= g
['stuff'].split()[0]
880 if screen_name
.startswith('@'):
882 screen_name
=screen_name
[1:],
883 include_entities
=False,
885 printNicely(green('You blocked ' + screen_name
+ '.'))
887 printNicely(red('A name should begin with a \'@\''))
894 t
= Twitter(auth
=authen())
895 screen_name
= g
['stuff'].split()[0]
896 if screen_name
.startswith('@'):
898 screen_name
=screen_name
[1:],
899 include_entities
=False,
901 printNicely(green('Unblock ' + screen_name
+ ' success!'))
903 printNicely(red('A name should begin with a \'@\''))
908 Report a user as a spam account
910 t
= Twitter(auth
=authen())
911 screen_name
= g
['stuff'].split()[0]
912 if screen_name
.startswith('@'):
914 screen_name
=screen_name
[1:])
915 printNicely(green('You reported ' + screen_name
+ '.'))
917 printNicely(red('Sorry I can\'t understand.'))
925 list_name
= raw_input(
926 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
927 # Get list name and owner
929 owner
, slug
= list_name
.split('/')
930 if slug
.startswith('@'):
935 light_magenta('List name should follow "@owner/list_name" format.'))
936 raise Exception('Wrong list name')
943 rel
= t
.lists
.list(screen_name
=g
['original_name'])
947 printNicely(light_magenta('You belong to no lists :)'))
954 owner
, slug
= get_slug()
955 res
= t
.lists
.statuses(
957 owner_screen_name
=owner
,
959 include_entities
=False)
960 for tweet
in reversed(res
):
969 owner
, slug
= get_slug()
973 while next_cursor
!= 0:
976 owner_screen_name
=owner
,
978 include_entities
=False)
980 rel
[u
['name']] = '@' + u
['screen_name']
981 next_cursor
= m
['next_cursor']
982 printNicely('All: ' + str(len(rel
)) + ' members.')
984 user
= ' ' + cycle_color(name
)
985 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
989 def list_subscribers(t
):
993 owner
, slug
= get_slug()
997 while next_cursor
!= 0:
998 m
= t
.lists
.subscribers(
1000 owner_screen_name
=owner
,
1002 include_entities
=False)
1003 for u
in m
['users']:
1004 rel
[u
['name']] = '@' + u
['screen_name']
1005 next_cursor
= m
['next_cursor']
1006 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1008 user
= ' ' + cycle_color(name
)
1009 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1015 Add specific user to a list
1017 owner
, slug
= get_slug()
1019 user_name
= raw_input(
1021 'Give me name of the newbie: ',
1023 if user_name
.startswith('@'):
1024 user_name
= user_name
[1:]
1026 t
.lists
.members
.create(
1028 owner_screen_name
=owner
,
1029 screen_name
=user_name
)
1030 printNicely(green('Added.'))
1033 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1038 Remove specific user from a list
1040 owner
, slug
= get_slug()
1042 user_name
= raw_input(
1044 'Give me name of the unlucky one: ',
1046 if user_name
.startswith('@'):
1047 user_name
= user_name
[1:]
1049 t
.lists
.members
.destroy(
1051 owner_screen_name
=owner
,
1052 screen_name
=user_name
)
1053 printNicely(green('Gone.'))
1056 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1059 def list_subscribe(t
):
1063 owner
, slug
= get_slug()
1066 t
.lists
.subscribers
.create(
1068 owner_screen_name
=owner
)
1069 printNicely(green('Done.'))
1073 light_magenta('I\'m sorry you can not subscribe to this list.'))
1076 def list_unsubscribe(t
):
1080 owner
, slug
= get_slug()
1083 t
.lists
.subscribers
.destroy(
1085 owner_screen_name
=owner
)
1086 printNicely(green('Done.'))
1090 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1099 while next_cursor
!= 0:
1100 res
= t
.lists
.ownerships(
1101 screen_name
=g
['original_name'],
1104 next_cursor
= res
['next_cursor']
1108 printNicely(light_magenta('You own no lists :)'))
1115 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1118 'New list\'s mode (public/private): ',
1120 description
= raw_input(
1122 'New list\'s description: ',
1128 description
=description
)
1129 printNicely(green(name
+ ' list is created.'))
1132 printNicely(red('Oops something is wrong with Twitter :('))
1141 'Your list that you want to update: ',
1145 'Update name (leave blank to unchange): ',
1147 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1148 description
= raw_input(light_magenta('Update description: ', rl
=True))
1152 slug
='-'.join(slug
.split()),
1153 owner_screen_name
=g
['original_name'],
1156 description
=description
)
1160 owner_screen_name
=g
['original_name'],
1162 description
=description
)
1163 printNicely(green(slug
+ ' list is updated.'))
1166 printNicely(red('Oops something is wrong with Twitter :('))
1175 'Your list that you want to delete: ',
1179 slug
='-'.join(slug
.split()),
1180 owner_screen_name
=g
['original_name'])
1181 printNicely(green(slug
+ ' list is deleted.'))
1184 printNicely(red('Oops something is wrong with Twitter :('))
1191 t
= Twitter(auth
=authen())
1192 # List all lists or base on action
1194 g
['list_action'] = g
['stuff'].split()[0]
1201 'all_mem': list_members
,
1202 'all_sub': list_subscribers
,
1205 'sub': list_subscribe
,
1206 'unsub': list_unsubscribe
,
1209 'update': list_update
,
1213 return action_ary
[g
['list_action']](t
)
1215 printNicely(red('Please try again.'))
1223 target
= g
['stuff'].split()[0]
1225 args
= parse_arguments()
1227 if g
['stuff'].split()[-1] == '-f':
1228 guide
= 'To ignore an option, just hit Enter key.'
1229 printNicely(light_magenta(guide
))
1230 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1231 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1232 args
.filter = filter(None, only
.split(','))
1233 args
.ignore
= filter(None, ignore
.split(','))
1235 printNicely(red('Sorry, wrong format.'))
1238 if target
== 'public':
1239 keyword
= g
['stuff'].split()[1]
1240 if keyword
[0] == '#':
1241 keyword
= keyword
[1:]
1243 g
['stream_stop'] = True
1244 args
.track_keywords
= keyword
1246 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1248 th
= threading
.Thread(
1256 elif target
== 'mine':
1258 g
['stream_stop'] = True
1260 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1262 th
= threading
.Thread(
1267 g
['original_name']))
1270 # Stream base on list
1271 elif target
== 'list':
1272 owner
, slug
= get_slug()
1273 # Force python 2 not redraw readline buffer
1274 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1275 printNicely(light_yellow('getting list members ...'))
1277 t
= Twitter(auth
=authen())
1280 while next_cursor
!= 0:
1281 m
= t
.lists
.members(
1283 owner_screen_name
=owner
,
1285 include_entities
=False)
1286 for u
in m
['users']:
1287 members
.append('@' + u
['screen_name'])
1288 next_cursor
= m
['next_cursor']
1289 printNicely(light_yellow('... done.'))
1290 # Build thread filter array
1291 args
.filter = members
1293 g
['stream_stop'] = True
1295 th
= threading
.Thread(
1305 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1307 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1311 printNicely(red('Sorry I can\'t understand.'))
1316 Unix's command `cal`
1319 rel
= os
.popen('cal').read().split('\n')
1322 show_calendar(month
, date
, rel
)
1327 List and change theme
1331 for theme
in g
['themes']:
1332 line
= light_magenta(theme
)
1333 if c
['THEME'] == theme
:
1334 line
= ' ' * 2 + light_yellow('* ') + line
1336 line
= ' ' * 4 + line
1342 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1343 # Redefine decorated_name
1344 g
['decorated_name'] = lambda x
: color_func(
1345 c
['DECORATED_NAME'])(
1347 printNicely(green('Theme changed.'))
1349 printNicely(red('No such theme exists.'))
1354 Browse and change config
1356 all_config
= get_all_config()
1357 g
['stuff'] = g
['stuff'].strip()
1360 for k
in all_config
:
1362 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1364 guide
= 'Detailed explanation can be found at ' + \
1365 color_func(c
['TWEET']['link'])(
1366 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1368 # Print specific config
1369 elif len(g
['stuff'].split()) == 1:
1370 if g
['stuff'] in all_config
:
1373 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1376 printNicely(red('No such config key.'))
1377 # Print specific config's default value
1378 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1379 key
= g
['stuff'].split()[0]
1381 value
= get_default_config(key
)
1382 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1386 printNicely(red('Just can not get the default.'))
1387 # Delete specific config key in config file
1388 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1389 key
= g
['stuff'].split()[0]
1392 printNicely(green('Config key is dropped.'))
1395 printNicely(red('Just can not drop the key.'))
1396 # Set specific config
1397 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1398 key
= g
['stuff'].split()[0]
1399 value
= g
['stuff'].split()[-1]
1400 if key
== 'THEME' and not validate_theme(value
):
1401 printNicely(red('Invalid theme\'s value.'))
1404 set_config(key
, value
)
1405 # Keys that needs to be apply immediately
1407 c
['THEME'] = reload_theme(value
, c
['THEME'])
1408 g
['decorated_name'] = lambda x
: color_func(
1409 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1410 elif key
== 'PREFIX':
1411 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1413 printNicely(green('Updated successfully.'))
1416 printNicely(red('Just can not set the key.'))
1418 printNicely(light_magenta('Sorry I can\'s understand.'))
1421 def help_discover():
1426 # Discover the world
1428 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1429 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1430 'You can try ' + light_green('trend US') + ' or ' + \
1431 light_green('trend JP Tokyo') + '.\n'
1432 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1433 light_green('home 7') + ' will show 7 tweets.\n'
1435 light_green('notification') + ' will show your recent notification.\n'
1436 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1437 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1438 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1439 magenta('@mdo') + '.\n'
1440 usage
+= s
* 2 + light_green('view @mdo') + \
1441 ' will show ' + magenta('@mdo') + '\'s home.\n'
1442 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1443 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1444 'Search can be performed with or without hashtag.\n'
1455 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1456 usage
+= s
* 2 + light_green('t oops ') + \
1457 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1459 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1460 light_yellow('[id=12]') + '.\n'
1462 light_green('quote 12 ') + ' will quote the tweet with ' + \
1463 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1464 'the quote will be canceled.\n'
1466 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1467 light_yellow('[id=12]') + '.\n'
1468 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1469 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1470 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1471 light_yellow('oops') + '" to tweet with ' + \
1472 light_yellow('[id=12]') + '.\n'
1474 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1475 light_yellow('[id=12]') + '.\n'
1477 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1478 light_yellow('[id=12]') + '.\n'
1480 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1481 light_yellow('[id=12]') + '.\n'
1483 light_green('del 12 ') + ' will delete tweet with ' + \
1484 light_yellow('[id=12]') + '.\n'
1485 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1486 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1487 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1488 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1492 def help_messages():
1499 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1500 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1501 light_green('inbox 7') + ' will show newest 7 messages.\n'
1502 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1503 light_yellow('[thread_id=2]') + '.\n'
1504 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1505 magenta('@dtvd88') + '.\n'
1506 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1507 light_yellow('[message_id=5]') + '.\n'
1511 def help_friends_and_followers():
1513 Friends and Followers
1516 # Follower and following
1518 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1520 light_green('ls fl') + \
1521 ' will list all followers (people who are following you).\n'
1523 light_green('ls fr') + \
1524 ' will list all friends (people who you are following).\n'
1525 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1526 magenta('@dtvd88') + '.\n'
1527 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1528 magenta('@dtvd88') + '.\n'
1529 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1530 magenta('@dtvd88') + '.\n'
1531 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1532 magenta('@dtvd88') + '.\n'
1533 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1534 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1535 magenta('@dtvd88') + '.\n'
1536 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1537 magenta('@dtvd88') + '.\n'
1538 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1539 magenta('@dtvd88') + ' as a spam account.\n'
1550 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1551 usage
+= s
* 2 + light_green('list') + \
1552 ' will show all lists you are belong to.\n'
1553 usage
+= s
* 2 + light_green('list home') + \
1554 ' will show timeline of list. You will be asked for list\'s name.\n'
1555 usage
+= s
* 2 + light_green('list all_mem') + \
1556 ' will show list\'s all members.\n'
1557 usage
+= s
* 2 + light_green('list all_sub') + \
1558 ' will show list\'s all subscribers.\n'
1559 usage
+= s
* 2 + light_green('list add') + \
1560 ' will add specific person to a list owned by you.' + \
1561 ' You will be asked for list\'s name and person\'s name.\n'
1562 usage
+= s
* 2 + light_green('list rm') + \
1563 ' will remove specific person from a list owned by you.' + \
1564 ' You will be asked for list\'s name and person\'s name.\n'
1565 usage
+= s
* 2 + light_green('list sub') + \
1566 ' will subscribe you to a specific list.\n'
1567 usage
+= s
* 2 + light_green('list unsub') + \
1568 ' will unsubscribe you from a specific list.\n'
1569 usage
+= s
* 2 + light_green('list own') + \
1570 ' will show all list owned by you.\n'
1571 usage
+= s
* 2 + light_green('list new') + \
1572 ' will create a new list.\n'
1573 usage
+= s
* 2 + light_green('list update') + \
1574 ' will update a list owned by you.\n'
1575 usage
+= s
* 2 + light_green('list del') + \
1576 ' will delete a list owned by you.\n'
1587 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1588 usage
+= s
* 2 + light_green('switch public #AKB') + \
1589 ' will switch to public stream and follow "' + \
1590 light_yellow('AKB') + '" keyword.\n'
1591 usage
+= s
* 2 + light_green('switch mine') + \
1592 ' will switch to your personal stream.\n'
1593 usage
+= s
* 2 + light_green('switch mine -f ') + \
1594 ' will prompt to enter the filter.\n'
1595 usage
+= s
* 3 + light_yellow('Only nicks') + \
1596 ' filter will decide nicks will be INCLUDE ONLY.\n'
1597 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1598 ' filter will decide nicks will be EXCLUDE.\n'
1599 usage
+= s
* 2 + light_green('switch list') + \
1600 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1609 h
, w
= os
.popen('stty size', 'r').read().split()
1612 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1613 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1614 usage
+= s
+ 'You are ' + \
1615 light_yellow('already') + ' on your personal stream.\n'
1616 usage
+= s
+ 'Any update from Twitter will show up ' + \
1617 light_yellow('immediately') + '.\n'
1618 usage
+= s
+ 'In addition, following commands are available right now:\n'
1619 # Twitter help section
1621 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1622 usage
+= s
* 2 + light_green('h discover') + \
1623 ' will show help for discover commands.\n'
1624 usage
+= s
* 2 + light_green('h tweets') + \
1625 ' will show help for tweets commands.\n'
1626 usage
+= s
* 2 + light_green('h messages') + \
1627 ' will show help for messages commands.\n'
1628 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1629 ' will show help for friends and followers commands.\n'
1630 usage
+= s
* 2 + light_green('h list') + \
1631 ' will show help for list commands.\n'
1632 usage
+= s
* 2 + light_green('h stream') + \
1633 ' will show help for stream commands.\n'
1636 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1637 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1638 'will be evaluate by Python interpreter.\n'
1639 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1640 ' for current month.\n'
1643 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1644 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1645 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1646 ' theme immediately.\n'
1647 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1649 light_green('config ASCII_ART') + ' will output current value of ' +\
1650 light_yellow('ASCII_ART') + ' config key.\n'
1652 light_green('config TREND_MAX default') + ' will output default value of ' + \
1653 light_yellow('TREND_MAX') + ' config key.\n'
1655 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1656 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1658 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1659 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1660 light_yellow('True') + '.\n'
1663 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1664 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1665 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1666 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1667 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1668 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1669 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1672 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1673 usage
+= s
+ 'Have fun and hang tight! \n'
1676 'discover': help_discover
,
1677 'tweets': help_tweets
,
1678 'messages': help_messages
,
1679 'friends_and_followers': help_friends_and_followers
,
1681 'stream': help_stream
,
1686 lambda: printNicely(red('No such command.'))
1694 Pause stream display
1697 printNicely(green('Stream is paused'))
1705 printNicely(green('Stream is running back now'))
1721 printNicely(green('See you next time :)'))
1729 Reset prefix of line
1732 if c
.get('USER_JSON_ERROR'):
1733 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1734 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1736 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1739 printNicely(str(eval(g
['cmd'])))
1791 # Handle function set
1843 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1848 Listen to user's input
1853 ['public', 'mine', 'list'], # switch
1871 ['image'], # show image
1873 ['fl', 'fr'], # list
1875 [i
for i
in g
['message_threads']], # sent
1900 [key
for key
in dict(get_all_config())], # config
1901 g
['themes'], # theme
1906 'friends_and_followers',
1917 init_interactive_shell(d
)
1924 # Only use PREFIX as a string with raw_input
1925 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1928 # Save cmd to compare with readline buffer
1929 g
['cmd'] = line
.strip()
1930 # Get short cmd to pass to handle function
1932 cmd
= line
.split()[0]
1935 # Lock the semaphore
1937 # Save cmd to global variable and call process
1938 g
['stuff'] = ' '.join(line
.split()[1:])
1939 # Process the command
1942 if cmd
in ['switch', 't', 'rt', 'rep']:
1946 # Release the semaphore lock
1952 printNicely(red('OMG something is wrong with Twitter right now.'))
1955 def reconn_notice():
1957 Notice when Hangup or Timeout
1959 guide
= light_magenta("You can use ") + \
1960 light_green("switch") + \
1961 light_magenta(" command to return to your stream.\n")
1962 guide
+= light_magenta("Type ") + \
1963 light_green("h stream") + \
1964 light_magenta(" for more details.")
1966 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1970 def stream(domain
, args
, name
='Rainbow Stream'):
1976 c
['USER_DOMAIN']: name
,
1977 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1978 c
['SITE_DOMAIN']: name
,
1981 ascii_art(art_dict
[domain
])
1982 # These arguments are optional:
1984 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1986 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1989 if args
.track_keywords
:
1990 query_args
['track'] = args
.track_keywords
1992 stream
= TwitterStream(
1997 if domain
== c
['USER_DOMAIN']:
1998 tweet_iter
= stream
.user(**query_args
)
1999 elif domain
== c
['SITE_DOMAIN']:
2000 tweet_iter
= stream
.site(**query_args
)
2002 if args
.track_keywords
:
2003 tweet_iter
= stream
.statuses
.filter(**query_args
)
2005 tweet_iter
= stream
.statuses
.sample()
2006 # Block new stream until other one exits
2007 StreamLock
.acquire()
2008 g
['stream_stop'] = False
2009 last_tweet_time
= time
.time()
2010 for tweet
in tweet_iter
:
2012 printNicely("-- None --")
2013 elif tweet
is Timeout
:
2014 # Because the stream check for each 0.3s
2015 # so we shouldn't output anything here
2016 if(g
['stream_stop']):
2017 StreamLock
.release()
2019 elif tweet
is HeartbeatTimeout
:
2020 printNicely("-- Heartbeat Timeout --")
2022 StreamLock
.release()
2024 elif tweet
is Hangup
:
2025 printNicely("-- Hangup --")
2027 StreamLock
.release()
2029 elif tweet
.get('text'):
2030 # Slow down the stream by STREAM_DELAY config key
2031 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2033 last_tweet_time
= time
.time()
2034 # Check the semaphore pause and lock (stream process only)
2042 keyword
=args
.track_keywords
,
2047 # Current readline buffer
2048 current_buffer
= readline
.get_line_buffer().strip()
2049 # There is an unexpected behaviour in MacOSX readline + Python 2:
2050 # after completely delete a word after typing it,
2051 # somehow readline buffer still contains
2052 # the 1st character of that word
2053 if current_buffer
and g
['cmd'] != current_buffer
:
2055 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2057 elif not c
['HIDE_PROMPT']:
2058 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2060 elif tweet
.get('direct_message'):
2061 # Check the semaphore pause and lock (stream process only)
2066 print_message(tweet
['direct_message'])
2067 elif tweet
.get('event'):
2068 c
['events'].append(tweet
)
2070 except TwitterHTTPError
as e
:
2073 magenta("We have connection problem with twitter'stream API right now :("))
2074 detail_twitter_error(e
)
2075 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2084 args
= parse_arguments()
2088 # Twitter API connection problem
2089 except TwitterHTTPError
as e
:
2092 magenta("We have connection problem with twitter'REST API right now :("))
2093 detail_twitter_error(e
)
2096 # Proxy connection problem
2097 except (socks
.ProxyConnectionError
, URLError
):
2099 magenta("There seems to be a connection problem."))
2101 magenta("You might want to check your proxy settings (host, port and type)!"))
2105 # Spawn stream thread
2106 th
= threading
.Thread(
2111 g
['original_name']))
2114 # Start listen process