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 *
35 StreamLock
= threading
.Lock()
38 def parse_arguments():
42 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
46 help='Timeout for the stream (seconds).')
50 help='Search the stream for specific text.')
54 help='Filter specific screen_name.')
58 help='Ignore specific screen_name.')
63 help='Display all image on terminal.')
67 help='Use HTTP/SOCKS proxy for network connections.')
72 help='HTTP/SOCKS proxy port (Default: 8080).')
77 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
78 return parser
.parse_args()
81 def proxy_connect(args
):
83 Connect to specified proxy
86 # Setup proxy by monkeypatching the standard lib
87 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
88 socks
.set_default_proxy(
89 socks
.SOCKS5
, args
.proxy_host
,
91 elif args
.proxy_type
.lower() == "http":
92 socks
.set_default_proxy(
93 socks
.HTTP
, args
.proxy_host
,
95 elif args
.proxy_type
.lower() == "socks4":
96 socks
.set_default_proxy(
97 socks
.SOCKS4
, args
.proxy_host
,
101 magenta("Sorry, wrong proxy type specified! Aborting..."))
103 socket
.socket
= socks
.socksocket
108 Authenticate with Twitter OAuth
110 # When using rainbow stream you must authorize.
111 twitter_credential
= os
.environ
.get(
115 '')) + os
.sep
+ '.rainbow_oauth'
116 if not os
.path
.exists(twitter_credential
):
117 oauth_dance("Rainbow Stream",
121 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
129 def build_mute_dict(dict_data
=False):
133 t
= Twitter(auth
=authen())
136 screen_name_list
= []
139 while next_cursor
!= 0:
140 list = t
.mutes
.users
.list(
141 screen_name
=g
['original_name'],
144 include_entities
=False,
146 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
147 name_list
+= [u
['name'] for u
in list['users']]
148 next_cursor
= list['next_cursor']
149 # Return dict or list
151 return dict(zip(screen_name_list
, name_list
))
153 return screen_name_list
158 Save traceback when run in debug mode
161 g
['traceback'].append(traceback
.format_exc())
164 def upgrade_center():
166 Check latest and notify to upgrade
169 current
= pkg_resources
.get_distribution("rainbowstream").version
170 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
171 readme
= requests
.get(url
).text
172 latest
= readme
.split("version = \'")[1].split("\'")[0]
173 if current
!= latest
:
174 notice
= light_magenta('RainbowStream latest version is ')
175 notice
+= light_green(latest
)
176 notice
+= light_magenta(' while your current version is ')
177 notice
+= light_yellow(current
) + '\n'
178 notice
+= light_magenta('You should upgrade with ')
179 notice
+= light_green('pip install -U rainbowstream')
182 printNicely(yellow('You are running latest ' + current
+ ' version.'))
192 ctrl_c_handler
= lambda signum
, frame
: quit()
193 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
197 t
= Twitter(auth
=authen())
198 credential
= t
.account
.verify_credentials()
199 screen_name
= '@' + credential
['screen_name']
200 name
= credential
['name']
201 if not get_config('PREFIX'):
202 set_config('PREFIX', screen_name
)
203 c
['PREFIX'] = emojize(c
['PREFIX'])
204 g
['PREFIX'] = u2str(c
['PREFIX'])
205 c
['original_name'] = g
['original_name'] = screen_name
[1:]
206 g
['full_name'] = name
207 g
['decorated_name'] = lambda x
: color_func(
208 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
210 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
211 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
214 g
['message_threads'] = {}
217 # Debug option default = True
224 # Init tweet dict and message dict
226 c
['message_dict'] = []
228 c
['IMAGE_ON_TERM'] = args
.image_on_term
229 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
230 # Check type of ONLY_LIST and IGNORE_LIST
231 if not isinstance(c
['ONLY_LIST'], list):
232 printNicely(red('ONLY_LIST is not a valid list value.'))
234 if not isinstance(c
['IGNORE_LIST'], list):
235 printNicely(red('IGNORE_LIST is not a valid list value.'))
236 c
['IGNORE_LIST'] = []
238 c
['IGNORE_LIST'] += build_mute_dict()
245 t
= Twitter(auth
=authen())
246 # Get country and town
248 country
= g
['stuff'].split()[0]
252 town
= g
['stuff'].split()[1]
255 avail
= t
.trends
.available()
258 trends
= t
.trends
.place(_id
=1)[0]['trends']
261 for location
in avail
:
262 # Search for country and Town
264 if location
['countryCode'] == country \
265 and location
['placeType']['name'] == 'Town' \
266 and location
['name'] == town
:
267 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
269 # Search for country only
271 if location
['countryCode'] == country \
272 and location
['placeType']['name'] == 'Country':
273 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
281 t
= Twitter(auth
=authen())
282 num
= c
['HOME_TWEET_NUM']
283 if g
['stuff'].isdigit():
284 num
= int(g
['stuff'])
285 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
295 for e
in c
['events']:
299 printNicely(magenta('Nothing at this time.'))
306 t
= Twitter(auth
=authen())
307 num
= c
['HOME_TWEET_NUM']
308 if g
['stuff'].isdigit():
309 num
= int(g
['stuff'])
310 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
317 Show profile of a specific user
319 t
= Twitter(auth
=authen())
320 screen_name
= g
['stuff'].split()[0]
321 if screen_name
.startswith('@'):
324 screen_name
=screen_name
[1:],
325 include_entities
=False)
329 printNicely(red('No user.'))
331 printNicely(red('A name should begin with a \'@\''))
338 t
= Twitter(auth
=authen())
339 user
= g
['stuff'].split()[0]
342 num
= int(g
['stuff'].split()[1])
344 num
= c
['HOME_TWEET_NUM']
345 for tweet
in reversed(
346 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
350 printNicely(red('A name should begin with a \'@\''))
357 t
= Twitter(auth
=authen())
359 query
= g
['stuff'].strip()
360 type = c
['SEARCH_TYPE']
361 if type not in ['mixed', 'recent', 'popular']:
363 max_record
= c
['SEARCH_MAX_RECORD']
364 count
= min(max_record
, 100)
366 rel
= t
.search
.tweets(
373 printNicely('Newest tweets:')
374 for i
in reversed(xrange(count
)):
375 draw(t
=rel
[i
], keyword
=query
)
378 printNicely(magenta('I\'m afraid there is no result'))
385 t
= Twitter(auth
=authen())
386 t
.statuses
.update(status
=g
['stuff'])
393 t
= Twitter(auth
=authen())
395 id = int(g
['stuff'].split()[0])
397 printNicely(red('Sorry I can\'t understand.'))
399 tid
= c
['tweet_dict'][id]
400 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
408 t
= Twitter(auth
=authen())
410 id = int(g
['stuff'].split()[0])
412 printNicely(red('Sorry I can\'t understand.'))
414 tid
= c
['tweet_dict'][id]
415 tweet
= t
.statuses
.show(id=tid
)
417 formater
= format_quote(tweet
)
421 prefix
= light_magenta('Compose your ', rl
=True) + \
422 light_green('#comment: ', rl
=True)
423 comment
= raw_input(prefix
)
425 quote
= comment
.join(formater
.split('#comment'))
426 t
.statuses
.update(status
=quote
)
428 printNicely(light_magenta('No text added.'))
435 t
= Twitter(auth
=authen())
438 id = int(g
['stuff'].split()[0])
440 printNicely(red('Sorry I can\'t understand.'))
442 tid
= c
['tweet_dict'][id]
443 # Get display num if exist
445 num
= int(g
['stuff'].split()[1])
447 num
= c
['RETWEETS_SHOW_NUM']
448 # Get result and display
449 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
451 printNicely(magenta('This tweet has no retweet.'))
453 for tweet
in reversed(rt_ary
):
462 t
= Twitter(auth
=authen())
464 id = int(g
['stuff'].split()[0])
466 printNicely(red('Sorry I can\'t understand.'))
468 tid
= c
['tweet_dict'][id]
469 tweet
= t
.statuses
.show(id=tid
)
470 limit
= c
['CONVERSATION_MAX']
472 thread_ref
.append(tweet
)
473 prev_tid
= tweet
['in_reply_to_status_id']
474 while prev_tid
and limit
:
476 tweet
= t
.statuses
.show(id=prev_tid
)
477 prev_tid
= tweet
['in_reply_to_status_id']
478 thread_ref
.append(tweet
)
480 for tweet
in reversed(thread_ref
):
489 t
= Twitter(auth
=authen())
491 id = int(g
['stuff'].split()[0])
493 printNicely(red('Sorry I can\'t understand.'))
495 tid
= c
['tweet_dict'][id]
496 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
497 status
= ' '.join(g
['stuff'].split()[1:])
498 status
= '@' + user
+ ' ' + str2u(status
)
499 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
506 t
= Twitter(auth
=authen())
508 id = int(g
['stuff'].split()[0])
510 printNicely(red('Sorry I can\'t understand.'))
512 tid
= c
['tweet_dict'][id]
513 t
.favorites
.create(_id
=tid
, include_entities
=False)
514 printNicely(green('Favorited.'))
515 draw(t
.statuses
.show(id=tid
))
523 t
= Twitter(auth
=authen())
525 id = int(g
['stuff'].split()[0])
527 printNicely(red('Sorry I can\'t understand.'))
529 tid
= c
['tweet_dict'][id]
530 t
.favorites
.destroy(_id
=tid
)
531 printNicely(green('Okay it\'s unfavorited.'))
532 draw(t
.statuses
.show(id=tid
))
538 Copy url of a tweet to clipboard
540 t
= Twitter(auth
=authen())
542 id = int(g
['stuff'].split()[0])
543 tid
= c
['tweet_dict'][id]
545 printNicely(red('Tweet id is not valid.'))
547 tweet
= t
.statuses
.show(id=tid
)
548 url
= 'https://twitter.com/' + \
549 tweet
['user']['screen_name'] + '/status/' + str(tid
)
551 if platform
.system().lower() == 'darwin':
552 os
.system("echo '%s' | pbcopy" % url
)
553 printNicely(green('Copied tweet\'s url to clipboard.'))
555 printNicely('Direct link: ' + yellow(url
))
562 t
= Twitter(auth
=authen())
564 id = int(g
['stuff'].split()[0])
566 printNicely(red('Sorry I can\'t understand.'))
568 tid
= c
['tweet_dict'][id]
569 t
.statuses
.destroy(id=tid
)
570 printNicely(green('Okay it\'s gone.'))
577 t
= Twitter(auth
=authen())
579 target
= g
['stuff'].split()[0]
580 if target
!= 'image':
582 id = int(g
['stuff'].split()[1])
583 tid
= c
['tweet_dict'][id]
584 tweet
= t
.statuses
.show(id=tid
)
585 media
= tweet
['entities']['media']
587 res
= requests
.get(m
['media_url'])
588 img
= Image
.open(BytesIO(res
.content
))
592 printNicely(red('Sorry I can\'t show this image.'))
599 t
= Twitter(auth
=authen())
601 if not g
['stuff'].isdigit():
603 tid
= c
['tweet_dict'][int(g
['stuff'])]
604 tweet
= t
.statuses
.show(id=tid
)
605 link_prefix
= ('http://', 'https://')
606 link_ary
= [u
for u
in tweet
['text'].split()
607 if u
.startswith(link_prefix
)]
609 printNicely(light_magenta('No url here @.@!'))
611 for link
in link_ary
:
612 webbrowser
.open(link
)
615 printNicely(red('Sorry I can\'t open url in this tweet.'))
622 t
= Twitter(auth
=authen())
623 num
= c
['MESSAGES_DISPLAY']
624 if g
['stuff'].isdigit():
630 inbox
= inbox
+ t
.direct_messages(
633 include_entities
=False,
638 inbox
= inbox
+ t
.direct_messages(
641 include_entities
=False,
645 num
= c
['MESSAGES_DISPLAY']
646 if g
['stuff'].isdigit():
651 sent
= sent
+ t
.direct_messages
.sent(
654 include_entities
=False,
659 sent
= sent
+ t
.direct_messages
.sent(
662 include_entities
=False,
667 uniq_inbox
= list(set(
668 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
670 uniq_sent
= list(set(
671 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
673 for partner
in uniq_inbox
:
674 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
676 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
677 d
[partner
] = inbox_ary
+ sent_ary
678 for partner
in uniq_sent
:
681 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
682 g
['message_threads'] = print_threads(d
)
687 View a thread of message
690 thread_id
= int(g
['stuff'])
692 g
['message_threads'][thread_id
],
697 printNicely(red('No such thread.'))
702 Send a direct message
704 t
= Twitter(auth
=authen())
706 user
= g
['stuff'].split()[0]
707 if user
[0].startswith('@'):
708 content
= ' '.join(g
['stuff'].split()[1:])
709 t
.direct_messages
.new(
710 screen_name
=user
[1:],
713 printNicely(green('Message sent.'))
715 printNicely(red('A name should begin with a \'@\''))
718 printNicely(red('Sorry I can\'t understand.'))
725 t
= Twitter(auth
=authen())
727 id = int(g
['stuff'].split()[0])
729 printNicely(red('Sorry I can\'t understand.'))
730 mid
= c
['message_dict'][id]
731 t
.direct_messages
.destroy(id=mid
)
732 printNicely(green('Message deleted.'))
737 List friends for followers
739 t
= Twitter(auth
=authen())
742 name
= g
['stuff'].split()[1]
743 if name
.startswith('@'):
746 printNicely(red('A name should begin with a \'@\''))
747 raise Exception('Invalid name')
749 name
= g
['original_name']
750 # Get list followers or friends
752 target
= g
['stuff'].split()[0]
754 printNicely(red('Omg some syntax is wrong.'))
756 d
= {'fl': 'followers', 'fr': 'friends'}
760 while next_cursor
!= 0:
761 list = getattr(t
, d
[target
]).list(
765 include_entities
=False,
767 for u
in list['users']:
768 rel
[u
['name']] = '@' + u
['screen_name']
769 next_cursor
= list['next_cursor']
771 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
773 user
= ' ' + cycle_color(name
)
774 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
782 t
= Twitter(auth
=authen())
783 screen_name
= g
['stuff'].split()[0]
784 if screen_name
.startswith('@'):
785 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
786 printNicely(green('You are following ' + screen_name
+ ' now!'))
788 printNicely(red('A name should begin with a \'@\''))
795 t
= Twitter(auth
=authen())
796 screen_name
= g
['stuff'].split()[0]
797 if screen_name
.startswith('@'):
798 t
.friendships
.destroy(
799 screen_name
=screen_name
[1:],
800 include_entities
=False)
801 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
803 printNicely(red('A name should begin with a \'@\''))
810 t
= Twitter(auth
=authen())
812 screen_name
= g
['stuff'].split()[0]
814 printNicely(red('A name should be specified. '))
816 if screen_name
.startswith('@'):
818 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
819 if isinstance(rel
, dict):
820 printNicely(green(screen_name
+ ' is muted.'))
821 c
['IGNORE_LIST'] += [unc(screen_name
)]
822 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
824 printNicely(red(rel
))
827 printNicely(red('Something is wrong, can not mute now :('))
829 printNicely(red('A name should begin with a \'@\''))
836 t
= Twitter(auth
=authen())
838 screen_name
= g
['stuff'].split()[0]
840 printNicely(red('A name should be specified. '))
842 if screen_name
.startswith('@'):
844 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
845 if isinstance(rel
, dict):
846 printNicely(green(screen_name
+ ' is unmuted.'))
847 c
['IGNORE_LIST'].remove(screen_name
)
849 printNicely(red(rel
))
851 printNicely(red('Maybe you are not muting this person ?'))
853 printNicely(red('A name should begin with a \'@\''))
860 # Get dict of muting users
861 md
= build_mute_dict(dict_data
=True)
862 printNicely('All: ' + str(len(md
)) + ' people.')
864 user
= ' ' + cycle_color(md
[name
])
865 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
867 # Update from Twitter
868 c
['IGNORE_LIST'] = [n
for n
in md
]
875 t
= Twitter(auth
=authen())
876 screen_name
= g
['stuff'].split()[0]
877 if screen_name
.startswith('@'):
879 screen_name
=screen_name
[1:],
880 include_entities
=False,
882 printNicely(green('You blocked ' + screen_name
+ '.'))
884 printNicely(red('A name should begin with a \'@\''))
891 t
= Twitter(auth
=authen())
892 screen_name
= g
['stuff'].split()[0]
893 if screen_name
.startswith('@'):
895 screen_name
=screen_name
[1:],
896 include_entities
=False,
898 printNicely(green('Unblock ' + screen_name
+ ' success!'))
900 printNicely(red('A name should begin with a \'@\''))
905 Report a user as a spam account
907 t
= Twitter(auth
=authen())
908 screen_name
= g
['stuff'].split()[0]
909 if screen_name
.startswith('@'):
911 screen_name
=screen_name
[1:])
912 printNicely(green('You reported ' + screen_name
+ '.'))
914 printNicely(red('Sorry I can\'t understand.'))
922 list_name
= raw_input(
923 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
924 # Get list name and owner
926 owner
, slug
= list_name
.split('/')
927 if slug
.startswith('@'):
932 light_magenta('List name should follow "@owner/list_name" format.'))
933 raise Exception('Wrong list name')
940 rel
= t
.lists
.list(screen_name
=g
['original_name'])
944 printNicely(light_magenta('You belong to no lists :)'))
951 owner
, slug
= get_slug()
952 res
= t
.lists
.statuses(
954 owner_screen_name
=owner
,
956 include_entities
=False)
957 for tweet
in reversed(res
):
966 owner
, slug
= get_slug()
970 while next_cursor
!= 0:
973 owner_screen_name
=owner
,
975 include_entities
=False)
977 rel
[u
['name']] = '@' + u
['screen_name']
978 next_cursor
= m
['next_cursor']
979 printNicely('All: ' + str(len(rel
)) + ' members.')
981 user
= ' ' + cycle_color(name
)
982 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
986 def list_subscribers(t
):
990 owner
, slug
= get_slug()
994 while next_cursor
!= 0:
995 m
= t
.lists
.subscribers(
997 owner_screen_name
=owner
,
999 include_entities
=False)
1000 for u
in m
['users']:
1001 rel
[u
['name']] = '@' + u
['screen_name']
1002 next_cursor
= m
['next_cursor']
1003 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1005 user
= ' ' + cycle_color(name
)
1006 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1012 Add specific user to a list
1014 owner
, slug
= get_slug()
1016 user_name
= raw_input(
1018 'Give me name of the newbie: ',
1020 if user_name
.startswith('@'):
1021 user_name
= user_name
[1:]
1023 t
.lists
.members
.create(
1025 owner_screen_name
=owner
,
1026 screen_name
=user_name
)
1027 printNicely(green('Added.'))
1030 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1035 Remove specific user from a list
1037 owner
, slug
= get_slug()
1039 user_name
= raw_input(
1041 'Give me name of the unlucky one: ',
1043 if user_name
.startswith('@'):
1044 user_name
= user_name
[1:]
1046 t
.lists
.members
.destroy(
1048 owner_screen_name
=owner
,
1049 screen_name
=user_name
)
1050 printNicely(green('Gone.'))
1053 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1056 def list_subscribe(t
):
1060 owner
, slug
= get_slug()
1063 t
.lists
.subscribers
.create(
1065 owner_screen_name
=owner
)
1066 printNicely(green('Done.'))
1070 light_magenta('I\'m sorry you can not subscribe to this list.'))
1073 def list_unsubscribe(t
):
1077 owner
, slug
= get_slug()
1080 t
.lists
.subscribers
.destroy(
1082 owner_screen_name
=owner
)
1083 printNicely(green('Done.'))
1087 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1096 while next_cursor
!= 0:
1097 res
= t
.lists
.ownerships(
1098 screen_name
=g
['original_name'],
1101 next_cursor
= res
['next_cursor']
1105 printNicely(light_magenta('You own no lists :)'))
1112 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1115 'New list\'s mode (public/private): ',
1117 description
= raw_input(
1119 'New list\'s description: ',
1125 description
=description
)
1126 printNicely(green(name
+ ' list is created.'))
1129 printNicely(red('Oops something is wrong with Twitter :('))
1138 'Your list that you want to update: ',
1142 'Update name (leave blank to unchange): ',
1144 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1145 description
= raw_input(light_magenta('Update description: ', rl
=True))
1149 slug
='-'.join(slug
.split()),
1150 owner_screen_name
=g
['original_name'],
1153 description
=description
)
1157 owner_screen_name
=g
['original_name'],
1159 description
=description
)
1160 printNicely(green(slug
+ ' list is updated.'))
1163 printNicely(red('Oops something is wrong with Twitter :('))
1172 'Your list that you want to delete: ',
1176 slug
='-'.join(slug
.split()),
1177 owner_screen_name
=g
['original_name'])
1178 printNicely(green(slug
+ ' list is deleted.'))
1181 printNicely(red('Oops something is wrong with Twitter :('))
1188 t
= Twitter(auth
=authen())
1189 # List all lists or base on action
1191 g
['list_action'] = g
['stuff'].split()[0]
1198 'all_mem': list_members
,
1199 'all_sub': list_subscribers
,
1202 'sub': list_subscribe
,
1203 'unsub': list_unsubscribe
,
1206 'update': list_update
,
1210 return action_ary
[g
['list_action']](t
)
1212 printNicely(red('Please try again.'))
1220 target
= g
['stuff'].split()[0]
1222 args
= parse_arguments()
1224 if g
['stuff'].split()[-1] == '-f':
1225 guide
= 'To ignore an option, just hit Enter key.'
1226 printNicely(light_magenta(guide
))
1227 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1228 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1229 args
.filter = filter(None, only
.split(','))
1230 args
.ignore
= filter(None, ignore
.split(','))
1232 printNicely(red('Sorry, wrong format.'))
1235 if target
== 'public':
1236 keyword
= g
['stuff'].split()[1]
1237 if keyword
[0] == '#':
1238 keyword
= keyword
[1:]
1240 g
['stream_stop'] = True
1241 args
.track_keywords
= keyword
1243 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1245 th
= threading
.Thread(
1253 elif target
== 'mine':
1255 g
['stream_stop'] = True
1257 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1259 th
= threading
.Thread(
1264 g
['original_name']))
1267 # Stream base on list
1268 elif target
== 'list':
1269 owner
, slug
= get_slug()
1270 # Force python 2 not redraw readline buffer
1271 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1272 printNicely(light_yellow('getting list members ...'))
1274 t
= Twitter(auth
=authen())
1277 while next_cursor
!= 0:
1278 m
= t
.lists
.members(
1280 owner_screen_name
=owner
,
1282 include_entities
=False)
1283 for u
in m
['users']:
1284 members
.append('@' + u
['screen_name'])
1285 next_cursor
= m
['next_cursor']
1286 printNicely(light_yellow('... done.'))
1287 # Build thread filter array
1288 args
.filter = members
1290 g
['stream_stop'] = True
1292 th
= threading
.Thread(
1302 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1304 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1308 printNicely(red('Sorry I can\'t understand.'))
1313 Unix's command `cal`
1316 rel
= os
.popen('cal').read().split('\n')
1319 show_calendar(month
, date
, rel
)
1324 List and change theme
1328 for theme
in g
['themes']:
1329 line
= light_magenta(theme
)
1330 if c
['THEME'] == theme
:
1331 line
= ' ' * 2 + light_yellow('* ') + line
1333 line
= ' ' * 4 + line
1339 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1340 # Redefine decorated_name
1341 g
['decorated_name'] = lambda x
: color_func(
1342 c
['DECORATED_NAME'])(
1344 printNicely(green('Theme changed.'))
1346 printNicely(red('No such theme exists.'))
1351 Browse and change config
1353 all_config
= get_all_config()
1354 g
['stuff'] = g
['stuff'].strip()
1357 for k
in all_config
:
1359 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1361 guide
= 'Detailed explanation can be found at ' + \
1362 color_func(c
['TWEET']['link'])(
1363 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1365 # Print specific config
1366 elif len(g
['stuff'].split()) == 1:
1367 if g
['stuff'] in all_config
:
1370 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1373 printNicely(red('No such config key.'))
1374 # Print specific config's default value
1375 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1376 key
= g
['stuff'].split()[0]
1378 value
= get_default_config(key
)
1379 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1383 printNicely(red('Just can not get the default.'))
1384 # Delete specific config key in config file
1385 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1386 key
= g
['stuff'].split()[0]
1389 printNicely(green('Config key is dropped.'))
1392 printNicely(red('Just can not drop the key.'))
1393 # Set specific config
1394 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1395 key
= g
['stuff'].split()[0]
1396 value
= g
['stuff'].split()[-1]
1397 if key
== 'THEME' and not validate_theme(value
):
1398 printNicely(red('Invalid theme\'s value.'))
1401 set_config(key
, value
)
1402 # Keys that needs to be apply immediately
1404 c
['THEME'] = reload_theme(value
, c
['THEME'])
1405 g
['decorated_name'] = lambda x
: color_func(
1406 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1407 elif key
== 'PREFIX':
1408 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1410 printNicely(green('Updated successfully.'))
1413 printNicely(red('Just can not set the key.'))
1415 printNicely(light_magenta('Sorry I can\'s understand.'))
1418 def help_discover():
1423 # Discover the world
1425 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1426 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1427 'You can try ' + light_green('trend US') + ' or ' + \
1428 light_green('trend JP Tokyo') + '.\n'
1429 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1430 light_green('home 7') + ' will show 7 tweets.\n'
1432 light_green('notification') + ' will show your recent notification.\n'
1433 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1434 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1435 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1436 magenta('@mdo') + '.\n'
1437 usage
+= s
* 2 + light_green('view @mdo') + \
1438 ' will show ' + magenta('@mdo') + '\'s home.\n'
1439 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1440 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1441 'Search can be performed with or without hashtag.\n'
1452 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1453 usage
+= s
* 2 + light_green('t oops ') + \
1454 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1456 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1457 light_yellow('[id=12]') + '.\n'
1459 light_green('quote 12 ') + ' will quote the tweet with ' + \
1460 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1461 'the quote will be canceled.\n'
1463 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1464 light_yellow('[id=12]') + '.\n'
1465 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1466 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1467 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1468 light_yellow('oops') + '" to tweet with ' + \
1469 light_yellow('[id=12]') + '.\n'
1471 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1472 light_yellow('[id=12]') + '.\n'
1474 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1475 light_yellow('[id=12]') + '.\n'
1477 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1478 light_yellow('[id=12]') + '.\n'
1480 light_green('del 12 ') + ' will delete tweet with ' + \
1481 light_yellow('[id=12]') + '.\n'
1482 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1483 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1484 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1485 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1489 def help_messages():
1496 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1497 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1498 light_green('inbox 7') + ' will show newest 7 messages.\n'
1499 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1500 light_yellow('[thread_id=2]') + '.\n'
1501 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1502 magenta('@dtvd88') + '.\n'
1503 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1504 light_yellow('[message_id=5]') + '.\n'
1508 def help_friends_and_followers():
1510 Friends and Followers
1513 # Follower and following
1515 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1517 light_green('ls fl') + \
1518 ' will list all followers (people who are following you).\n'
1520 light_green('ls fr') + \
1521 ' will list all friends (people who you are following).\n'
1522 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1523 magenta('@dtvd88') + '.\n'
1524 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1525 magenta('@dtvd88') + '.\n'
1526 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1527 magenta('@dtvd88') + '.\n'
1528 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1529 magenta('@dtvd88') + '.\n'
1530 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1531 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1532 magenta('@dtvd88') + '.\n'
1533 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1534 magenta('@dtvd88') + '.\n'
1535 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1536 magenta('@dtvd88') + ' as a spam account.\n'
1547 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1548 usage
+= s
* 2 + light_green('list') + \
1549 ' will show all lists you are belong to.\n'
1550 usage
+= s
* 2 + light_green('list home') + \
1551 ' will show timeline of list. You will be asked for list\'s name.\n'
1552 usage
+= s
* 2 + light_green('list all_mem') + \
1553 ' will show list\'s all members.\n'
1554 usage
+= s
* 2 + light_green('list all_sub') + \
1555 ' will show list\'s all subscribers.\n'
1556 usage
+= s
* 2 + light_green('list add') + \
1557 ' will add specific person to a list owned by you.' + \
1558 ' You will be asked for list\'s name and person\'s name.\n'
1559 usage
+= s
* 2 + light_green('list rm') + \
1560 ' will remove specific person from 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 sub') + \
1563 ' will subscribe you to a specific list.\n'
1564 usage
+= s
* 2 + light_green('list unsub') + \
1565 ' will unsubscribe you from a specific list.\n'
1566 usage
+= s
* 2 + light_green('list own') + \
1567 ' will show all list owned by you.\n'
1568 usage
+= s
* 2 + light_green('list new') + \
1569 ' will create a new list.\n'
1570 usage
+= s
* 2 + light_green('list update') + \
1571 ' will update a list owned by you.\n'
1572 usage
+= s
* 2 + light_green('list del') + \
1573 ' will delete a list owned by you.\n'
1584 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1585 usage
+= s
* 2 + light_green('switch public #AKB') + \
1586 ' will switch to public stream and follow "' + \
1587 light_yellow('AKB') + '" keyword.\n'
1588 usage
+= s
* 2 + light_green('switch mine') + \
1589 ' will switch to your personal stream.\n'
1590 usage
+= s
* 2 + light_green('switch mine -f ') + \
1591 ' will prompt to enter the filter.\n'
1592 usage
+= s
* 3 + light_yellow('Only nicks') + \
1593 ' filter will decide nicks will be INCLUDE ONLY.\n'
1594 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1595 ' filter will decide nicks will be EXCLUDE.\n'
1596 usage
+= s
* 2 + light_green('switch list') + \
1597 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1606 h
, w
= os
.popen('stty size', 'r').read().split()
1609 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1610 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1611 usage
+= s
+ 'You are ' + \
1612 light_yellow('already') + ' on your personal stream.\n'
1613 usage
+= s
+ 'Any update from Twitter will show up ' + \
1614 light_yellow('immediately') + '.\n'
1615 usage
+= s
+ 'In addition, following commands are available right now:\n'
1616 # Twitter help section
1618 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1619 usage
+= s
* 2 + light_green('h discover') + \
1620 ' will show help for discover commands.\n'
1621 usage
+= s
* 2 + light_green('h tweets') + \
1622 ' will show help for tweets commands.\n'
1623 usage
+= s
* 2 + light_green('h messages') + \
1624 ' will show help for messages commands.\n'
1625 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1626 ' will show help for friends and followers commands.\n'
1627 usage
+= s
* 2 + light_green('h list') + \
1628 ' will show help for list commands.\n'
1629 usage
+= s
* 2 + light_green('h stream') + \
1630 ' will show help for stream commands.\n'
1633 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1634 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1635 'will be evaluate by Python interpreter.\n'
1636 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1637 ' for current month.\n'
1640 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1641 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1642 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1643 ' theme immediately.\n'
1644 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1646 light_green('config ASCII_ART') + ' will output current value of ' +\
1647 light_yellow('ASCII_ART') + ' config key.\n'
1649 light_green('config TREND_MAX default') + ' will output default value of ' + \
1650 light_yellow('TREND_MAX') + ' config key.\n'
1652 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1653 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1655 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1656 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1657 light_yellow('True') + '.\n'
1660 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1661 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1662 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1663 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1664 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1665 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1668 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1669 usage
+= s
+ 'Have fun and hang tight! \n'
1672 'discover': help_discover
,
1673 'tweets': help_tweets
,
1674 'messages': help_messages
,
1675 'friends_and_followers': help_friends_and_followers
,
1677 'stream': help_stream
,
1682 lambda: printNicely(red('No such command.'))
1690 Pause stream display
1693 printNicely(green('Stream is paused'))
1701 printNicely(green('Stream is running back now'))
1717 printNicely(green('See you next time :)'))
1725 Reset prefix of line
1728 if c
.get('USER_JSON_ERROR'):
1729 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1730 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1732 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1735 printNicely(str(eval(g
['cmd'])))
1787 # Handle function set
1839 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1844 Listen to user's input
1849 ['public', 'mine', 'list'], # switch
1867 ['image'], # show image
1869 ['fl', 'fr'], # list
1871 [i
for i
in g
['message_threads']], # sent
1896 [key
for key
in dict(get_all_config())], # config
1897 g
['themes'], # theme
1902 'friends_and_followers',
1913 init_interactive_shell(d
)
1920 # Only use PREFIX as a string with raw_input
1921 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1924 # Save cmd to compare with readline buffer
1925 g
['cmd'] = line
.strip()
1926 # Get short cmd to pass to handle function
1928 cmd
= line
.split()[0]
1931 # Lock the semaphore
1933 # Save cmd to global variable and call process
1934 g
['stuff'] = ' '.join(line
.split()[1:])
1935 # Process the command
1938 if cmd
in ['switch', 't', 'rt', 'rep']:
1942 # Release the semaphore lock
1948 printNicely(red('OMG something is wrong with Twitter right now.'))
1951 def reconn_notice():
1953 Notice when Hangup or Timeout
1955 guide
= light_magenta("You can use ") + \
1956 light_green("switch") + \
1957 light_magenta(" command to return to your stream.\n")
1958 guide
+= light_magenta("Type ") + \
1959 light_green("h stream") + \
1960 light_magenta(" for more details.")
1962 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1966 def stream(domain
, args
, name
='Rainbow Stream'):
1972 c
['USER_DOMAIN']: name
,
1973 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1974 c
['SITE_DOMAIN']: name
,
1977 ascii_art(art_dict
[domain
])
1978 # These arguments are optional:
1980 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1982 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1985 if args
.track_keywords
:
1986 query_args
['track'] = args
.track_keywords
1988 stream
= TwitterStream(
1993 if domain
== c
['USER_DOMAIN']:
1994 tweet_iter
= stream
.user(**query_args
)
1995 elif domain
== c
['SITE_DOMAIN']:
1996 tweet_iter
= stream
.site(**query_args
)
1998 if args
.track_keywords
:
1999 tweet_iter
= stream
.statuses
.filter(**query_args
)
2001 tweet_iter
= stream
.statuses
.sample()
2002 # Block new stream until other one exits
2003 StreamLock
.acquire()
2004 g
['stream_stop'] = False
2005 last_tweet_time
= time
.time()
2006 for tweet
in tweet_iter
:
2008 printNicely("-- None --")
2009 elif tweet
is Timeout
:
2010 # Because the stream check for each 0.3s
2011 # so we shouldn't output anything here
2012 if(g
['stream_stop']):
2013 StreamLock
.release()
2015 elif tweet
is HeartbeatTimeout
:
2016 printNicely("-- Heartbeat Timeout --")
2018 StreamLock
.release()
2020 elif tweet
is Hangup
:
2021 printNicely("-- Hangup --")
2023 StreamLock
.release()
2025 elif tweet
.get('text'):
2026 # Slow down the stream by STREAM_DELAY config key
2027 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2029 last_tweet_time
= time
.time()
2030 # Check the semaphore pause and lock (stream process only)
2038 keyword
=args
.track_keywords
,
2043 # Current readline buffer
2044 current_buffer
= readline
.get_line_buffer().strip()
2045 # There is an unexpected behaviour in MacOSX readline + Python 2:
2046 # after completely delete a word after typing it,
2047 # somehow readline buffer still contains
2048 # the 1st character of that word
2049 if current_buffer
and g
['cmd'] != current_buffer
:
2051 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2053 elif not c
['HIDE_PROMPT']:
2054 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2056 elif tweet
.get('direct_message'):
2057 # Check the semaphore pause and lock (stream process only)
2062 print_message(tweet
['direct_message'])
2063 elif tweet
.get('event'):
2064 c
['events'].append(tweet
)
2066 except TwitterHTTPError
:
2069 magenta("We have maximum connection problem with twitter'stream API right now :("))
2077 args
= parse_arguments()
2081 # Twitter API connection problem
2082 except TwitterHTTPError
:
2085 magenta("We have connection problem with twitter'stream API right now :("))
2086 printNicely(magenta("Let's try again later."))
2089 # Proxy connection problem
2090 except (socks
.ProxyConnectionError
, URLError
):
2092 magenta("There seems to be a connection problem."))
2094 magenta("You might want to check your proxy settings (host, port and type)!"))
2098 # Spawn stream thread
2099 th
= threading
.Thread(
2104 g
['original_name']))
2107 # Start listen process