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')
191 ctrl_c_handler
= lambda signum
, frame
: quit()
192 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
196 t
= Twitter(auth
=authen())
197 credential
= t
.account
.verify_credentials()
198 screen_name
= '@' + credential
['screen_name']
199 name
= credential
['name']
200 if not get_config('PREFIX'):
201 set_config('PREFIX', screen_name
)
202 c
['PREFIX'] = emojize(c
['PREFIX'])
203 g
['PREFIX'] = u2str(c
['PREFIX'])
204 c
['original_name'] = g
['original_name'] = screen_name
[1:]
205 g
['full_name'] = name
206 g
['decorated_name'] = lambda x
: color_func(
207 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
209 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
210 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
213 g
['message_threads'] = {}
216 # Debug option default = True
223 # Init tweet dict and message dict
225 c
['message_dict'] = []
227 c
['IMAGE_ON_TERM'] = args
.image_on_term
228 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
229 # Check type of ONLY_LIST and IGNORE_LIST
230 if not isinstance(c
['ONLY_LIST'], list):
231 printNicely(red('ONLY_LIST is not a valid list value.'))
233 if not isinstance(c
['IGNORE_LIST'], list):
234 printNicely(red('IGNORE_LIST is not a valid list value.'))
235 c
['IGNORE_LIST'] = []
237 c
['IGNORE_LIST'] += build_mute_dict()
244 t
= Twitter(auth
=authen())
245 # Get country and town
247 country
= g
['stuff'].split()[0]
251 town
= g
['stuff'].split()[1]
254 avail
= t
.trends
.available()
257 trends
= t
.trends
.place(_id
=1)[0]['trends']
260 for location
in avail
:
261 # Search for country and Town
263 if location
['countryCode'] == country \
264 and location
['placeType']['name'] == 'Town' \
265 and location
['name'] == town
:
266 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
268 # Search for country only
270 if location
['countryCode'] == country \
271 and location
['placeType']['name'] == 'Country':
272 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
280 t
= Twitter(auth
=authen())
281 num
= c
['HOME_TWEET_NUM']
282 if g
['stuff'].isdigit():
283 num
= int(g
['stuff'])
284 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
294 for e
in c
['events']:
298 printNicely(magenta('Nothing at this time.'))
305 t
= Twitter(auth
=authen())
306 num
= c
['HOME_TWEET_NUM']
307 if g
['stuff'].isdigit():
308 num
= int(g
['stuff'])
309 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
316 Show profile of a specific user
318 t
= Twitter(auth
=authen())
319 screen_name
= g
['stuff'].split()[0]
320 if screen_name
.startswith('@'):
323 screen_name
=screen_name
[1:],
324 include_entities
=False)
328 printNicely(red('No user.'))
330 printNicely(red('A name should begin with a \'@\''))
337 t
= Twitter(auth
=authen())
338 user
= g
['stuff'].split()[0]
341 num
= int(g
['stuff'].split()[1])
343 num
= c
['HOME_TWEET_NUM']
344 for tweet
in reversed(
345 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
349 printNicely(red('A name should begin with a \'@\''))
356 t
= Twitter(auth
=authen())
358 query
= g
['stuff'].strip()
359 type = c
['SEARCH_TYPE']
360 if type not in ['mixed', 'recent', 'popular']:
362 max_record
= c
['SEARCH_MAX_RECORD']
363 count
= min(max_record
, 100)
365 rel
= t
.search
.tweets(
372 printNicely('Newest tweets:')
373 for i
in reversed(xrange(count
)):
374 draw(t
=rel
[i
], keyword
=query
)
377 printNicely(magenta('I\'m afraid there is no result'))
384 t
= Twitter(auth
=authen())
385 t
.statuses
.update(status
=g
['stuff'])
392 t
= Twitter(auth
=authen())
394 id = int(g
['stuff'].split()[0])
396 printNicely(red('Sorry I can\'t understand.'))
398 tid
= c
['tweet_dict'][id]
399 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
407 t
= Twitter(auth
=authen())
409 id = int(g
['stuff'].split()[0])
411 printNicely(red('Sorry I can\'t understand.'))
413 tid
= c
['tweet_dict'][id]
414 tweet
= t
.statuses
.show(id=tid
)
416 formater
= format_quote(tweet
)
420 prefix
= light_magenta('Compose your ', rl
=True) + \
421 light_green('#comment: ', rl
=True)
422 comment
= raw_input(prefix
)
424 quote
= comment
.join(formater
.split('#comment'))
425 t
.statuses
.update(status
=quote
)
427 printNicely(light_magenta('No text added.'))
434 t
= Twitter(auth
=authen())
437 id = int(g
['stuff'].split()[0])
439 printNicely(red('Sorry I can\'t understand.'))
441 tid
= c
['tweet_dict'][id]
442 # Get display num if exist
444 num
= int(g
['stuff'].split()[1])
446 num
= c
['RETWEETS_SHOW_NUM']
447 # Get result and display
448 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
450 printNicely(magenta('This tweet has no retweet.'))
452 for tweet
in reversed(rt_ary
):
461 t
= Twitter(auth
=authen())
463 id = int(g
['stuff'].split()[0])
465 printNicely(red('Sorry I can\'t understand.'))
467 tid
= c
['tweet_dict'][id]
468 tweet
= t
.statuses
.show(id=tid
)
469 limit
= c
['CONVERSATION_MAX']
471 thread_ref
.append(tweet
)
472 prev_tid
= tweet
['in_reply_to_status_id']
473 while prev_tid
and limit
:
475 tweet
= t
.statuses
.show(id=prev_tid
)
476 prev_tid
= tweet
['in_reply_to_status_id']
477 thread_ref
.append(tweet
)
479 for tweet
in reversed(thread_ref
):
488 t
= Twitter(auth
=authen())
490 id = int(g
['stuff'].split()[0])
492 printNicely(red('Sorry I can\'t understand.'))
494 tid
= c
['tweet_dict'][id]
495 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
496 status
= ' '.join(g
['stuff'].split()[1:])
497 status
= '@' + user
+ ' ' + str2u(status
)
498 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
505 t
= Twitter(auth
=authen())
507 id = int(g
['stuff'].split()[0])
509 printNicely(red('Sorry I can\'t understand.'))
511 tid
= c
['tweet_dict'][id]
512 t
.favorites
.create(_id
=tid
, include_entities
=False)
513 printNicely(green('Favorited.'))
514 draw(t
.statuses
.show(id=tid
))
522 t
= Twitter(auth
=authen())
524 id = int(g
['stuff'].split()[0])
526 printNicely(red('Sorry I can\'t understand.'))
528 tid
= c
['tweet_dict'][id]
529 t
.favorites
.destroy(_id
=tid
)
530 printNicely(green('Okay it\'s unfavorited.'))
531 draw(t
.statuses
.show(id=tid
))
537 Copy url of a tweet to clipboard
539 t
= Twitter(auth
=authen())
541 id = int(g
['stuff'].split()[0])
542 tid
= c
['tweet_dict'][id]
544 printNicely(red('Tweet id is not valid.'))
546 tweet
= t
.statuses
.show(id=tid
)
547 url
= 'https://twitter.com/' + \
548 tweet
['user']['screen_name'] + '/status/' + str(tid
)
550 if platform
.system().lower() == 'darwin':
551 os
.system("echo '%s' | pbcopy" % url
)
552 printNicely(green('Copied tweet\'s url to clipboard.'))
554 printNicely('Direct link: ' + yellow(url
))
561 t
= Twitter(auth
=authen())
563 id = int(g
['stuff'].split()[0])
565 printNicely(red('Sorry I can\'t understand.'))
567 tid
= c
['tweet_dict'][id]
568 t
.statuses
.destroy(id=tid
)
569 printNicely(green('Okay it\'s gone.'))
576 t
= Twitter(auth
=authen())
578 target
= g
['stuff'].split()[0]
579 if target
!= 'image':
581 id = int(g
['stuff'].split()[1])
582 tid
= c
['tweet_dict'][id]
583 tweet
= t
.statuses
.show(id=tid
)
584 media
= tweet
['entities']['media']
586 res
= requests
.get(m
['media_url'])
587 img
= Image
.open(BytesIO(res
.content
))
591 printNicely(red('Sorry I can\'t show this image.'))
598 t
= Twitter(auth
=authen())
600 if not g
['stuff'].isdigit():
602 tid
= c
['tweet_dict'][int(g
['stuff'])]
603 tweet
= t
.statuses
.show(id=tid
)
604 link_prefix
= ('http://', 'https://')
605 link_ary
= [u
for u
in tweet
['text'].split()
606 if u
.startswith(link_prefix
)]
608 printNicely(light_magenta('No url here @.@!'))
610 for link
in link_ary
:
611 webbrowser
.open(link
)
614 printNicely(red('Sorry I can\'t open url in this tweet.'))
621 t
= Twitter(auth
=authen())
622 num
= c
['MESSAGES_DISPLAY']
623 if g
['stuff'].isdigit():
629 inbox
= inbox
+ t
.direct_messages(
632 include_entities
=False,
637 inbox
= inbox
+ t
.direct_messages(
640 include_entities
=False,
644 num
= c
['MESSAGES_DISPLAY']
645 if g
['stuff'].isdigit():
650 sent
= sent
+ t
.direct_messages
.sent(
653 include_entities
=False,
658 sent
= sent
+ t
.direct_messages
.sent(
661 include_entities
=False,
666 uniq_inbox
= list(set(
667 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
669 uniq_sent
= list(set(
670 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
672 for partner
in uniq_inbox
:
673 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
675 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
676 d
[partner
] = inbox_ary
+ sent_ary
677 for partner
in uniq_sent
:
680 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
681 g
['message_threads'] = print_threads(d
)
686 View a thread of message
689 thread_id
= int(g
['stuff'])
691 g
['message_threads'][thread_id
],
696 printNicely(red('No such thread.'))
701 Send a direct message
703 t
= Twitter(auth
=authen())
705 user
= g
['stuff'].split()[0]
706 if user
[0].startswith('@'):
707 content
= ' '.join(g
['stuff'].split()[1:])
708 t
.direct_messages
.new(
709 screen_name
=user
[1:],
712 printNicely(green('Message sent.'))
714 printNicely(red('A name should begin with a \'@\''))
717 printNicely(red('Sorry I can\'t understand.'))
724 t
= Twitter(auth
=authen())
726 id = int(g
['stuff'].split()[0])
728 printNicely(red('Sorry I can\'t understand.'))
729 mid
= c
['message_dict'][id]
730 t
.direct_messages
.destroy(id=mid
)
731 printNicely(green('Message deleted.'))
736 List friends for followers
738 t
= Twitter(auth
=authen())
741 name
= g
['stuff'].split()[1]
742 if name
.startswith('@'):
745 printNicely(red('A name should begin with a \'@\''))
746 raise Exception('Invalid name')
748 name
= g
['original_name']
749 # Get list followers or friends
751 target
= g
['stuff'].split()[0]
753 printNicely(red('Omg some syntax is wrong.'))
755 d
= {'fl': 'followers', 'fr': 'friends'}
759 while next_cursor
!= 0:
760 list = getattr(t
, d
[target
]).list(
764 include_entities
=False,
766 for u
in list['users']:
767 rel
[u
['name']] = '@' + u
['screen_name']
768 next_cursor
= list['next_cursor']
770 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
772 user
= ' ' + cycle_color(name
)
773 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
781 t
= Twitter(auth
=authen())
782 screen_name
= g
['stuff'].split()[0]
783 if screen_name
.startswith('@'):
784 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
785 printNicely(green('You are following ' + screen_name
+ ' now!'))
787 printNicely(red('A name should begin with a \'@\''))
794 t
= Twitter(auth
=authen())
795 screen_name
= g
['stuff'].split()[0]
796 if screen_name
.startswith('@'):
797 t
.friendships
.destroy(
798 screen_name
=screen_name
[1:],
799 include_entities
=False)
800 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
802 printNicely(red('A name should begin with a \'@\''))
809 t
= Twitter(auth
=authen())
811 screen_name
= g
['stuff'].split()[0]
813 printNicely(red('A name should be specified. '))
815 if screen_name
.startswith('@'):
817 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
818 if isinstance(rel
, dict):
819 printNicely(green(screen_name
+ ' is muted.'))
820 c
['IGNORE_LIST'] += [unc(screen_name
)]
821 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
823 printNicely(red(rel
))
826 printNicely(red('Something is wrong, can not mute now :('))
828 printNicely(red('A name should begin with a \'@\''))
835 t
= Twitter(auth
=authen())
837 screen_name
= g
['stuff'].split()[0]
839 printNicely(red('A name should be specified. '))
841 if screen_name
.startswith('@'):
843 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
844 if isinstance(rel
, dict):
845 printNicely(green(screen_name
+ ' is unmuted.'))
846 c
['IGNORE_LIST'].remove(screen_name
)
848 printNicely(red(rel
))
850 printNicely(red('Maybe you are not muting this person ?'))
852 printNicely(red('A name should begin with a \'@\''))
859 # Get dict of muting users
860 md
= build_mute_dict(dict_data
=True)
861 printNicely('All: ' + str(len(md
)) + ' people.')
863 user
= ' ' + cycle_color(md
[name
])
864 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
866 # Update from Twitter
867 c
['IGNORE_LIST'] = [n
for n
in md
]
874 t
= Twitter(auth
=authen())
875 screen_name
= g
['stuff'].split()[0]
876 if screen_name
.startswith('@'):
878 screen_name
=screen_name
[1:],
879 include_entities
=False,
881 printNicely(green('You blocked ' + screen_name
+ '.'))
883 printNicely(red('A name should begin with a \'@\''))
890 t
= Twitter(auth
=authen())
891 screen_name
= g
['stuff'].split()[0]
892 if screen_name
.startswith('@'):
894 screen_name
=screen_name
[1:],
895 include_entities
=False,
897 printNicely(green('Unblock ' + screen_name
+ ' success!'))
899 printNicely(red('A name should begin with a \'@\''))
904 Report a user as a spam account
906 t
= Twitter(auth
=authen())
907 screen_name
= g
['stuff'].split()[0]
908 if screen_name
.startswith('@'):
910 screen_name
=screen_name
[1:])
911 printNicely(green('You reported ' + screen_name
+ '.'))
913 printNicely(red('Sorry I can\'t understand.'))
921 list_name
= raw_input(
922 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
923 # Get list name and owner
925 owner
, slug
= list_name
.split('/')
926 if slug
.startswith('@'):
931 light_magenta('List name should follow "@owner/list_name" format.'))
932 raise Exception('Wrong list name')
939 rel
= t
.lists
.list(screen_name
=g
['original_name'])
943 printNicely(light_magenta('You belong to no lists :)'))
950 owner
, slug
= get_slug()
951 res
= t
.lists
.statuses(
953 owner_screen_name
=owner
,
955 include_entities
=False)
956 for tweet
in reversed(res
):
965 owner
, slug
= get_slug()
969 while next_cursor
!= 0:
972 owner_screen_name
=owner
,
974 include_entities
=False)
976 rel
[u
['name']] = '@' + u
['screen_name']
977 next_cursor
= m
['next_cursor']
978 printNicely('All: ' + str(len(rel
)) + ' members.')
980 user
= ' ' + cycle_color(name
)
981 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
985 def list_subscribers(t
):
989 owner
, slug
= get_slug()
993 while next_cursor
!= 0:
994 m
= t
.lists
.subscribers(
996 owner_screen_name
=owner
,
998 include_entities
=False)
1000 rel
[u
['name']] = '@' + u
['screen_name']
1001 next_cursor
= m
['next_cursor']
1002 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1004 user
= ' ' + cycle_color(name
)
1005 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1011 Add specific user to a list
1013 owner
, slug
= get_slug()
1015 user_name
= raw_input(
1017 'Give me name of the newbie: ',
1019 if user_name
.startswith('@'):
1020 user_name
= user_name
[1:]
1022 t
.lists
.members
.create(
1024 owner_screen_name
=owner
,
1025 screen_name
=user_name
)
1026 printNicely(green('Added.'))
1029 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1034 Remove specific user from a list
1036 owner
, slug
= get_slug()
1038 user_name
= raw_input(
1040 'Give me name of the unlucky one: ',
1042 if user_name
.startswith('@'):
1043 user_name
= user_name
[1:]
1045 t
.lists
.members
.destroy(
1047 owner_screen_name
=owner
,
1048 screen_name
=user_name
)
1049 printNicely(green('Gone.'))
1052 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1055 def list_subscribe(t
):
1059 owner
, slug
= get_slug()
1062 t
.lists
.subscribers
.create(
1064 owner_screen_name
=owner
)
1065 printNicely(green('Done.'))
1069 light_magenta('I\'m sorry you can not subscribe to this list.'))
1072 def list_unsubscribe(t
):
1076 owner
, slug
= get_slug()
1079 t
.lists
.subscribers
.destroy(
1081 owner_screen_name
=owner
)
1082 printNicely(green('Done.'))
1086 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1095 while next_cursor
!= 0:
1096 res
= t
.lists
.ownerships(
1097 screen_name
=g
['original_name'],
1100 next_cursor
= res
['next_cursor']
1104 printNicely(light_magenta('You own no lists :)'))
1111 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1114 'New list\'s mode (public/private): ',
1116 description
= raw_input(
1118 'New list\'s description: ',
1124 description
=description
)
1125 printNicely(green(name
+ ' list is created.'))
1128 printNicely(red('Oops something is wrong with Twitter :('))
1137 'Your list that you want to update: ',
1141 'Update name (leave blank to unchange): ',
1143 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1144 description
= raw_input(light_magenta('Update description: ', rl
=True))
1148 slug
='-'.join(slug
.split()),
1149 owner_screen_name
=g
['original_name'],
1152 description
=description
)
1156 owner_screen_name
=g
['original_name'],
1158 description
=description
)
1159 printNicely(green(slug
+ ' list is updated.'))
1162 printNicely(red('Oops something is wrong with Twitter :('))
1171 'Your list that you want to delete: ',
1175 slug
='-'.join(slug
.split()),
1176 owner_screen_name
=g
['original_name'])
1177 printNicely(green(slug
+ ' list is deleted.'))
1180 printNicely(red('Oops something is wrong with Twitter :('))
1187 t
= Twitter(auth
=authen())
1188 # List all lists or base on action
1190 g
['list_action'] = g
['stuff'].split()[0]
1197 'all_mem': list_members
,
1198 'all_sub': list_subscribers
,
1201 'sub': list_subscribe
,
1202 'unsub': list_unsubscribe
,
1205 'update': list_update
,
1209 return action_ary
[g
['list_action']](t
)
1211 printNicely(red('Please try again.'))
1219 target
= g
['stuff'].split()[0]
1221 args
= parse_arguments()
1223 if g
['stuff'].split()[-1] == '-f':
1224 guide
= 'To ignore an option, just hit Enter key.'
1225 printNicely(light_magenta(guide
))
1226 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1227 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1228 args
.filter = filter(None, only
.split(','))
1229 args
.ignore
= filter(None, ignore
.split(','))
1231 printNicely(red('Sorry, wrong format.'))
1234 if target
== 'public':
1235 keyword
= g
['stuff'].split()[1]
1236 if keyword
[0] == '#':
1237 keyword
= keyword
[1:]
1239 g
['stream_stop'] = True
1240 args
.track_keywords
= keyword
1242 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1244 th
= threading
.Thread(
1252 elif target
== 'mine':
1254 g
['stream_stop'] = True
1256 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1258 th
= threading
.Thread(
1263 g
['original_name']))
1266 # Stream base on list
1267 elif target
== 'list':
1268 owner
, slug
= get_slug()
1269 # Force python 2 not redraw readline buffer
1270 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1271 printNicely(light_yellow('getting list members ...'))
1273 t
= Twitter(auth
=authen())
1276 while next_cursor
!= 0:
1277 m
= t
.lists
.members(
1279 owner_screen_name
=owner
,
1281 include_entities
=False)
1282 for u
in m
['users']:
1283 members
.append('@' + u
['screen_name'])
1284 next_cursor
= m
['next_cursor']
1285 printNicely(light_yellow('... done.'))
1286 # Build thread filter array
1287 args
.filter = members
1289 g
['stream_stop'] = True
1291 th
= threading
.Thread(
1301 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1303 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1307 printNicely(red('Sorry I can\'t understand.'))
1312 Unix's command `cal`
1315 rel
= os
.popen('cal').read().split('\n')
1318 show_calendar(month
, date
, rel
)
1323 List and change theme
1327 for theme
in g
['themes']:
1328 line
= light_magenta(theme
)
1329 if c
['THEME'] == theme
:
1330 line
= ' ' * 2 + light_yellow('* ') + line
1332 line
= ' ' * 4 + line
1338 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1339 # Redefine decorated_name
1340 g
['decorated_name'] = lambda x
: color_func(
1341 c
['DECORATED_NAME'])(
1343 printNicely(green('Theme changed.'))
1345 printNicely(red('No such theme exists.'))
1350 Browse and change config
1352 all_config
= get_all_config()
1353 g
['stuff'] = g
['stuff'].strip()
1356 for k
in all_config
:
1358 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1360 guide
= 'Detailed explanation can be found at ' + \
1361 color_func(c
['TWEET']['link'])(
1362 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1364 # Print specific config
1365 elif len(g
['stuff'].split()) == 1:
1366 if g
['stuff'] in all_config
:
1369 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1372 printNicely(red('No such config key.'))
1373 # Print specific config's default value
1374 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1375 key
= g
['stuff'].split()[0]
1377 value
= get_default_config(key
)
1378 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1382 printNicely(red('Just can not get the default.'))
1383 # Delete specific config key in config file
1384 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1385 key
= g
['stuff'].split()[0]
1388 printNicely(green('Config key is dropped.'))
1391 printNicely(red('Just can not drop the key.'))
1392 # Set specific config
1393 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1394 key
= g
['stuff'].split()[0]
1395 value
= g
['stuff'].split()[-1]
1396 if key
== 'THEME' and not validate_theme(value
):
1397 printNicely(red('Invalid theme\'s value.'))
1400 set_config(key
, value
)
1401 # Keys that needs to be apply immediately
1403 c
['THEME'] = reload_theme(value
, c
['THEME'])
1404 g
['decorated_name'] = lambda x
: color_func(
1405 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1406 elif key
== 'PREFIX':
1407 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1409 printNicely(green('Updated successfully.'))
1412 printNicely(red('Just can not set the key.'))
1414 printNicely(light_magenta('Sorry I can\'s understand.'))
1417 def help_discover():
1422 # Discover the world
1424 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1425 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1426 'You can try ' + light_green('trend US') + ' or ' + \
1427 light_green('trend JP Tokyo') + '.\n'
1428 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1429 light_green('home 7') + ' will show 7 tweets.\n'
1431 light_green('notification') + ' will show your recent notification.\n'
1432 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1433 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1434 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1435 magenta('@mdo') + '.\n'
1436 usage
+= s
* 2 + light_green('view @mdo') + \
1437 ' will show ' + magenta('@mdo') + '\'s home.\n'
1438 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1439 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1440 'Search can be performed with or without hashtag.\n'
1451 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1452 usage
+= s
* 2 + light_green('t oops ') + \
1453 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1455 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1456 light_yellow('[id=12]') + '.\n'
1458 light_green('quote 12 ') + ' will quote the tweet with ' + \
1459 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1460 'the quote will be canceled.\n'
1462 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1463 light_yellow('[id=12]') + '.\n'
1464 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1465 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1466 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1467 light_yellow('oops') + '" to tweet with ' + \
1468 light_yellow('[id=12]') + '.\n'
1470 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1471 light_yellow('[id=12]') + '.\n'
1473 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1474 light_yellow('[id=12]') + '.\n'
1476 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1477 light_yellow('[id=12]') + '.\n'
1479 light_green('del 12 ') + ' will delete tweet with ' + \
1480 light_yellow('[id=12]') + '.\n'
1481 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1482 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1483 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1484 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1488 def help_messages():
1495 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1496 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1497 light_green('inbox 7') + ' will show newest 7 messages.\n'
1498 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1499 light_yellow('[thread_id=2]') + '.\n'
1500 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1501 magenta('@dtvd88') + '.\n'
1502 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1503 light_yellow('[message_id=5]') + '.\n'
1507 def help_friends_and_followers():
1509 Friends and Followers
1512 # Follower and following
1514 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1516 light_green('ls fl') + \
1517 ' will list all followers (people who are following you).\n'
1519 light_green('ls fr') + \
1520 ' will list all friends (people who you are following).\n'
1521 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1522 magenta('@dtvd88') + '.\n'
1523 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1524 magenta('@dtvd88') + '.\n'
1525 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1526 magenta('@dtvd88') + '.\n'
1527 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1528 magenta('@dtvd88') + '.\n'
1529 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1530 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1531 magenta('@dtvd88') + '.\n'
1532 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1533 magenta('@dtvd88') + '.\n'
1534 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1535 magenta('@dtvd88') + ' as a spam account.\n'
1546 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1547 usage
+= s
* 2 + light_green('list') + \
1548 ' will show all lists you are belong to.\n'
1549 usage
+= s
* 2 + light_green('list home') + \
1550 ' will show timeline of list. You will be asked for list\'s name.\n'
1551 usage
+= s
* 2 + light_green('list all_mem') + \
1552 ' will show list\'s all members.\n'
1553 usage
+= s
* 2 + light_green('list all_sub') + \
1554 ' will show list\'s all subscribers.\n'
1555 usage
+= s
* 2 + light_green('list add') + \
1556 ' will add specific person to a list owned by you.' + \
1557 ' You will be asked for list\'s name and person\'s name.\n'
1558 usage
+= s
* 2 + light_green('list rm') + \
1559 ' will remove specific person from a list owned by you.' + \
1560 ' You will be asked for list\'s name and person\'s name.\n'
1561 usage
+= s
* 2 + light_green('list sub') + \
1562 ' will subscribe you to a specific list.\n'
1563 usage
+= s
* 2 + light_green('list unsub') + \
1564 ' will unsubscribe you from a specific list.\n'
1565 usage
+= s
* 2 + light_green('list own') + \
1566 ' will show all list owned by you.\n'
1567 usage
+= s
* 2 + light_green('list new') + \
1568 ' will create a new list.\n'
1569 usage
+= s
* 2 + light_green('list update') + \
1570 ' will update a list owned by you.\n'
1571 usage
+= s
* 2 + light_green('list del') + \
1572 ' will delete a list owned by you.\n'
1583 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1584 usage
+= s
* 2 + light_green('switch public #AKB') + \
1585 ' will switch to public stream and follow "' + \
1586 light_yellow('AKB') + '" keyword.\n'
1587 usage
+= s
* 2 + light_green('switch mine') + \
1588 ' will switch to your personal stream.\n'
1589 usage
+= s
* 2 + light_green('switch mine -f ') + \
1590 ' will prompt to enter the filter.\n'
1591 usage
+= s
* 3 + light_yellow('Only nicks') + \
1592 ' filter will decide nicks will be INCLUDE ONLY.\n'
1593 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1594 ' filter will decide nicks will be EXCLUDE.\n'
1595 usage
+= s
* 2 + light_green('switch list') + \
1596 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1605 h
, w
= os
.popen('stty size', 'r').read().split()
1608 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1609 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1610 usage
+= s
+ 'You are ' + \
1611 light_yellow('already') + ' on your personal stream.\n'
1612 usage
+= s
+ 'Any update from Twitter will show up ' + \
1613 light_yellow('immediately') + '.\n'
1614 usage
+= s
+ 'In addition, following commands are available right now:\n'
1615 # Twitter help section
1617 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1618 usage
+= s
* 2 + light_green('h discover') + \
1619 ' will show help for discover commands.\n'
1620 usage
+= s
* 2 + light_green('h tweets') + \
1621 ' will show help for tweets commands.\n'
1622 usage
+= s
* 2 + light_green('h messages') + \
1623 ' will show help for messages commands.\n'
1624 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1625 ' will show help for friends and followers commands.\n'
1626 usage
+= s
* 2 + light_green('h list') + \
1627 ' will show help for list commands.\n'
1628 usage
+= s
* 2 + light_green('h stream') + \
1629 ' will show help for stream commands.\n'
1632 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1633 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1634 'will be evaluate by Python interpreter.\n'
1635 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1636 ' for current month.\n'
1639 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1640 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1641 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1642 ' theme immediately.\n'
1643 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1645 light_green('config ASCII_ART') + ' will output current value of ' +\
1646 light_yellow('ASCII_ART') + ' config key.\n'
1648 light_green('config TREND_MAX default') + ' will output default value of ' + \
1649 light_yellow('TREND_MAX') + ' config key.\n'
1651 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1652 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1654 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1655 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1656 light_yellow('True') + '.\n'
1659 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1660 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1661 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1662 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1663 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1664 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1667 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1668 usage
+= s
+ 'Have fun and hang tight! \n'
1671 'discover': help_discover
,
1672 'tweets': help_tweets
,
1673 'messages': help_messages
,
1674 'friends_and_followers': help_friends_and_followers
,
1676 'stream': help_stream
,
1681 lambda: printNicely(red('No such command.'))
1689 Pause stream display
1692 printNicely(green('Stream is paused'))
1700 printNicely(green('Stream is running back now'))
1716 printNicely(green('See you next time :)'))
1724 Reset prefix of line
1727 if c
.get('USER_JSON_ERROR'):
1728 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1729 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1731 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1734 printNicely(str(eval(g
['cmd'])))
1785 # Handle function set
1836 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1841 Listen to user's input
1846 ['public', 'mine', 'list'], # switch
1864 ['image'], # show image
1866 ['fl', 'fr'], # list
1868 [i
for i
in g
['message_threads']], # sent
1893 [key
for key
in dict(get_all_config())], # config
1894 g
['themes'], # theme
1899 'friends_and_followers',
1909 init_interactive_shell(d
)
1916 # Only use PREFIX as a string with raw_input
1917 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1920 # Save cmd to compare with readline buffer
1921 g
['cmd'] = line
.strip()
1922 # Get short cmd to pass to handle function
1924 cmd
= line
.split()[0]
1927 # Lock the semaphore
1929 # Save cmd to global variable and call process
1930 g
['stuff'] = ' '.join(line
.split()[1:])
1931 # Process the command
1934 if cmd
in ['switch', 't', 'rt', 'rep']:
1938 # Release the semaphore lock
1944 printNicely(red('OMG something is wrong with Twitter right now.'))
1947 def reconn_notice():
1949 Notice when Hangup or Timeout
1951 guide
= light_magenta("You can use ") + \
1952 light_green("switch") + \
1953 light_magenta(" command to return to your stream.\n")
1954 guide
+= light_magenta("Type ") + \
1955 light_green("h stream") + \
1956 light_magenta(" for more details.")
1958 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1962 def stream(domain
, args
, name
='Rainbow Stream'):
1968 c
['USER_DOMAIN']: name
,
1969 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1970 c
['SITE_DOMAIN']: name
,
1973 ascii_art(art_dict
[domain
])
1974 # These arguments are optional:
1976 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1978 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1981 if args
.track_keywords
:
1982 query_args
['track'] = args
.track_keywords
1984 stream
= TwitterStream(
1989 if domain
== c
['USER_DOMAIN']:
1990 tweet_iter
= stream
.user(**query_args
)
1991 elif domain
== c
['SITE_DOMAIN']:
1992 tweet_iter
= stream
.site(**query_args
)
1994 if args
.track_keywords
:
1995 tweet_iter
= stream
.statuses
.filter(**query_args
)
1997 tweet_iter
= stream
.statuses
.sample()
1998 # Block new stream until other one exits
1999 StreamLock
.acquire()
2000 g
['stream_stop'] = False
2001 last_tweet_time
= time
.time()
2002 for tweet
in tweet_iter
:
2004 printNicely("-- None --")
2005 elif tweet
is Timeout
:
2006 # Because the stream check for each 0.3s
2007 # so we shouldn't output anything here
2008 if(g
['stream_stop']):
2009 StreamLock
.release()
2011 elif tweet
is HeartbeatTimeout
:
2012 printNicely("-- Heartbeat Timeout --")
2014 StreamLock
.release()
2016 elif tweet
is Hangup
:
2017 printNicely("-- Hangup --")
2019 StreamLock
.release()
2021 elif tweet
.get('text'):
2022 # Slow down the stream by STREAM_DELAY config key
2023 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2025 last_tweet_time
= time
.time()
2026 # Check the semaphore pause and lock (stream process only)
2034 keyword
=args
.track_keywords
,
2039 # Current readline buffer
2040 current_buffer
= readline
.get_line_buffer().strip()
2041 # There is an unexpected behaviour in MacOSX readline + Python 2:
2042 # after completely delete a word after typing it,
2043 # somehow readline buffer still contains
2044 # the 1st character of that word
2045 if current_buffer
and g
['cmd'] != current_buffer
:
2047 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2049 elif not c
['HIDE_PROMPT']:
2050 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2052 elif tweet
.get('direct_message'):
2053 # Check the semaphore pause and lock (stream process only)
2058 print_message(tweet
['direct_message'])
2059 elif tweet
.get('event'):
2060 c
['events'].append(tweet
)
2062 except TwitterHTTPError
as e
:
2065 magenta("We have maximum connection problem with twitter'stream API right now :("))
2066 printTwitterErrors(e
)
2074 args
= parse_arguments()
2078 # Twitter API connection problem
2079 except TwitterHTTPError
as e
:
2082 magenta("We have connection problem with twitter'stream API right now :("))
2083 printTwitterErrors(e
)
2084 printNicely(magenta("Let's try again later."))
2087 # Proxy connection problem
2088 except (socks
.ProxyConnectionError
, URLError
):
2090 magenta("There seems to be a connection problem."))
2092 magenta("You might want to check your proxy settings (host, port and type)!"))
2096 # Spawn stream thread
2097 th
= threading
.Thread(
2102 g
['original_name']))
2105 # Start listen process