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 *
30 from .util
import printTwitterErrors
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 c
['PREFIX'] = emojize(c
['PREFIX'])
208 g
['PREFIX'] = u2str(c
['PREFIX'])
209 c
['original_name'] = g
['original_name'] = screen_name
[1:]
210 g
['full_name'] = name
211 g
['decorated_name'] = lambda x
: color_func(
212 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
214 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
215 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
218 g
['message_threads'] = {}
221 # Debug option default = True
228 # Init tweet dict and message dict
230 c
['message_dict'] = []
232 c
['IMAGE_ON_TERM'] = args
.image_on_term
233 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
234 # Check type of ONLY_LIST and IGNORE_LIST
235 if not isinstance(c
['ONLY_LIST'], list):
236 printNicely(red('ONLY_LIST is not a valid list value.'))
238 if not isinstance(c
['IGNORE_LIST'], list):
239 printNicely(red('IGNORE_LIST is not a valid list value.'))
240 c
['IGNORE_LIST'] = []
242 c
['IGNORE_LIST'] += build_mute_dict()
249 t
= Twitter(auth
=authen())
250 # Get country and town
252 country
= g
['stuff'].split()[0]
256 town
= g
['stuff'].split()[1]
259 avail
= t
.trends
.available()
262 trends
= t
.trends
.place(_id
=1)[0]['trends']
265 for location
in avail
:
266 # Search for country and Town
268 if location
['countryCode'] == country \
269 and location
['placeType']['name'] == 'Town' \
270 and location
['name'] == town
:
271 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
273 # Search for country only
275 if location
['countryCode'] == country \
276 and location
['placeType']['name'] == 'Country':
277 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
285 t
= Twitter(auth
=authen())
286 num
= c
['HOME_TWEET_NUM']
287 if g
['stuff'].isdigit():
288 num
= int(g
['stuff'])
289 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
299 for e
in c
['events']:
303 printNicely(magenta('Nothing at this time.'))
310 t
= Twitter(auth
=authen())
311 num
= c
['HOME_TWEET_NUM']
312 if g
['stuff'].isdigit():
313 num
= int(g
['stuff'])
314 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
321 Show profile of a specific user
323 t
= Twitter(auth
=authen())
324 screen_name
= g
['stuff'].split()[0]
325 if screen_name
.startswith('@'):
328 screen_name
=screen_name
[1:],
329 include_entities
=False)
333 printNicely(red('No user.'))
335 printNicely(red('A name should begin with a \'@\''))
342 t
= Twitter(auth
=authen())
343 user
= g
['stuff'].split()[0]
346 num
= int(g
['stuff'].split()[1])
348 num
= c
['HOME_TWEET_NUM']
349 for tweet
in reversed(
350 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
354 printNicely(red('A name should begin with a \'@\''))
361 t
= Twitter(auth
=authen())
363 query
= g
['stuff'].strip()
364 type = c
['SEARCH_TYPE']
365 if type not in ['mixed', 'recent', 'popular']:
367 max_record
= c
['SEARCH_MAX_RECORD']
368 count
= min(max_record
, 100)
370 rel
= t
.search
.tweets(
377 printNicely('Newest tweets:')
378 for i
in reversed(xrange(count
)):
379 draw(t
=rel
[i
], keyword
=query
)
382 printNicely(magenta('I\'m afraid there is no result'))
389 t
= Twitter(auth
=authen())
390 t
.statuses
.update(status
=g
['stuff'])
397 t
= Twitter(auth
=authen())
399 id = int(g
['stuff'].split()[0])
401 printNicely(red('Sorry I can\'t understand.'))
403 tid
= c
['tweet_dict'][id]
404 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
412 t
= Twitter(auth
=authen())
414 id = int(g
['stuff'].split()[0])
416 printNicely(red('Sorry I can\'t understand.'))
418 tid
= c
['tweet_dict'][id]
419 tweet
= t
.statuses
.show(id=tid
)
421 formater
= format_quote(tweet
)
425 prefix
= light_magenta('Compose your ', rl
=True) + \
426 light_green('#comment: ', rl
=True)
427 comment
= raw_input(prefix
)
429 quote
= comment
.join(formater
.split('#comment'))
430 t
.statuses
.update(status
=quote
)
432 printNicely(light_magenta('No text added.'))
439 t
= Twitter(auth
=authen())
442 id = int(g
['stuff'].split()[0])
444 printNicely(red('Sorry I can\'t understand.'))
446 tid
= c
['tweet_dict'][id]
447 # Get display num if exist
449 num
= int(g
['stuff'].split()[1])
451 num
= c
['RETWEETS_SHOW_NUM']
452 # Get result and display
453 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
455 printNicely(magenta('This tweet has no retweet.'))
457 for tweet
in reversed(rt_ary
):
466 t
= Twitter(auth
=authen())
468 id = int(g
['stuff'].split()[0])
470 printNicely(red('Sorry I can\'t understand.'))
472 tid
= c
['tweet_dict'][id]
473 tweet
= t
.statuses
.show(id=tid
)
474 limit
= c
['CONVERSATION_MAX']
476 thread_ref
.append(tweet
)
477 prev_tid
= tweet
['in_reply_to_status_id']
478 while prev_tid
and limit
:
480 tweet
= t
.statuses
.show(id=prev_tid
)
481 prev_tid
= tweet
['in_reply_to_status_id']
482 thread_ref
.append(tweet
)
484 for tweet
in reversed(thread_ref
):
493 t
= Twitter(auth
=authen())
495 id = int(g
['stuff'].split()[0])
497 printNicely(red('Sorry I can\'t understand.'))
499 tid
= c
['tweet_dict'][id]
500 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
501 status
= ' '.join(g
['stuff'].split()[1:])
502 status
= '@' + user
+ ' ' + str2u(status
)
503 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
510 t
= Twitter(auth
=authen())
512 id = int(g
['stuff'].split()[0])
514 printNicely(red('Sorry I can\'t understand.'))
516 tid
= c
['tweet_dict'][id]
517 t
.favorites
.create(_id
=tid
, include_entities
=False)
518 printNicely(green('Favorited.'))
519 draw(t
.statuses
.show(id=tid
))
527 t
= Twitter(auth
=authen())
529 id = int(g
['stuff'].split()[0])
531 printNicely(red('Sorry I can\'t understand.'))
533 tid
= c
['tweet_dict'][id]
534 t
.favorites
.destroy(_id
=tid
)
535 printNicely(green('Okay it\'s unfavorited.'))
536 draw(t
.statuses
.show(id=tid
))
542 Copy url of a tweet to clipboard
544 t
= Twitter(auth
=authen())
546 id = int(g
['stuff'].split()[0])
547 tid
= c
['tweet_dict'][id]
549 printNicely(red('Tweet id is not valid.'))
551 tweet
= t
.statuses
.show(id=tid
)
552 url
= 'https://twitter.com/' + \
553 tweet
['user']['screen_name'] + '/status/' + str(tid
)
555 if platform
.system().lower() == 'darwin':
556 os
.system("echo '%s' | pbcopy" % url
)
557 printNicely(green('Copied tweet\'s url to clipboard.'))
559 printNicely('Direct link: ' + yellow(url
))
566 t
= Twitter(auth
=authen())
568 id = int(g
['stuff'].split()[0])
570 printNicely(red('Sorry I can\'t understand.'))
572 tid
= c
['tweet_dict'][id]
573 t
.statuses
.destroy(id=tid
)
574 printNicely(green('Okay it\'s gone.'))
581 t
= Twitter(auth
=authen())
583 target
= g
['stuff'].split()[0]
584 if target
!= 'image':
586 id = int(g
['stuff'].split()[1])
587 tid
= c
['tweet_dict'][id]
588 tweet
= t
.statuses
.show(id=tid
)
589 media
= tweet
['entities']['media']
591 res
= requests
.get(m
['media_url'])
592 img
= Image
.open(BytesIO(res
.content
))
596 printNicely(red('Sorry I can\'t show this image.'))
603 t
= Twitter(auth
=authen())
605 if not g
['stuff'].isdigit():
607 tid
= c
['tweet_dict'][int(g
['stuff'])]
608 tweet
= t
.statuses
.show(id=tid
)
609 link_prefix
= ('http://', 'https://')
610 link_ary
= [u
for u
in tweet
['text'].split()
611 if u
.startswith(link_prefix
)]
613 printNicely(light_magenta('No url here @.@!'))
615 for link
in link_ary
:
616 webbrowser
.open(link
)
619 printNicely(red('Sorry I can\'t open url in this tweet.'))
626 t
= Twitter(auth
=authen())
627 num
= c
['MESSAGES_DISPLAY']
628 if g
['stuff'].isdigit():
634 inbox
= inbox
+ t
.direct_messages(
637 include_entities
=False,
642 inbox
= inbox
+ t
.direct_messages(
645 include_entities
=False,
649 num
= c
['MESSAGES_DISPLAY']
650 if g
['stuff'].isdigit():
655 sent
= sent
+ t
.direct_messages
.sent(
658 include_entities
=False,
663 sent
= sent
+ t
.direct_messages
.sent(
666 include_entities
=False,
671 uniq_inbox
= list(set(
672 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
674 uniq_sent
= list(set(
675 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
677 for partner
in uniq_inbox
:
678 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
680 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
681 d
[partner
] = inbox_ary
+ sent_ary
682 for partner
in uniq_sent
:
685 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
686 g
['message_threads'] = print_threads(d
)
691 View a thread of message
694 thread_id
= int(g
['stuff'])
696 g
['message_threads'][thread_id
],
701 printNicely(red('No such thread.'))
706 Send a direct message
708 t
= Twitter(auth
=authen())
710 user
= g
['stuff'].split()[0]
711 if user
[0].startswith('@'):
712 content
= ' '.join(g
['stuff'].split()[1:])
713 t
.direct_messages
.new(
714 screen_name
=user
[1:],
717 printNicely(green('Message sent.'))
719 printNicely(red('A name should begin with a \'@\''))
722 printNicely(red('Sorry I can\'t understand.'))
729 t
= Twitter(auth
=authen())
731 id = int(g
['stuff'].split()[0])
733 printNicely(red('Sorry I can\'t understand.'))
734 mid
= c
['message_dict'][id]
735 t
.direct_messages
.destroy(id=mid
)
736 printNicely(green('Message deleted.'))
741 List friends for followers
743 t
= Twitter(auth
=authen())
746 name
= g
['stuff'].split()[1]
747 if name
.startswith('@'):
750 printNicely(red('A name should begin with a \'@\''))
751 raise Exception('Invalid name')
753 name
= g
['original_name']
754 # Get list followers or friends
756 target
= g
['stuff'].split()[0]
758 printNicely(red('Omg some syntax is wrong.'))
760 d
= {'fl': 'followers', 'fr': 'friends'}
764 while next_cursor
!= 0:
765 list = getattr(t
, d
[target
]).list(
769 include_entities
=False,
771 for u
in list['users']:
772 rel
[u
['name']] = '@' + u
['screen_name']
773 next_cursor
= list['next_cursor']
775 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
777 user
= ' ' + cycle_color(name
)
778 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
786 t
= Twitter(auth
=authen())
787 screen_name
= g
['stuff'].split()[0]
788 if screen_name
.startswith('@'):
789 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
790 printNicely(green('You are following ' + screen_name
+ ' now!'))
792 printNicely(red('A name should begin with a \'@\''))
799 t
= Twitter(auth
=authen())
800 screen_name
= g
['stuff'].split()[0]
801 if screen_name
.startswith('@'):
802 t
.friendships
.destroy(
803 screen_name
=screen_name
[1:],
804 include_entities
=False)
805 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
807 printNicely(red('A name should begin with a \'@\''))
814 t
= Twitter(auth
=authen())
816 screen_name
= g
['stuff'].split()[0]
818 printNicely(red('A name should be specified. '))
820 if screen_name
.startswith('@'):
822 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
823 if isinstance(rel
, dict):
824 printNicely(green(screen_name
+ ' is muted.'))
825 c
['IGNORE_LIST'] += [unc(screen_name
)]
826 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
828 printNicely(red(rel
))
831 printNicely(red('Something is wrong, can not mute now :('))
833 printNicely(red('A name should begin with a \'@\''))
840 t
= Twitter(auth
=authen())
842 screen_name
= g
['stuff'].split()[0]
844 printNicely(red('A name should be specified. '))
846 if screen_name
.startswith('@'):
848 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
849 if isinstance(rel
, dict):
850 printNicely(green(screen_name
+ ' is unmuted.'))
851 c
['IGNORE_LIST'].remove(screen_name
)
853 printNicely(red(rel
))
855 printNicely(red('Maybe you are not muting this person ?'))
857 printNicely(red('A name should begin with a \'@\''))
864 # Get dict of muting users
865 md
= build_mute_dict(dict_data
=True)
866 printNicely('All: ' + str(len(md
)) + ' people.')
868 user
= ' ' + cycle_color(md
[name
])
869 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
871 # Update from Twitter
872 c
['IGNORE_LIST'] = [n
for n
in md
]
879 t
= Twitter(auth
=authen())
880 screen_name
= g
['stuff'].split()[0]
881 if screen_name
.startswith('@'):
883 screen_name
=screen_name
[1:],
884 include_entities
=False,
886 printNicely(green('You blocked ' + screen_name
+ '.'))
888 printNicely(red('A name should begin with a \'@\''))
895 t
= Twitter(auth
=authen())
896 screen_name
= g
['stuff'].split()[0]
897 if screen_name
.startswith('@'):
899 screen_name
=screen_name
[1:],
900 include_entities
=False,
902 printNicely(green('Unblock ' + screen_name
+ ' success!'))
904 printNicely(red('A name should begin with a \'@\''))
909 Report a user as a spam account
911 t
= Twitter(auth
=authen())
912 screen_name
= g
['stuff'].split()[0]
913 if screen_name
.startswith('@'):
915 screen_name
=screen_name
[1:])
916 printNicely(green('You reported ' + screen_name
+ '.'))
918 printNicely(red('Sorry I can\'t understand.'))
926 list_name
= raw_input(
927 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
928 # Get list name and owner
930 owner
, slug
= list_name
.split('/')
931 if slug
.startswith('@'):
936 light_magenta('List name should follow "@owner/list_name" format.'))
937 raise Exception('Wrong list name')
944 rel
= t
.lists
.list(screen_name
=g
['original_name'])
948 printNicely(light_magenta('You belong to no lists :)'))
955 owner
, slug
= get_slug()
956 res
= t
.lists
.statuses(
958 owner_screen_name
=owner
,
960 include_entities
=False)
961 for tweet
in reversed(res
):
970 owner
, slug
= get_slug()
974 while next_cursor
!= 0:
977 owner_screen_name
=owner
,
979 include_entities
=False)
981 rel
[u
['name']] = '@' + u
['screen_name']
982 next_cursor
= m
['next_cursor']
983 printNicely('All: ' + str(len(rel
)) + ' members.')
985 user
= ' ' + cycle_color(name
)
986 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
990 def list_subscribers(t
):
994 owner
, slug
= get_slug()
998 while next_cursor
!= 0:
999 m
= t
.lists
.subscribers(
1001 owner_screen_name
=owner
,
1003 include_entities
=False)
1004 for u
in m
['users']:
1005 rel
[u
['name']] = '@' + u
['screen_name']
1006 next_cursor
= m
['next_cursor']
1007 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1009 user
= ' ' + cycle_color(name
)
1010 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1016 Add specific user to a list
1018 owner
, slug
= get_slug()
1020 user_name
= raw_input(
1022 'Give me name of the newbie: ',
1024 if user_name
.startswith('@'):
1025 user_name
= user_name
[1:]
1027 t
.lists
.members
.create(
1029 owner_screen_name
=owner
,
1030 screen_name
=user_name
)
1031 printNicely(green('Added.'))
1034 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1039 Remove specific user from a list
1041 owner
, slug
= get_slug()
1043 user_name
= raw_input(
1045 'Give me name of the unlucky one: ',
1047 if user_name
.startswith('@'):
1048 user_name
= user_name
[1:]
1050 t
.lists
.members
.destroy(
1052 owner_screen_name
=owner
,
1053 screen_name
=user_name
)
1054 printNicely(green('Gone.'))
1057 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1060 def list_subscribe(t
):
1064 owner
, slug
= get_slug()
1067 t
.lists
.subscribers
.create(
1069 owner_screen_name
=owner
)
1070 printNicely(green('Done.'))
1074 light_magenta('I\'m sorry you can not subscribe to this list.'))
1077 def list_unsubscribe(t
):
1081 owner
, slug
= get_slug()
1084 t
.lists
.subscribers
.destroy(
1086 owner_screen_name
=owner
)
1087 printNicely(green('Done.'))
1091 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1100 while next_cursor
!= 0:
1101 res
= t
.lists
.ownerships(
1102 screen_name
=g
['original_name'],
1105 next_cursor
= res
['next_cursor']
1109 printNicely(light_magenta('You own no lists :)'))
1116 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1119 'New list\'s mode (public/private): ',
1121 description
= raw_input(
1123 'New list\'s description: ',
1129 description
=description
)
1130 printNicely(green(name
+ ' list is created.'))
1133 printNicely(red('Oops something is wrong with Twitter :('))
1142 'Your list that you want to update: ',
1146 'Update name (leave blank to unchange): ',
1148 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1149 description
= raw_input(light_magenta('Update description: ', rl
=True))
1153 slug
='-'.join(slug
.split()),
1154 owner_screen_name
=g
['original_name'],
1157 description
=description
)
1161 owner_screen_name
=g
['original_name'],
1163 description
=description
)
1164 printNicely(green(slug
+ ' list is updated.'))
1167 printNicely(red('Oops something is wrong with Twitter :('))
1176 'Your list that you want to delete: ',
1180 slug
='-'.join(slug
.split()),
1181 owner_screen_name
=g
['original_name'])
1182 printNicely(green(slug
+ ' list is deleted.'))
1185 printNicely(red('Oops something is wrong with Twitter :('))
1192 t
= Twitter(auth
=authen())
1193 # List all lists or base on action
1195 g
['list_action'] = g
['stuff'].split()[0]
1202 'all_mem': list_members
,
1203 'all_sub': list_subscribers
,
1206 'sub': list_subscribe
,
1207 'unsub': list_unsubscribe
,
1210 'update': list_update
,
1214 return action_ary
[g
['list_action']](t
)
1216 printNicely(red('Please try again.'))
1224 target
= g
['stuff'].split()[0]
1226 args
= parse_arguments()
1228 if g
['stuff'].split()[-1] == '-f':
1229 guide
= 'To ignore an option, just hit Enter key.'
1230 printNicely(light_magenta(guide
))
1231 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1232 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1233 args
.filter = filter(None, only
.split(','))
1234 args
.ignore
= filter(None, ignore
.split(','))
1236 printNicely(red('Sorry, wrong format.'))
1239 if target
== 'public':
1240 keyword
= g
['stuff'].split()[1]
1241 if keyword
[0] == '#':
1242 keyword
= keyword
[1:]
1244 g
['stream_stop'] = True
1245 args
.track_keywords
= keyword
1247 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1249 th
= threading
.Thread(
1257 elif target
== 'mine':
1259 g
['stream_stop'] = True
1261 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1263 th
= threading
.Thread(
1268 g
['original_name']))
1271 # Stream base on list
1272 elif target
== 'list':
1273 owner
, slug
= get_slug()
1274 # Force python 2 not redraw readline buffer
1275 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1276 printNicely(light_yellow('getting list members ...'))
1278 t
= Twitter(auth
=authen())
1281 while next_cursor
!= 0:
1282 m
= t
.lists
.members(
1284 owner_screen_name
=owner
,
1286 include_entities
=False)
1287 for u
in m
['users']:
1288 members
.append('@' + u
['screen_name'])
1289 next_cursor
= m
['next_cursor']
1290 printNicely(light_yellow('... done.'))
1291 # Build thread filter array
1292 args
.filter = members
1294 g
['stream_stop'] = True
1296 th
= threading
.Thread(
1306 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1308 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1312 printNicely(red('Sorry I can\'t understand.'))
1317 Unix's command `cal`
1320 rel
= os
.popen('cal').read().split('\n')
1323 show_calendar(month
, date
, rel
)
1328 List and change theme
1332 for theme
in g
['themes']:
1333 line
= light_magenta(theme
)
1334 if c
['THEME'] == theme
:
1335 line
= ' ' * 2 + light_yellow('* ') + line
1337 line
= ' ' * 4 + line
1343 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1344 # Redefine decorated_name
1345 g
['decorated_name'] = lambda x
: color_func(
1346 c
['DECORATED_NAME'])(
1348 printNicely(green('Theme changed.'))
1350 printNicely(red('No such theme exists.'))
1355 Browse and change config
1357 all_config
= get_all_config()
1358 g
['stuff'] = g
['stuff'].strip()
1361 for k
in all_config
:
1363 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1365 guide
= 'Detailed explanation can be found at ' + \
1366 color_func(c
['TWEET']['link'])(
1367 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1369 # Print specific config
1370 elif len(g
['stuff'].split()) == 1:
1371 if g
['stuff'] in all_config
:
1374 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1377 printNicely(red('No such config key.'))
1378 # Print specific config's default value
1379 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1380 key
= g
['stuff'].split()[0]
1382 value
= get_default_config(key
)
1383 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1387 printNicely(red('Just can not get the default.'))
1388 # Delete specific config key in config file
1389 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1390 key
= g
['stuff'].split()[0]
1393 printNicely(green('Config key is dropped.'))
1396 printNicely(red('Just can not drop the key.'))
1397 # Set specific config
1398 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1399 key
= g
['stuff'].split()[0]
1400 value
= g
['stuff'].split()[-1]
1401 if key
== 'THEME' and not validate_theme(value
):
1402 printNicely(red('Invalid theme\'s value.'))
1405 set_config(key
, value
)
1406 # Keys that needs to be apply immediately
1408 c
['THEME'] = reload_theme(value
, c
['THEME'])
1409 g
['decorated_name'] = lambda x
: color_func(
1410 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1411 elif key
== 'PREFIX':
1412 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1414 printNicely(green('Updated successfully.'))
1417 printNicely(red('Just can not set the key.'))
1419 printNicely(light_magenta('Sorry I can\'s understand.'))
1422 def help_discover():
1427 # Discover the world
1429 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1430 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1431 'You can try ' + light_green('trend US') + ' or ' + \
1432 light_green('trend JP Tokyo') + '.\n'
1433 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1434 light_green('home 7') + ' will show 7 tweets.\n'
1436 light_green('notification') + ' will show your recent notification.\n'
1437 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1438 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1439 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1440 magenta('@mdo') + '.\n'
1441 usage
+= s
* 2 + light_green('view @mdo') + \
1442 ' will show ' + magenta('@mdo') + '\'s home.\n'
1443 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1444 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1445 'Search can be performed with or without hashtag.\n'
1456 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1457 usage
+= s
* 2 + light_green('t oops ') + \
1458 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1460 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1461 light_yellow('[id=12]') + '.\n'
1463 light_green('quote 12 ') + ' will quote the tweet with ' + \
1464 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1465 'the quote will be canceled.\n'
1467 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1468 light_yellow('[id=12]') + '.\n'
1469 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1470 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1471 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1472 light_yellow('oops') + '" to tweet with ' + \
1473 light_yellow('[id=12]') + '.\n'
1475 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1476 light_yellow('[id=12]') + '.\n'
1478 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1479 light_yellow('[id=12]') + '.\n'
1481 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1482 light_yellow('[id=12]') + '.\n'
1484 light_green('del 12 ') + ' will delete tweet with ' + \
1485 light_yellow('[id=12]') + '.\n'
1486 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1487 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1488 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1489 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1493 def help_messages():
1500 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1501 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1502 light_green('inbox 7') + ' will show newest 7 messages.\n'
1503 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1504 light_yellow('[thread_id=2]') + '.\n'
1505 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1506 magenta('@dtvd88') + '.\n'
1507 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1508 light_yellow('[message_id=5]') + '.\n'
1512 def help_friends_and_followers():
1514 Friends and Followers
1517 # Follower and following
1519 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1521 light_green('ls fl') + \
1522 ' will list all followers (people who are following you).\n'
1524 light_green('ls fr') + \
1525 ' will list all friends (people who you are following).\n'
1526 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1527 magenta('@dtvd88') + '.\n'
1528 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1529 magenta('@dtvd88') + '.\n'
1530 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1531 magenta('@dtvd88') + '.\n'
1532 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1533 magenta('@dtvd88') + '.\n'
1534 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1535 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1536 magenta('@dtvd88') + '.\n'
1537 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1538 magenta('@dtvd88') + '.\n'
1539 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1540 magenta('@dtvd88') + ' as a spam account.\n'
1551 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1552 usage
+= s
* 2 + light_green('list') + \
1553 ' will show all lists you are belong to.\n'
1554 usage
+= s
* 2 + light_green('list home') + \
1555 ' will show timeline of list. You will be asked for list\'s name.\n'
1556 usage
+= s
* 2 + light_green('list all_mem') + \
1557 ' will show list\'s all members.\n'
1558 usage
+= s
* 2 + light_green('list all_sub') + \
1559 ' will show list\'s all subscribers.\n'
1560 usage
+= s
* 2 + light_green('list add') + \
1561 ' will add specific person to a list owned by you.' + \
1562 ' You will be asked for list\'s name and person\'s name.\n'
1563 usage
+= s
* 2 + light_green('list rm') + \
1564 ' will remove specific person from a list owned by you.' + \
1565 ' You will be asked for list\'s name and person\'s name.\n'
1566 usage
+= s
* 2 + light_green('list sub') + \
1567 ' will subscribe you to a specific list.\n'
1568 usage
+= s
* 2 + light_green('list unsub') + \
1569 ' will unsubscribe you from a specific list.\n'
1570 usage
+= s
* 2 + light_green('list own') + \
1571 ' will show all list owned by you.\n'
1572 usage
+= s
* 2 + light_green('list new') + \
1573 ' will create a new list.\n'
1574 usage
+= s
* 2 + light_green('list update') + \
1575 ' will update a list owned by you.\n'
1576 usage
+= s
* 2 + light_green('list del') + \
1577 ' will delete a list owned by you.\n'
1588 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1589 usage
+= s
* 2 + light_green('switch public #AKB') + \
1590 ' will switch to public stream and follow "' + \
1591 light_yellow('AKB') + '" keyword.\n'
1592 usage
+= s
* 2 + light_green('switch mine') + \
1593 ' will switch to your personal stream.\n'
1594 usage
+= s
* 2 + light_green('switch mine -f ') + \
1595 ' will prompt to enter the filter.\n'
1596 usage
+= s
* 3 + light_yellow('Only nicks') + \
1597 ' filter will decide nicks will be INCLUDE ONLY.\n'
1598 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1599 ' filter will decide nicks will be EXCLUDE.\n'
1600 usage
+= s
* 2 + light_green('switch list') + \
1601 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1610 h
, w
= os
.popen('stty size', 'r').read().split()
1613 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1614 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1615 usage
+= s
+ 'You are ' + \
1616 light_yellow('already') + ' on your personal stream.\n'
1617 usage
+= s
+ 'Any update from Twitter will show up ' + \
1618 light_yellow('immediately') + '.\n'
1619 usage
+= s
+ 'In addition, following commands are available right now:\n'
1620 # Twitter help section
1622 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1623 usage
+= s
* 2 + light_green('h discover') + \
1624 ' will show help for discover commands.\n'
1625 usage
+= s
* 2 + light_green('h tweets') + \
1626 ' will show help for tweets commands.\n'
1627 usage
+= s
* 2 + light_green('h messages') + \
1628 ' will show help for messages commands.\n'
1629 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1630 ' will show help for friends and followers commands.\n'
1631 usage
+= s
* 2 + light_green('h list') + \
1632 ' will show help for list commands.\n'
1633 usage
+= s
* 2 + light_green('h stream') + \
1634 ' will show help for stream commands.\n'
1637 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1638 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1639 'will be evaluate by Python interpreter.\n'
1640 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1641 ' for current month.\n'
1644 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1645 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1646 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1647 ' theme immediately.\n'
1648 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1650 light_green('config ASCII_ART') + ' will output current value of ' +\
1651 light_yellow('ASCII_ART') + ' config key.\n'
1653 light_green('config TREND_MAX default') + ' will output default value of ' + \
1654 light_yellow('TREND_MAX') + ' config key.\n'
1656 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1657 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1659 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1660 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1661 light_yellow('True') + '.\n'
1664 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1665 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1666 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1667 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1668 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1669 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1670 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1673 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1674 usage
+= s
+ 'Have fun and hang tight! \n'
1677 'discover': help_discover
,
1678 'tweets': help_tweets
,
1679 'messages': help_messages
,
1680 'friends_and_followers': help_friends_and_followers
,
1682 'stream': help_stream
,
1687 lambda: printNicely(red('No such command.'))
1695 Pause stream display
1698 printNicely(green('Stream is paused'))
1706 printNicely(green('Stream is running back now'))
1722 printNicely(green('See you next time :)'))
1730 Reset prefix of line
1733 if c
.get('USER_JSON_ERROR'):
1734 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1735 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1737 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1740 printNicely(str(eval(g
['cmd'])))
1792 # Handle function set
1844 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1849 Listen to user's input
1854 ['public', 'mine', 'list'], # switch
1872 ['image'], # show image
1874 ['fl', 'fr'], # list
1876 [i
for i
in g
['message_threads']], # sent
1901 [key
for key
in dict(get_all_config())], # config
1902 g
['themes'], # theme
1907 'friends_and_followers',
1918 init_interactive_shell(d
)
1925 # Only use PREFIX as a string with raw_input
1926 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1929 # Save cmd to compare with readline buffer
1930 g
['cmd'] = line
.strip()
1931 # Get short cmd to pass to handle function
1933 cmd
= line
.split()[0]
1936 # Lock the semaphore
1938 # Save cmd to global variable and call process
1939 g
['stuff'] = ' '.join(line
.split()[1:])
1940 # Process the command
1943 if cmd
in ['switch', 't', 'rt', 'rep']:
1947 # Release the semaphore lock
1953 printNicely(red('OMG something is wrong with Twitter right now.'))
1956 def reconn_notice():
1958 Notice when Hangup or Timeout
1960 guide
= light_magenta("You can use ") + \
1961 light_green("switch") + \
1962 light_magenta(" command to return to your stream.\n")
1963 guide
+= light_magenta("Type ") + \
1964 light_green("h stream") + \
1965 light_magenta(" for more details.")
1967 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1971 def stream(domain
, args
, name
='Rainbow Stream'):
1977 c
['USER_DOMAIN']: name
,
1978 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1979 c
['SITE_DOMAIN']: name
,
1982 ascii_art(art_dict
[domain
])
1983 # These arguments are optional:
1985 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1987 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1990 if args
.track_keywords
:
1991 query_args
['track'] = args
.track_keywords
1993 stream
= TwitterStream(
1998 if domain
== c
['USER_DOMAIN']:
1999 tweet_iter
= stream
.user(**query_args
)
2000 elif domain
== c
['SITE_DOMAIN']:
2001 tweet_iter
= stream
.site(**query_args
)
2003 if args
.track_keywords
:
2004 tweet_iter
= stream
.statuses
.filter(**query_args
)
2006 tweet_iter
= stream
.statuses
.sample()
2007 # Block new stream until other one exits
2008 StreamLock
.acquire()
2009 g
['stream_stop'] = False
2010 last_tweet_time
= time
.time()
2011 for tweet
in tweet_iter
:
2013 printNicely("-- None --")
2014 elif tweet
is Timeout
:
2015 # Because the stream check for each 0.3s
2016 # so we shouldn't output anything here
2017 if(g
['stream_stop']):
2018 StreamLock
.release()
2020 elif tweet
is HeartbeatTimeout
:
2021 printNicely("-- Heartbeat Timeout --")
2023 StreamLock
.release()
2025 elif tweet
is Hangup
:
2026 printNicely("-- Hangup --")
2028 StreamLock
.release()
2030 elif tweet
.get('text'):
2031 # Slow down the stream by STREAM_DELAY config key
2032 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2034 last_tweet_time
= time
.time()
2035 # Check the semaphore pause and lock (stream process only)
2043 keyword
=args
.track_keywords
,
2048 # Current readline buffer
2049 current_buffer
= readline
.get_line_buffer().strip()
2050 # There is an unexpected behaviour in MacOSX readline + Python 2:
2051 # after completely delete a word after typing it,
2052 # somehow readline buffer still contains
2053 # the 1st character of that word
2054 if current_buffer
and g
['cmd'] != current_buffer
:
2056 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2058 elif not c
['HIDE_PROMPT']:
2059 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2061 elif tweet
.get('direct_message'):
2062 # Check the semaphore pause and lock (stream process only)
2067 print_message(tweet
['direct_message'])
2068 elif tweet
.get('event'):
2069 c
['events'].append(tweet
)
2071 except TwitterHTTPError
as e
:
2074 magenta("We have maximum connection problem with twitter'stream API right now :("))
2075 printTwitterErrors(e
)
2083 args
= parse_arguments()
2087 # Twitter API connection problem
2088 except TwitterHTTPError
as e
:
2091 magenta("We have connection problem with twitter'stream API right now :("))
2092 printTwitterErrors(e
)
2093 printNicely(magenta("Let's try again later."))
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