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')
190 ctrl_c_handler
= lambda signum
, frame
: quit()
191 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
195 t
= Twitter(auth
=authen())
196 credential
= t
.account
.verify_credentials()
197 screen_name
= '@' + credential
['screen_name']
198 name
= credential
['name']
199 if not get_config('PREFIX'):
200 set_config('PREFIX', screen_name
)
201 c
['PREFIX'] = emojize(c
['PREFIX'])
202 g
['PREFIX'] = u2str(c
['PREFIX'])
203 c
['original_name'] = g
['original_name'] = screen_name
[1:]
204 g
['full_name'] = name
205 g
['decorated_name'] = lambda x
: color_func(
206 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
208 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
209 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
212 g
['message_threads'] = {}
215 # Debug option default = True
222 # Init tweet dict and message dict
224 c
['message_dict'] = []
226 c
['IMAGE_ON_TERM'] = args
.image_on_term
227 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
228 # Check type of ONLY_LIST and IGNORE_LIST
229 if not isinstance(c
['ONLY_LIST'], list):
230 printNicely(red('ONLY_LIST is not a valid list value.'))
232 if not isinstance(c
['IGNORE_LIST'], list):
233 printNicely(red('IGNORE_LIST is not a valid list value.'))
234 c
['IGNORE_LIST'] = []
236 c
['IGNORE_LIST'] += build_mute_dict()
243 t
= Twitter(auth
=authen())
244 # Get country and town
246 country
= g
['stuff'].split()[0]
250 town
= g
['stuff'].split()[1]
253 avail
= t
.trends
.available()
256 trends
= t
.trends
.place(_id
=1)[0]['trends']
259 for location
in avail
:
260 # Search for country and Town
262 if location
['countryCode'] == country \
263 and location
['placeType']['name'] == 'Town' \
264 and location
['name'] == town
:
265 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
267 # Search for country only
269 if location
['countryCode'] == country \
270 and location
['placeType']['name'] == 'Country':
271 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
279 t
= Twitter(auth
=authen())
280 num
= c
['HOME_TWEET_NUM']
281 if g
['stuff'].isdigit():
282 num
= int(g
['stuff'])
283 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
293 for e
in c
['events']:
297 printNicely(magenta('Nothing at this time.'))
304 t
= Twitter(auth
=authen())
305 num
= c
['HOME_TWEET_NUM']
306 if g
['stuff'].isdigit():
307 num
= int(g
['stuff'])
308 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
315 Show profile of a specific user
317 t
= Twitter(auth
=authen())
318 screen_name
= g
['stuff'].split()[0]
319 if screen_name
.startswith('@'):
322 screen_name
=screen_name
[1:],
323 include_entities
=False)
327 printNicely(red('No user.'))
329 printNicely(red('A name should begin with a \'@\''))
336 t
= Twitter(auth
=authen())
337 user
= g
['stuff'].split()[0]
340 num
= int(g
['stuff'].split()[1])
342 num
= c
['HOME_TWEET_NUM']
343 for tweet
in reversed(
344 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
348 printNicely(red('A name should begin with a \'@\''))
355 t
= Twitter(auth
=authen())
357 query
= g
['stuff'].strip()
358 type = c
['SEARCH_TYPE']
359 if type not in ['mixed', 'recent', 'popular']:
361 max_record
= c
['SEARCH_MAX_RECORD']
362 count
= min(max_record
, 100)
364 rel
= t
.search
.tweets(
371 printNicely('Newest tweets:')
372 for i
in reversed(xrange(count
)):
373 draw(t
=rel
[i
], keyword
=query
)
376 printNicely(magenta('I\'m afraid there is no result'))
383 t
= Twitter(auth
=authen())
384 t
.statuses
.update(status
=g
['stuff'])
391 t
= Twitter(auth
=authen())
393 id = int(g
['stuff'].split()[0])
395 printNicely(red('Sorry I can\'t understand.'))
397 tid
= c
['tweet_dict'][id]
398 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
406 t
= Twitter(auth
=authen())
408 id = int(g
['stuff'].split()[0])
410 printNicely(red('Sorry I can\'t understand.'))
412 tid
= c
['tweet_dict'][id]
413 tweet
= t
.statuses
.show(id=tid
)
415 formater
= format_quote(tweet
)
419 prefix
= light_magenta('Compose your ', rl
=True) + \
420 light_green('#comment: ', rl
=True)
421 comment
= raw_input(prefix
)
423 quote
= comment
.join(formater
.split('#comment'))
424 t
.statuses
.update(status
=quote
)
426 printNicely(light_magenta('No text added.'))
433 t
= Twitter(auth
=authen())
436 id = int(g
['stuff'].split()[0])
438 printNicely(red('Sorry I can\'t understand.'))
440 tid
= c
['tweet_dict'][id]
441 # Get display num if exist
443 num
= int(g
['stuff'].split()[1])
445 num
= c
['RETWEETS_SHOW_NUM']
446 # Get result and display
447 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
449 printNicely(magenta('This tweet has no retweet.'))
451 for tweet
in reversed(rt_ary
):
460 t
= Twitter(auth
=authen())
462 id = int(g
['stuff'].split()[0])
464 printNicely(red('Sorry I can\'t understand.'))
466 tid
= c
['tweet_dict'][id]
467 tweet
= t
.statuses
.show(id=tid
)
468 limit
= c
['CONVERSATION_MAX']
470 thread_ref
.append(tweet
)
471 prev_tid
= tweet
['in_reply_to_status_id']
472 while prev_tid
and limit
:
474 tweet
= t
.statuses
.show(id=prev_tid
)
475 prev_tid
= tweet
['in_reply_to_status_id']
476 thread_ref
.append(tweet
)
478 for tweet
in reversed(thread_ref
):
487 t
= Twitter(auth
=authen())
489 id = int(g
['stuff'].split()[0])
491 printNicely(red('Sorry I can\'t understand.'))
493 tid
= c
['tweet_dict'][id]
494 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
495 status
= ' '.join(g
['stuff'].split()[1:])
496 status
= '@' + user
+ ' ' + str2u(status
)
497 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
504 t
= Twitter(auth
=authen())
506 id = int(g
['stuff'].split()[0])
508 printNicely(red('Sorry I can\'t understand.'))
510 tid
= c
['tweet_dict'][id]
511 t
.favorites
.create(_id
=tid
, include_entities
=False)
512 printNicely(green('Favorited.'))
513 draw(t
.statuses
.show(id=tid
))
521 t
= Twitter(auth
=authen())
523 id = int(g
['stuff'].split()[0])
525 printNicely(red('Sorry I can\'t understand.'))
527 tid
= c
['tweet_dict'][id]
528 t
.favorites
.destroy(_id
=tid
)
529 printNicely(green('Okay it\'s unfavorited.'))
530 draw(t
.statuses
.show(id=tid
))
536 Copy url of a tweet to clipboard
538 t
= Twitter(auth
=authen())
540 id = int(g
['stuff'].split()[0])
541 tid
= c
['tweet_dict'][id]
543 printNicely(red('Tweet id is not valid.'))
545 tweet
= t
.statuses
.show(id=tid
)
546 url
= 'https://twitter.com/' + \
547 tweet
['user']['screen_name'] + '/status/' + str(tid
)
549 if platform
.system().lower() == 'darwin':
550 os
.system("echo '%s' | pbcopy" % url
)
551 printNicely(green('Copied tweet\'s url to clipboard.'))
553 printNicely('Direct link: ' + yellow(url
))
560 t
= Twitter(auth
=authen())
562 id = int(g
['stuff'].split()[0])
564 printNicely(red('Sorry I can\'t understand.'))
566 tid
= c
['tweet_dict'][id]
567 t
.statuses
.destroy(id=tid
)
568 printNicely(green('Okay it\'s gone.'))
575 t
= Twitter(auth
=authen())
577 target
= g
['stuff'].split()[0]
578 if target
!= 'image':
580 id = int(g
['stuff'].split()[1])
581 tid
= c
['tweet_dict'][id]
582 tweet
= t
.statuses
.show(id=tid
)
583 media
= tweet
['entities']['media']
585 res
= requests
.get(m
['media_url'])
586 img
= Image
.open(BytesIO(res
.content
))
590 printNicely(red('Sorry I can\'t show this image.'))
597 t
= Twitter(auth
=authen())
599 if not g
['stuff'].isdigit():
601 tid
= c
['tweet_dict'][int(g
['stuff'])]
602 tweet
= t
.statuses
.show(id=tid
)
603 link_prefix
= ('http://', 'https://')
604 link_ary
= [u
for u
in tweet
['text'].split()
605 if u
.startswith(link_prefix
)]
607 printNicely(light_magenta('No url here @.@!'))
609 for link
in link_ary
:
610 webbrowser
.open(link
)
613 printNicely(red('Sorry I can\'t open url in this tweet.'))
620 t
= Twitter(auth
=authen())
621 num
= c
['MESSAGES_DISPLAY']
622 if g
['stuff'].isdigit():
628 inbox
= inbox
+ t
.direct_messages(
631 include_entities
=False,
636 inbox
= inbox
+ t
.direct_messages(
639 include_entities
=False,
643 num
= c
['MESSAGES_DISPLAY']
644 if g
['stuff'].isdigit():
649 sent
= sent
+ t
.direct_messages
.sent(
652 include_entities
=False,
657 sent
= sent
+ t
.direct_messages
.sent(
660 include_entities
=False,
665 uniq_inbox
= list(set(
666 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
668 uniq_sent
= list(set(
669 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
671 for partner
in uniq_inbox
:
672 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
674 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
675 d
[partner
] = inbox_ary
+ sent_ary
676 for partner
in uniq_sent
:
679 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
680 g
['message_threads'] = print_threads(d
)
685 View a thread of message
688 thread_id
= int(g
['stuff'])
690 g
['message_threads'][thread_id
],
695 printNicely(red('No such thread.'))
700 Send a direct message
702 t
= Twitter(auth
=authen())
704 user
= g
['stuff'].split()[0]
705 if user
[0].startswith('@'):
706 content
= ' '.join(g
['stuff'].split()[1:])
707 t
.direct_messages
.new(
708 screen_name
=user
[1:],
711 printNicely(green('Message sent.'))
713 printNicely(red('A name should begin with a \'@\''))
716 printNicely(red('Sorry I can\'t understand.'))
723 t
= Twitter(auth
=authen())
725 id = int(g
['stuff'].split()[0])
727 printNicely(red('Sorry I can\'t understand.'))
728 mid
= c
['message_dict'][id]
729 t
.direct_messages
.destroy(id=mid
)
730 printNicely(green('Message deleted.'))
735 List friends for followers
737 t
= Twitter(auth
=authen())
740 name
= g
['stuff'].split()[1]
741 if name
.startswith('@'):
744 printNicely(red('A name should begin with a \'@\''))
745 raise Exception('Invalid name')
747 name
= g
['original_name']
748 # Get list followers or friends
750 target
= g
['stuff'].split()[0]
752 printNicely(red('Omg some syntax is wrong.'))
754 d
= {'fl': 'followers', 'fr': 'friends'}
758 while next_cursor
!= 0:
759 list = getattr(t
, d
[target
]).list(
763 include_entities
=False,
765 for u
in list['users']:
766 rel
[u
['name']] = '@' + u
['screen_name']
767 next_cursor
= list['next_cursor']
769 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
771 user
= ' ' + cycle_color(name
)
772 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
780 t
= Twitter(auth
=authen())
781 screen_name
= g
['stuff'].split()[0]
782 if screen_name
.startswith('@'):
783 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
784 printNicely(green('You are following ' + screen_name
+ ' now!'))
786 printNicely(red('A name should begin with a \'@\''))
793 t
= Twitter(auth
=authen())
794 screen_name
= g
['stuff'].split()[0]
795 if screen_name
.startswith('@'):
796 t
.friendships
.destroy(
797 screen_name
=screen_name
[1:],
798 include_entities
=False)
799 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
801 printNicely(red('A name should begin with a \'@\''))
808 t
= Twitter(auth
=authen())
810 screen_name
= g
['stuff'].split()[0]
812 printNicely(red('A name should be specified. '))
814 if screen_name
.startswith('@'):
816 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
817 if isinstance(rel
, dict):
818 printNicely(green(screen_name
+ ' is muted.'))
819 c
['IGNORE_LIST'] += [unc(screen_name
)]
820 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
822 printNicely(red(rel
))
825 printNicely(red('Something is wrong, can not mute now :('))
827 printNicely(red('A name should begin with a \'@\''))
834 t
= Twitter(auth
=authen())
836 screen_name
= g
['stuff'].split()[0]
838 printNicely(red('A name should be specified. '))
840 if screen_name
.startswith('@'):
842 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
843 if isinstance(rel
, dict):
844 printNicely(green(screen_name
+ ' is unmuted.'))
845 c
['IGNORE_LIST'].remove(screen_name
)
847 printNicely(red(rel
))
849 printNicely(red('Maybe you are not muting this person ?'))
851 printNicely(red('A name should begin with a \'@\''))
858 # Get dict of muting users
859 md
= build_mute_dict(dict_data
=True)
860 printNicely('All: ' + str(len(md
)) + ' people.')
862 user
= ' ' + cycle_color(md
[name
])
863 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
865 # Update from Twitter
866 c
['IGNORE_LIST'] = [n
for n
in md
]
873 t
= Twitter(auth
=authen())
874 screen_name
= g
['stuff'].split()[0]
875 if screen_name
.startswith('@'):
877 screen_name
=screen_name
[1:],
878 include_entities
=False,
880 printNicely(green('You blocked ' + screen_name
+ '.'))
882 printNicely(red('A name should begin with a \'@\''))
889 t
= Twitter(auth
=authen())
890 screen_name
= g
['stuff'].split()[0]
891 if screen_name
.startswith('@'):
893 screen_name
=screen_name
[1:],
894 include_entities
=False,
896 printNicely(green('Unblock ' + screen_name
+ ' success!'))
898 printNicely(red('A name should begin with a \'@\''))
903 Report a user as a spam account
905 t
= Twitter(auth
=authen())
906 screen_name
= g
['stuff'].split()[0]
907 if screen_name
.startswith('@'):
909 screen_name
=screen_name
[1:])
910 printNicely(green('You reported ' + screen_name
+ '.'))
912 printNicely(red('Sorry I can\'t understand.'))
920 list_name
= raw_input(
921 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
922 # Get list name and owner
924 owner
, slug
= list_name
.split('/')
925 if slug
.startswith('@'):
930 light_magenta('List name should follow "@owner/list_name" format.'))
931 raise Exception('Wrong list name')
938 rel
= t
.lists
.list(screen_name
=g
['original_name'])
942 printNicely(light_magenta('You belong to no lists :)'))
949 owner
, slug
= get_slug()
950 res
= t
.lists
.statuses(
952 owner_screen_name
=owner
,
954 include_entities
=False)
955 for tweet
in reversed(res
):
964 owner
, slug
= get_slug()
968 while next_cursor
!= 0:
971 owner_screen_name
=owner
,
973 include_entities
=False)
975 rel
[u
['name']] = '@' + u
['screen_name']
976 next_cursor
= m
['next_cursor']
977 printNicely('All: ' + str(len(rel
)) + ' members.')
979 user
= ' ' + cycle_color(name
)
980 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
984 def list_subscribers(t
):
988 owner
, slug
= get_slug()
992 while next_cursor
!= 0:
993 m
= t
.lists
.subscribers(
995 owner_screen_name
=owner
,
997 include_entities
=False)
999 rel
[u
['name']] = '@' + u
['screen_name']
1000 next_cursor
= m
['next_cursor']
1001 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1003 user
= ' ' + cycle_color(name
)
1004 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1010 Add specific user to a list
1012 owner
, slug
= get_slug()
1014 user_name
= raw_input(
1016 'Give me name of the newbie: ',
1018 if user_name
.startswith('@'):
1019 user_name
= user_name
[1:]
1021 t
.lists
.members
.create(
1023 owner_screen_name
=owner
,
1024 screen_name
=user_name
)
1025 printNicely(green('Added.'))
1028 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1033 Remove specific user from a list
1035 owner
, slug
= get_slug()
1037 user_name
= raw_input(
1039 'Give me name of the unlucky one: ',
1041 if user_name
.startswith('@'):
1042 user_name
= user_name
[1:]
1044 t
.lists
.members
.destroy(
1046 owner_screen_name
=owner
,
1047 screen_name
=user_name
)
1048 printNicely(green('Gone.'))
1051 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1054 def list_subscribe(t
):
1058 owner
, slug
= get_slug()
1061 t
.lists
.subscribers
.create(
1063 owner_screen_name
=owner
)
1064 printNicely(green('Done.'))
1068 light_magenta('I\'m sorry you can not subscribe to this list.'))
1071 def list_unsubscribe(t
):
1075 owner
, slug
= get_slug()
1078 t
.lists
.subscribers
.destroy(
1080 owner_screen_name
=owner
)
1081 printNicely(green('Done.'))
1085 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1094 while next_cursor
!= 0:
1095 res
= t
.lists
.ownerships(
1096 screen_name
=g
['original_name'],
1099 next_cursor
= res
['next_cursor']
1103 printNicely(light_magenta('You own no lists :)'))
1110 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1113 'New list\'s mode (public/private): ',
1115 description
= raw_input(
1117 'New list\'s description: ',
1123 description
=description
)
1124 printNicely(green(name
+ ' list is created.'))
1127 printNicely(red('Oops something is wrong with Twitter :('))
1136 'Your list that you want to update: ',
1140 'Update name (leave blank to unchange): ',
1142 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1143 description
= raw_input(light_magenta('Update description: ', rl
=True))
1147 slug
='-'.join(slug
.split()),
1148 owner_screen_name
=g
['original_name'],
1151 description
=description
)
1155 owner_screen_name
=g
['original_name'],
1157 description
=description
)
1158 printNicely(green(slug
+ ' list is updated.'))
1161 printNicely(red('Oops something is wrong with Twitter :('))
1170 'Your list that you want to delete: ',
1174 slug
='-'.join(slug
.split()),
1175 owner_screen_name
=g
['original_name'])
1176 printNicely(green(slug
+ ' list is deleted.'))
1179 printNicely(red('Oops something is wrong with Twitter :('))
1186 t
= Twitter(auth
=authen())
1187 # List all lists or base on action
1189 g
['list_action'] = g
['stuff'].split()[0]
1196 'all_mem': list_members
,
1197 'all_sub': list_subscribers
,
1200 'sub': list_subscribe
,
1201 'unsub': list_unsubscribe
,
1204 'update': list_update
,
1208 return action_ary
[g
['list_action']](t
)
1210 printNicely(red('Please try again.'))
1218 target
= g
['stuff'].split()[0]
1220 args
= parse_arguments()
1222 if g
['stuff'].split()[-1] == '-f':
1223 guide
= 'To ignore an option, just hit Enter key.'
1224 printNicely(light_magenta(guide
))
1225 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1226 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1227 args
.filter = filter(None, only
.split(','))
1228 args
.ignore
= filter(None, ignore
.split(','))
1230 printNicely(red('Sorry, wrong format.'))
1233 if target
== 'public':
1234 keyword
= g
['stuff'].split()[1]
1235 if keyword
[0] == '#':
1236 keyword
= keyword
[1:]
1238 g
['stream_stop'] = True
1239 args
.track_keywords
= keyword
1241 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1243 th
= threading
.Thread(
1251 elif target
== 'mine':
1253 g
['stream_stop'] = True
1255 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1257 th
= threading
.Thread(
1262 g
['original_name']))
1265 # Stream base on list
1266 elif target
== 'list':
1267 owner
, slug
= get_slug()
1268 # Force python 2 not redraw readline buffer
1269 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1270 printNicely(light_yellow('getting list members ...'))
1272 t
= Twitter(auth
=authen())
1275 while next_cursor
!= 0:
1276 m
= t
.lists
.members(
1278 owner_screen_name
=owner
,
1280 include_entities
=False)
1281 for u
in m
['users']:
1282 members
.append('@' + u
['screen_name'])
1283 next_cursor
= m
['next_cursor']
1284 printNicely(light_yellow('... done.'))
1285 # Build thread filter array
1286 args
.filter = members
1288 g
['stream_stop'] = True
1290 th
= threading
.Thread(
1300 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1302 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1306 printNicely(red('Sorry I can\'t understand.'))
1311 Unix's command `cal`
1314 rel
= os
.popen('cal').read().split('\n')
1317 show_calendar(month
, date
, rel
)
1322 List and change theme
1326 for theme
in g
['themes']:
1327 line
= light_magenta(theme
)
1328 if c
['THEME'] == theme
:
1329 line
= ' ' * 2 + light_yellow('* ') + line
1331 line
= ' ' * 4 + line
1337 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1338 # Redefine decorated_name
1339 g
['decorated_name'] = lambda x
: color_func(
1340 c
['DECORATED_NAME'])(
1342 printNicely(green('Theme changed.'))
1344 printNicely(red('No such theme exists.'))
1349 Browse and change config
1351 all_config
= get_all_config()
1352 g
['stuff'] = g
['stuff'].strip()
1355 for k
in all_config
:
1357 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1359 guide
= 'Detailed explanation can be found at ' + \
1360 color_func(c
['TWEET']['link'])(
1361 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1363 # Print specific config
1364 elif len(g
['stuff'].split()) == 1:
1365 if g
['stuff'] in all_config
:
1368 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1371 printNicely(red('No such config key.'))
1372 # Print specific config's default value
1373 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1374 key
= g
['stuff'].split()[0]
1376 value
= get_default_config(key
)
1377 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1381 printNicely(red('Just can not get the default.'))
1382 # Delete specific config key in config file
1383 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1384 key
= g
['stuff'].split()[0]
1387 printNicely(green('Config key is dropped.'))
1390 printNicely(red('Just can not drop the key.'))
1391 # Set specific config
1392 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1393 key
= g
['stuff'].split()[0]
1394 value
= g
['stuff'].split()[-1]
1395 if key
== 'THEME' and not validate_theme(value
):
1396 printNicely(red('Invalid theme\'s value.'))
1399 set_config(key
, value
)
1400 # Keys that needs to be apply immediately
1402 c
['THEME'] = reload_theme(value
, c
['THEME'])
1403 g
['decorated_name'] = lambda x
: color_func(
1404 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1405 elif key
== 'PREFIX':
1406 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1408 printNicely(green('Updated successfully.'))
1411 printNicely(red('Just can not set the key.'))
1413 printNicely(light_magenta('Sorry I can\'s understand.'))
1416 def help_discover():
1421 # Discover the world
1423 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1424 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1425 'You can try ' + light_green('trend US') + ' or ' + \
1426 light_green('trend JP Tokyo') + '.\n'
1427 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1428 light_green('home 7') + ' will show 7 tweets.\n'
1430 light_green('notification') + ' will show your recent notification.\n'
1431 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1432 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1433 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1434 magenta('@mdo') + '.\n'
1435 usage
+= s
* 2 + light_green('view @mdo') + \
1436 ' will show ' + magenta('@mdo') + '\'s home.\n'
1437 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1438 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1439 'Search can be performed with or without hashtag.\n'
1450 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1451 usage
+= s
* 2 + light_green('t oops ') + \
1452 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1454 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1455 light_yellow('[id=12]') + '.\n'
1457 light_green('quote 12 ') + ' will quote the tweet with ' + \
1458 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1459 'the quote will be canceled.\n'
1461 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1462 light_yellow('[id=12]') + '.\n'
1463 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1464 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1465 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1466 light_yellow('oops') + '" to tweet with ' + \
1467 light_yellow('[id=12]') + '.\n'
1469 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1470 light_yellow('[id=12]') + '.\n'
1472 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1473 light_yellow('[id=12]') + '.\n'
1475 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1476 light_yellow('[id=12]') + '.\n'
1478 light_green('del 12 ') + ' will delete tweet with ' + \
1479 light_yellow('[id=12]') + '.\n'
1480 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1481 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1482 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1483 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1487 def help_messages():
1494 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1495 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1496 light_green('inbox 7') + ' will show newest 7 messages.\n'
1497 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1498 light_yellow('[thread_id=2]') + '.\n'
1499 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1500 magenta('@dtvd88') + '.\n'
1501 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1502 light_yellow('[message_id=5]') + '.\n'
1506 def help_friends_and_followers():
1508 Friends and Followers
1511 # Follower and following
1513 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1515 light_green('ls fl') + \
1516 ' will list all followers (people who are following you).\n'
1518 light_green('ls fr') + \
1519 ' will list all friends (people who you are following).\n'
1520 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1521 magenta('@dtvd88') + '.\n'
1522 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1523 magenta('@dtvd88') + '.\n'
1524 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1525 magenta('@dtvd88') + '.\n'
1526 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1527 magenta('@dtvd88') + '.\n'
1528 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1529 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1530 magenta('@dtvd88') + '.\n'
1531 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1532 magenta('@dtvd88') + '.\n'
1533 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1534 magenta('@dtvd88') + ' as a spam account.\n'
1545 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1546 usage
+= s
* 2 + light_green('list') + \
1547 ' will show all lists you are belong to.\n'
1548 usage
+= s
* 2 + light_green('list home') + \
1549 ' will show timeline of list. You will be asked for list\'s name.\n'
1550 usage
+= s
* 2 + light_green('list all_mem') + \
1551 ' will show list\'s all members.\n'
1552 usage
+= s
* 2 + light_green('list all_sub') + \
1553 ' will show list\'s all subscribers.\n'
1554 usage
+= s
* 2 + light_green('list add') + \
1555 ' will add specific person to a list owned by you.' + \
1556 ' You will be asked for list\'s name and person\'s name.\n'
1557 usage
+= s
* 2 + light_green('list rm') + \
1558 ' will remove specific person from a list owned by you.' + \
1559 ' You will be asked for list\'s name and person\'s name.\n'
1560 usage
+= s
* 2 + light_green('list sub') + \
1561 ' will subscribe you to a specific list.\n'
1562 usage
+= s
* 2 + light_green('list unsub') + \
1563 ' will unsubscribe you from a specific list.\n'
1564 usage
+= s
* 2 + light_green('list own') + \
1565 ' will show all list owned by you.\n'
1566 usage
+= s
* 2 + light_green('list new') + \
1567 ' will create a new list.\n'
1568 usage
+= s
* 2 + light_green('list update') + \
1569 ' will update a list owned by you.\n'
1570 usage
+= s
* 2 + light_green('list del') + \
1571 ' will delete a list owned by you.\n'
1582 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1583 usage
+= s
* 2 + light_green('switch public #AKB') + \
1584 ' will switch to public stream and follow "' + \
1585 light_yellow('AKB') + '" keyword.\n'
1586 usage
+= s
* 2 + light_green('switch mine') + \
1587 ' will switch to your personal stream.\n'
1588 usage
+= s
* 2 + light_green('switch mine -f ') + \
1589 ' will prompt to enter the filter.\n'
1590 usage
+= s
* 3 + light_yellow('Only nicks') + \
1591 ' filter will decide nicks will be INCLUDE ONLY.\n'
1592 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1593 ' filter will decide nicks will be EXCLUDE.\n'
1594 usage
+= s
* 2 + light_green('switch list') + \
1595 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1604 h
, w
= os
.popen('stty size', 'r').read().split()
1607 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1608 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1609 usage
+= s
+ 'You are ' + \
1610 light_yellow('already') + ' on your personal stream.\n'
1611 usage
+= s
+ 'Any update from Twitter will show up ' + \
1612 light_yellow('immediately') + '.\n'
1613 usage
+= s
+ 'In addition, following commands are available right now:\n'
1614 # Twitter help section
1616 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1617 usage
+= s
* 2 + light_green('h discover') + \
1618 ' will show help for discover commands.\n'
1619 usage
+= s
* 2 + light_green('h tweets') + \
1620 ' will show help for tweets commands.\n'
1621 usage
+= s
* 2 + light_green('h messages') + \
1622 ' will show help for messages commands.\n'
1623 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1624 ' will show help for friends and followers commands.\n'
1625 usage
+= s
* 2 + light_green('h list') + \
1626 ' will show help for list commands.\n'
1627 usage
+= s
* 2 + light_green('h stream') + \
1628 ' will show help for stream commands.\n'
1631 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1632 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1633 'will be evaluate by Python interpreter.\n'
1634 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1635 ' for current month.\n'
1638 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1639 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1640 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1641 ' theme immediately.\n'
1642 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1644 light_green('config ASCII_ART') + ' will output current value of ' +\
1645 light_yellow('ASCII_ART') + ' config key.\n'
1647 light_green('config TREND_MAX default') + ' will output default value of ' + \
1648 light_yellow('TREND_MAX') + ' config key.\n'
1650 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1651 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1653 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1654 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1655 light_yellow('True') + '.\n'
1658 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1659 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1660 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1661 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1662 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1663 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1666 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1667 usage
+= s
+ 'Have fun and hang tight! \n'
1670 'discover': help_discover
,
1671 'tweets': help_tweets
,
1672 'messages': help_messages
,
1673 'friends_and_followers': help_friends_and_followers
,
1675 'stream': help_stream
,
1680 lambda: printNicely(red('No such command.'))
1688 Pause stream display
1691 printNicely(green('Stream is paused'))
1699 printNicely(green('Stream is running back now'))
1715 printNicely(green('See you next time :)'))
1723 Reset prefix of line
1726 if c
.get('USER_JSON_ERROR'):
1727 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1728 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1730 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1733 printNicely(str(eval(g
['cmd'])))
1784 # Handle function set
1835 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1840 Listen to user's input
1845 ['public', 'mine', 'list'], # switch
1863 ['image'], # show image
1865 ['fl', 'fr'], # list
1867 [i
for i
in g
['message_threads']], # sent
1892 [key
for key
in dict(get_all_config())], # config
1893 g
['themes'], # theme
1898 'friends_and_followers',
1908 init_interactive_shell(d
)
1915 # Only use PREFIX as a string with raw_input
1916 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1919 # Save cmd to compare with readline buffer
1920 g
['cmd'] = line
.strip()
1921 # Get short cmd to pass to handle function
1923 cmd
= line
.split()[0]
1926 # Lock the semaphore
1928 # Save cmd to global variable and call process
1929 g
['stuff'] = ' '.join(line
.split()[1:])
1930 # Process the command
1933 if cmd
in ['switch', 't', 'rt', 'rep']:
1937 # Release the semaphore lock
1943 printNicely(red('OMG something is wrong with Twitter right now.'))
1946 def reconn_notice():
1948 Notice when Hangup or Timeout
1950 guide
= light_magenta("You can use ") + \
1951 light_green("switch") + \
1952 light_magenta(" command to return to your stream.\n")
1953 guide
+= light_magenta("Type ") + \
1954 light_green("h stream") + \
1955 light_magenta(" for more details.")
1957 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1961 def stream(domain
, args
, name
='Rainbow Stream'):
1967 c
['USER_DOMAIN']: name
,
1968 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1969 c
['SITE_DOMAIN']: name
,
1972 ascii_art(art_dict
[domain
])
1973 # These arguments are optional:
1975 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1977 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1980 if args
.track_keywords
:
1981 query_args
['track'] = args
.track_keywords
1983 stream
= TwitterStream(
1988 if domain
== c
['USER_DOMAIN']:
1989 tweet_iter
= stream
.user(**query_args
)
1990 elif domain
== c
['SITE_DOMAIN']:
1991 tweet_iter
= stream
.site(**query_args
)
1993 if args
.track_keywords
:
1994 tweet_iter
= stream
.statuses
.filter(**query_args
)
1996 tweet_iter
= stream
.statuses
.sample()
1997 # Block new stream until other one exits
1998 StreamLock
.acquire()
1999 g
['stream_stop'] = False
2000 for tweet
in tweet_iter
:
2002 printNicely("-- None --")
2003 elif tweet
is Timeout
:
2004 # Because the stream check for each 0.3s
2005 # so we shouldn't output anything here
2006 if(g
['stream_stop']):
2007 StreamLock
.release()
2009 elif tweet
is HeartbeatTimeout
:
2010 printNicely("-- Heartbeat Timeout --")
2012 StreamLock
.release()
2014 elif tweet
is Hangup
:
2015 printNicely("-- Hangup --")
2017 StreamLock
.release()
2019 elif tweet
.get('text'):
2020 # Check the semaphore pause and lock (stream process only)
2028 keyword
=args
.track_keywords
,
2033 # Current readline buffer
2034 current_buffer
= readline
.get_line_buffer().strip()
2035 # There is an unexpected behaviour in MacOSX readline + Python 2:
2036 # after completely delete a word after typing it,
2037 # somehow readline buffer still contains
2038 # the 1st character of that word
2039 if current_buffer
and g
['cmd'] != current_buffer
:
2041 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2043 elif not c
['HIDE_PROMPT']:
2044 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2046 elif tweet
.get('direct_message'):
2047 # Check the semaphore pause and lock (stream process only)
2052 print_message(tweet
['direct_message'])
2053 elif tweet
.get('event'):
2054 c
['events'].append(tweet
)
2056 except TwitterHTTPError
:
2059 magenta("We have maximum connection problem with twitter'stream API right now :("))
2067 args
= parse_arguments()
2071 # Twitter API connection problem
2072 except TwitterHTTPError
:
2075 magenta("We have connection problem with twitter'stream API right now :("))
2076 printNicely(magenta("Let's try again later."))
2079 # Proxy connection problem
2080 except (socks
.ProxyConnectionError
, URLError
):
2082 magenta("There seems to be a connection problem."))
2084 magenta("You might want to check your proxy settings (host, port and type)!"))
2088 # Spawn stream thread
2089 th
= threading
.Thread(
2094 g
['original_name']))
2097 # Start listen process