15 from io
import BytesIO
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
25 from .consumer
import *
26 from .interactive
import *
27 from .c_image
import *
28 from .py3patch
import *
36 StreamLock
= threading
.Lock()
39 def parse_arguments():
43 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
47 help='Timeout for the stream (seconds).')
51 help='Search the stream for specific text.')
55 help='Filter specific screen_name.')
59 help='Ignore specific screen_name.')
64 help='Display all image on terminal.')
68 help='Use HTTP/SOCKS proxy for network connections.')
73 help='HTTP/SOCKS proxy port (Default: 8080).')
78 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
79 return parser
.parse_args()
82 def proxy_connect(args
):
84 Connect to specified proxy
87 # Setup proxy by monkeypatching the standard lib
88 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
89 socks
.set_default_proxy(
90 socks
.SOCKS5
, args
.proxy_host
,
92 elif args
.proxy_type
.lower() == "http":
93 socks
.set_default_proxy(
94 socks
.HTTP
, args
.proxy_host
,
96 elif args
.proxy_type
.lower() == "socks4":
97 socks
.set_default_proxy(
98 socks
.SOCKS4
, args
.proxy_host
,
102 magenta("Sorry, wrong proxy type specified! Aborting..."))
104 socket
.socket
= socks
.socksocket
109 Authenticate with Twitter OAuth
111 # When using rainbow stream you must authorize.
112 twitter_credential
= os
.environ
.get(
116 '')) + os
.sep
+ '.rainbow_oauth'
117 if not os
.path
.exists(twitter_credential
):
118 oauth_dance("Rainbow Stream",
122 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
130 def build_mute_dict(dict_data
=False):
134 t
= Twitter(auth
=authen())
137 screen_name_list
= []
140 while next_cursor
!= 0:
141 list = t
.mutes
.users
.list(
142 screen_name
=g
['original_name'],
145 include_entities
=False,
147 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
148 name_list
+= [u
['name'] for u
in list['users']]
149 next_cursor
= list['next_cursor']
150 # Return dict or list
152 return dict(zip(screen_name_list
, name_list
))
154 return screen_name_list
159 Save traceback when run in debug mode
162 g
['traceback'].append(traceback
.format_exc())
165 def upgrade_center():
167 Check latest and notify to upgrade
170 current
= pkg_resources
.get_distribution("rainbowstream").version
171 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
172 readme
= requests
.get(url
).text
173 latest
= readme
.split("version = \'")[1].split("\'")[0]
174 if current
!= latest
:
175 notice
= light_magenta('RainbowStream latest version is ')
176 notice
+= light_green(latest
)
177 notice
+= light_magenta(' while your current version is ')
178 notice
+= light_yellow(current
) + '\n'
179 notice
+= light_magenta('You should upgrade with ')
180 notice
+= light_green('pip install -U rainbowstream')
183 notice
= light_yellow('You are running latest version (')
184 notice
+= light_green(current
)
185 notice
+= light_yellow(')')
196 ctrl_c_handler
= lambda signum
, frame
: quit()
197 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
201 t
= Twitter(auth
=authen())
202 credential
= t
.account
.verify_credentials()
203 screen_name
= '@' + credential
['screen_name']
204 name
= credential
['name']
205 c
['original_name'] = g
['original_name'] = screen_name
[1:]
206 g
['listname'] = g
['keyword'] = ''
207 g
['PREFIX'] = u2str(emojize(format_prefix()))
208 g
['full_name'] = name
209 g
['decorated_name'] = lambda x
: color_func(
210 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
212 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
213 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
216 g
['message_threads'] = {}
219 # Debug option default = True
226 # Init tweet dict and message dict
228 c
['message_dict'] = []
230 c
['IMAGE_ON_TERM'] = args
.image_on_term
231 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
232 # Check type of ONLY_LIST and IGNORE_LIST
233 if not isinstance(c
['ONLY_LIST'], list):
234 printNicely(red('ONLY_LIST is not a valid list value.'))
236 if not isinstance(c
['IGNORE_LIST'], list):
237 printNicely(red('IGNORE_LIST is not a valid list value.'))
238 c
['IGNORE_LIST'] = []
240 c
['IGNORE_LIST'] += build_mute_dict()
247 t
= Twitter(auth
=authen())
248 # Get country and town
250 country
= g
['stuff'].split()[0]
254 town
= g
['stuff'].split()[1]
257 avail
= t
.trends
.available()
260 trends
= t
.trends
.place(_id
=1)[0]['trends']
263 for location
in avail
:
264 # Search for country and Town
266 if location
['countryCode'] == country \
267 and location
['placeType']['name'] == 'Town' \
268 and location
['name'] == town
:
269 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
271 # Search for country only
273 if location
['countryCode'] == country \
274 and location
['placeType']['name'] == 'Country':
275 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
283 t
= Twitter(auth
=authen())
284 num
= c
['HOME_TWEET_NUM']
285 if g
['stuff'].isdigit():
286 num
= int(g
['stuff'])
287 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
297 for e
in c
['events']:
301 printNicely(magenta('Nothing at this time.'))
308 t
= Twitter(auth
=authen())
309 num
= c
['HOME_TWEET_NUM']
310 if g
['stuff'].isdigit():
311 num
= int(g
['stuff'])
312 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
319 Show profile of a specific user
321 t
= Twitter(auth
=authen())
322 screen_name
= g
['stuff'].split()[0]
323 if screen_name
.startswith('@'):
326 screen_name
=screen_name
[1:],
327 include_entities
=False)
331 printNicely(red('No user.'))
333 printNicely(red('A name should begin with a \'@\''))
340 t
= Twitter(auth
=authen())
341 user
= g
['stuff'].split()[0]
344 num
= int(g
['stuff'].split()[1])
346 num
= c
['HOME_TWEET_NUM']
347 for tweet
in reversed(
348 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
352 printNicely(red('A name should begin with a \'@\''))
359 t
= Twitter(auth
=authen())
361 query
= g
['stuff'].strip()
362 type = c
['SEARCH_TYPE']
363 if type not in ['mixed', 'recent', 'popular']:
365 max_record
= c
['SEARCH_MAX_RECORD']
366 count
= min(max_record
, 100)
368 rel
= t
.search
.tweets(
375 printNicely('Newest tweets:')
376 for i
in reversed(xrange(count
)):
377 draw(t
=rel
[i
], keyword
=query
)
380 printNicely(magenta('I\'m afraid there is no result'))
387 t
= Twitter(auth
=authen())
388 t
.statuses
.update(status
=g
['stuff'])
395 t
= Twitter(auth
=authen())
397 id = int(g
['stuff'].split()[0])
399 printNicely(red('Sorry I can\'t understand.'))
401 tid
= c
['tweet_dict'][id]
402 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
410 t
= Twitter(auth
=authen())
412 id = int(g
['stuff'].split()[0])
414 printNicely(red('Sorry I can\'t understand.'))
416 tid
= c
['tweet_dict'][id]
417 tweet
= t
.statuses
.show(id=tid
)
419 formater
= format_quote(tweet
)
423 prefix
= light_magenta('Compose your ', rl
=True) + \
424 light_green('#comment: ', rl
=True)
425 comment
= raw_input(prefix
)
427 quote
= comment
.join(formater
.split('#comment'))
428 t
.statuses
.update(status
=quote
)
430 printNicely(light_magenta('No text added.'))
437 t
= Twitter(auth
=authen())
440 id = int(g
['stuff'].split()[0])
442 printNicely(red('Sorry I can\'t understand.'))
444 tid
= c
['tweet_dict'][id]
445 # Get display num if exist
447 num
= int(g
['stuff'].split()[1])
449 num
= c
['RETWEETS_SHOW_NUM']
450 # Get result and display
451 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
453 printNicely(magenta('This tweet has no retweet.'))
455 for tweet
in reversed(rt_ary
):
464 t
= Twitter(auth
=authen())
466 id = int(g
['stuff'].split()[0])
468 printNicely(red('Sorry I can\'t understand.'))
470 tid
= c
['tweet_dict'][id]
471 tweet
= t
.statuses
.show(id=tid
)
472 limit
= c
['CONVERSATION_MAX']
474 thread_ref
.append(tweet
)
475 prev_tid
= tweet
['in_reply_to_status_id']
476 while prev_tid
and limit
:
478 tweet
= t
.statuses
.show(id=prev_tid
)
479 prev_tid
= tweet
['in_reply_to_status_id']
480 thread_ref
.append(tweet
)
482 for tweet
in reversed(thread_ref
):
491 t
= Twitter(auth
=authen())
493 id = int(g
['stuff'].split()[0])
495 printNicely(red('Sorry I can\'t understand.'))
497 tid
= c
['tweet_dict'][id]
498 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
499 status
= ' '.join(g
['stuff'].split()[1:])
500 status
= '@' + user
+ ' ' + str2u(status
)
501 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
508 t
= Twitter(auth
=authen())
510 id = int(g
['stuff'].split()[0])
512 printNicely(red('Sorry I can\'t understand.'))
514 tid
= c
['tweet_dict'][id]
515 t
.favorites
.create(_id
=tid
, include_entities
=False)
516 printNicely(green('Favorited.'))
517 draw(t
.statuses
.show(id=tid
))
525 t
= Twitter(auth
=authen())
527 id = int(g
['stuff'].split()[0])
529 printNicely(red('Sorry I can\'t understand.'))
531 tid
= c
['tweet_dict'][id]
532 t
.favorites
.destroy(_id
=tid
)
533 printNicely(green('Okay it\'s unfavorited.'))
534 draw(t
.statuses
.show(id=tid
))
540 Copy url of a tweet to clipboard
542 t
= Twitter(auth
=authen())
544 id = int(g
['stuff'].split()[0])
545 tid
= c
['tweet_dict'][id]
547 printNicely(red('Tweet id is not valid.'))
549 tweet
= t
.statuses
.show(id=tid
)
550 url
= 'https://twitter.com/' + \
551 tweet
['user']['screen_name'] + '/status/' + str(tid
)
553 if platform
.system().lower() == 'darwin':
554 os
.system("echo '%s' | pbcopy" % url
)
555 printNicely(green('Copied tweet\'s url to clipboard.'))
557 printNicely('Direct link: ' + yellow(url
))
564 t
= Twitter(auth
=authen())
566 id = int(g
['stuff'].split()[0])
568 printNicely(red('Sorry I can\'t understand.'))
570 tid
= c
['tweet_dict'][id]
571 t
.statuses
.destroy(id=tid
)
572 printNicely(green('Okay it\'s gone.'))
579 t
= Twitter(auth
=authen())
581 target
= g
['stuff'].split()[0]
582 if target
!= 'image':
584 id = int(g
['stuff'].split()[1])
585 tid
= c
['tweet_dict'][id]
586 tweet
= t
.statuses
.show(id=tid
)
587 media
= tweet
['entities']['media']
589 res
= requests
.get(m
['media_url'])
590 img
= Image
.open(BytesIO(res
.content
))
594 printNicely(red('Sorry I can\'t show this image.'))
601 t
= Twitter(auth
=authen())
603 if not g
['stuff'].isdigit():
605 tid
= c
['tweet_dict'][int(g
['stuff'])]
606 tweet
= t
.statuses
.show(id=tid
)
607 link_prefix
= ('http://', 'https://')
608 link_ary
= [u
for u
in tweet
['text'].split()
609 if u
.startswith(link_prefix
)]
611 printNicely(light_magenta('No url here @.@!'))
613 for link
in link_ary
:
614 webbrowser
.open(link
)
617 printNicely(red('Sorry I can\'t open url in this tweet.'))
624 t
= Twitter(auth
=authen())
625 num
= c
['MESSAGES_DISPLAY']
626 if g
['stuff'].isdigit():
632 inbox
= inbox
+ t
.direct_messages(
635 include_entities
=False,
640 inbox
= inbox
+ t
.direct_messages(
643 include_entities
=False,
647 num
= c
['MESSAGES_DISPLAY']
648 if g
['stuff'].isdigit():
653 sent
= sent
+ t
.direct_messages
.sent(
656 include_entities
=False,
661 sent
= sent
+ t
.direct_messages
.sent(
664 include_entities
=False,
669 uniq_inbox
= list(set(
670 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
672 uniq_sent
= list(set(
673 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
675 for partner
in uniq_inbox
:
676 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
678 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
679 d
[partner
] = inbox_ary
+ sent_ary
680 for partner
in uniq_sent
:
683 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
684 g
['message_threads'] = print_threads(d
)
689 View a thread of message
692 thread_id
= int(g
['stuff'])
694 g
['message_threads'][thread_id
],
699 printNicely(red('No such thread.'))
704 Send a direct message
706 t
= Twitter(auth
=authen())
708 user
= g
['stuff'].split()[0]
709 if user
[0].startswith('@'):
710 content
= ' '.join(g
['stuff'].split()[1:])
711 t
.direct_messages
.new(
712 screen_name
=user
[1:],
715 printNicely(green('Message sent.'))
717 printNicely(red('A name should begin with a \'@\''))
720 printNicely(red('Sorry I can\'t understand.'))
727 t
= Twitter(auth
=authen())
729 id = int(g
['stuff'].split()[0])
731 printNicely(red('Sorry I can\'t understand.'))
732 mid
= c
['message_dict'][id]
733 t
.direct_messages
.destroy(id=mid
)
734 printNicely(green('Message deleted.'))
739 List friends for followers
741 t
= Twitter(auth
=authen())
744 name
= g
['stuff'].split()[1]
745 if name
.startswith('@'):
748 printNicely(red('A name should begin with a \'@\''))
749 raise Exception('Invalid name')
751 name
= g
['original_name']
752 # Get list followers or friends
754 target
= g
['stuff'].split()[0]
756 printNicely(red('Omg some syntax is wrong.'))
758 d
= {'fl': 'followers', 'fr': 'friends'}
762 while next_cursor
!= 0:
763 list = getattr(t
, d
[target
]).list(
767 include_entities
=False,
769 for u
in list['users']:
770 rel
[u
['name']] = '@' + u
['screen_name']
771 next_cursor
= list['next_cursor']
773 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
775 user
= ' ' + cycle_color(name
)
776 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
784 t
= Twitter(auth
=authen())
785 screen_name
= g
['stuff'].split()[0]
786 if screen_name
.startswith('@'):
787 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
788 printNicely(green('You are following ' + screen_name
+ ' now!'))
790 printNicely(red('A name should begin with a \'@\''))
797 t
= Twitter(auth
=authen())
798 screen_name
= g
['stuff'].split()[0]
799 if screen_name
.startswith('@'):
800 t
.friendships
.destroy(
801 screen_name
=screen_name
[1:],
802 include_entities
=False)
803 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
805 printNicely(red('A name should begin with a \'@\''))
812 t
= Twitter(auth
=authen())
814 screen_name
= g
['stuff'].split()[0]
816 printNicely(red('A name should be specified. '))
818 if screen_name
.startswith('@'):
820 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
821 if isinstance(rel
, dict):
822 printNicely(green(screen_name
+ ' is muted.'))
823 c
['IGNORE_LIST'] += [unc(screen_name
)]
824 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
826 printNicely(red(rel
))
829 printNicely(red('Something is wrong, can not mute now :('))
831 printNicely(red('A name should begin with a \'@\''))
838 t
= Twitter(auth
=authen())
840 screen_name
= g
['stuff'].split()[0]
842 printNicely(red('A name should be specified. '))
844 if screen_name
.startswith('@'):
846 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
847 if isinstance(rel
, dict):
848 printNicely(green(screen_name
+ ' is unmuted.'))
849 c
['IGNORE_LIST'].remove(screen_name
)
851 printNicely(red(rel
))
853 printNicely(red('Maybe you are not muting this person ?'))
855 printNicely(red('A name should begin with a \'@\''))
862 # Get dict of muting users
863 md
= build_mute_dict(dict_data
=True)
864 printNicely('All: ' + str(len(md
)) + ' people.')
866 user
= ' ' + cycle_color(md
[name
])
867 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
869 # Update from Twitter
870 c
['IGNORE_LIST'] = [n
for n
in md
]
877 t
= Twitter(auth
=authen())
878 screen_name
= g
['stuff'].split()[0]
879 if screen_name
.startswith('@'):
881 screen_name
=screen_name
[1:],
882 include_entities
=False,
884 printNicely(green('You blocked ' + screen_name
+ '.'))
886 printNicely(red('A name should begin with a \'@\''))
893 t
= Twitter(auth
=authen())
894 screen_name
= g
['stuff'].split()[0]
895 if screen_name
.startswith('@'):
897 screen_name
=screen_name
[1:],
898 include_entities
=False,
900 printNicely(green('Unblock ' + screen_name
+ ' success!'))
902 printNicely(red('A name should begin with a \'@\''))
907 Report a user as a spam account
909 t
= Twitter(auth
=authen())
910 screen_name
= g
['stuff'].split()[0]
911 if screen_name
.startswith('@'):
913 screen_name
=screen_name
[1:])
914 printNicely(green('You reported ' + screen_name
+ '.'))
916 printNicely(red('Sorry I can\'t understand.'))
924 list_name
= raw_input(
925 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
926 # Get list name and owner
928 owner
, slug
= list_name
.split('/')
929 if slug
.startswith('@'):
934 light_magenta('List name should follow "@owner/list_name" format.'))
935 raise Exception('Wrong list name')
942 rel
= t
.lists
.list(screen_name
=g
['original_name'])
946 printNicely(light_magenta('You belong to no lists :)'))
953 owner
, slug
= get_slug()
954 res
= t
.lists
.statuses(
956 owner_screen_name
=owner
,
958 include_entities
=False)
959 for tweet
in reversed(res
):
968 owner
, slug
= get_slug()
972 while next_cursor
!= 0:
975 owner_screen_name
=owner
,
977 include_entities
=False)
979 rel
[u
['name']] = '@' + u
['screen_name']
980 next_cursor
= m
['next_cursor']
981 printNicely('All: ' + str(len(rel
)) + ' members.')
983 user
= ' ' + cycle_color(name
)
984 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
988 def list_subscribers(t
):
992 owner
, slug
= get_slug()
996 while next_cursor
!= 0:
997 m
= t
.lists
.subscribers(
999 owner_screen_name
=owner
,
1001 include_entities
=False)
1002 for u
in m
['users']:
1003 rel
[u
['name']] = '@' + u
['screen_name']
1004 next_cursor
= m
['next_cursor']
1005 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1007 user
= ' ' + cycle_color(name
)
1008 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1014 Add specific user to a list
1016 owner
, slug
= get_slug()
1018 user_name
= raw_input(
1020 'Give me name of the newbie: ',
1022 if user_name
.startswith('@'):
1023 user_name
= user_name
[1:]
1025 t
.lists
.members
.create(
1027 owner_screen_name
=owner
,
1028 screen_name
=user_name
)
1029 printNicely(green('Added.'))
1032 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1037 Remove specific user from a list
1039 owner
, slug
= get_slug()
1041 user_name
= raw_input(
1043 'Give me name of the unlucky one: ',
1045 if user_name
.startswith('@'):
1046 user_name
= user_name
[1:]
1048 t
.lists
.members
.destroy(
1050 owner_screen_name
=owner
,
1051 screen_name
=user_name
)
1052 printNicely(green('Gone.'))
1055 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1058 def list_subscribe(t
):
1062 owner
, slug
= get_slug()
1065 t
.lists
.subscribers
.create(
1067 owner_screen_name
=owner
)
1068 printNicely(green('Done.'))
1072 light_magenta('I\'m sorry you can not subscribe to this list.'))
1075 def list_unsubscribe(t
):
1079 owner
, slug
= get_slug()
1082 t
.lists
.subscribers
.destroy(
1084 owner_screen_name
=owner
)
1085 printNicely(green('Done.'))
1089 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1098 while next_cursor
!= 0:
1099 res
= t
.lists
.ownerships(
1100 screen_name
=g
['original_name'],
1103 next_cursor
= res
['next_cursor']
1107 printNicely(light_magenta('You own no lists :)'))
1114 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1117 'New list\'s mode (public/private): ',
1119 description
= raw_input(
1121 'New list\'s description: ',
1127 description
=description
)
1128 printNicely(green(name
+ ' list is created.'))
1131 printNicely(red('Oops something is wrong with Twitter :('))
1140 'Your list that you want to update: ',
1144 'Update name (leave blank to unchange): ',
1146 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1147 description
= raw_input(light_magenta('Update description: ', rl
=True))
1151 slug
='-'.join(slug
.split()),
1152 owner_screen_name
=g
['original_name'],
1155 description
=description
)
1159 owner_screen_name
=g
['original_name'],
1161 description
=description
)
1162 printNicely(green(slug
+ ' list is updated.'))
1165 printNicely(red('Oops something is wrong with Twitter :('))
1174 'Your list that you want to delete: ',
1178 slug
='-'.join(slug
.split()),
1179 owner_screen_name
=g
['original_name'])
1180 printNicely(green(slug
+ ' list is deleted.'))
1183 printNicely(red('Oops something is wrong with Twitter :('))
1190 t
= Twitter(auth
=authen())
1191 # List all lists or base on action
1193 g
['list_action'] = g
['stuff'].split()[0]
1200 'all_mem': list_members
,
1201 'all_sub': list_subscribers
,
1204 'sub': list_subscribe
,
1205 'unsub': list_unsubscribe
,
1208 'update': list_update
,
1212 return action_ary
[g
['list_action']](t
)
1214 printNicely(red('Please try again.'))
1222 target
= g
['stuff'].split()[0]
1224 args
= parse_arguments()
1226 if g
['stuff'].split()[-1] == '-f':
1227 guide
= 'To ignore an option, just hit Enter key.'
1228 printNicely(light_magenta(guide
))
1229 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1230 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1231 args
.filter = filter(None, only
.split(','))
1232 args
.ignore
= filter(None, ignore
.split(','))
1234 printNicely(red('Sorry, wrong format.'))
1237 if target
== 'public':
1238 keyword
= g
['stuff'].split()[1]
1239 if keyword
[0] == '#':
1240 keyword
= keyword
[1:]
1242 g
['stream_stop'] = True
1243 args
.track_keywords
= keyword
1244 # Set the variable to tracked keyword
1245 # and reset the listname
1246 g
['keyword'] = keyword
1249 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
1251 th
= threading
.Thread(
1259 elif target
== 'mine':
1261 g
['stream_stop'] = True
1262 # Reset the tracked keyword and listname
1263 g
['keyword'] = g
['listname'] = ''
1265 g
['PREFIX'] = u2str(emojize(format_prefix()))
1267 th
= threading
.Thread(
1272 g
['original_name']))
1275 # Stream base on list
1276 elif target
== 'list':
1277 owner
, slug
= get_slug()
1278 # Force python 2 not redraw readline buffer
1279 listname
= '/'.join([owner
, slug
])
1280 # Set the listname variable
1281 # and reset tracked keyword
1282 g
['listname'] = listname
1284 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
1285 listname
=g
['listname']
1287 printNicely(light_yellow('getting list members ...'))
1289 t
= Twitter(auth
=authen())
1292 while next_cursor
!= 0:
1293 m
= t
.lists
.members(
1295 owner_screen_name
=owner
,
1297 include_entities
=False)
1298 for u
in m
['users']:
1299 members
.append('@' + u
['screen_name'])
1300 next_cursor
= m
['next_cursor']
1301 printNicely(light_yellow('... done.'))
1302 # Build thread filter array
1303 args
.filter = members
1305 g
['stream_stop'] = True
1307 th
= threading
.Thread(
1317 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1319 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1323 printNicely(red('Sorry I can\'t understand.'))
1328 Unix's command `cal`
1331 rel
= os
.popen('cal').read().split('\n')
1334 show_calendar(month
, date
, rel
)
1339 List and change theme
1343 for theme
in g
['themes']:
1344 line
= light_magenta(theme
)
1345 if c
['THEME'] == theme
:
1346 line
= ' ' * 2 + light_yellow('* ') + line
1348 line
= ' ' * 4 + line
1354 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1355 # Redefine decorated_name
1356 g
['decorated_name'] = lambda x
: color_func(
1357 c
['DECORATED_NAME'])(
1359 printNicely(green('Theme changed.'))
1361 printNicely(red('No such theme exists.'))
1366 Browse and change config
1368 all_config
= get_all_config()
1369 g
['stuff'] = g
['stuff'].strip()
1372 for k
in all_config
:
1374 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1376 guide
= 'Detailed explanation can be found at ' + \
1377 color_func(c
['TWEET']['link'])(
1378 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1380 # Print specific config
1381 elif len(g
['stuff'].split()) == 1:
1382 if g
['stuff'] in all_config
:
1385 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1388 printNicely(red('No such config key.'))
1389 # Print specific config's default value
1390 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1391 key
= g
['stuff'].split()[0]
1393 value
= get_default_config(key
)
1394 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1398 printNicely(red('Just can not get the default.'))
1399 # Delete specific config key in config file
1400 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1401 key
= g
['stuff'].split()[0]
1404 printNicely(green('Config key is dropped.'))
1407 printNicely(red('Just can not drop the key.'))
1408 # Set specific config
1409 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1410 key
= g
['stuff'].split()[0]
1411 value
= g
['stuff'].split()[-1]
1412 if key
== 'THEME' and not validate_theme(value
):
1413 printNicely(red('Invalid theme\'s value.'))
1416 set_config(key
, value
)
1417 # Keys that needs to be apply immediately
1419 c
['THEME'] = reload_theme(value
, c
['THEME'])
1420 g
['decorated_name'] = lambda x
: color_func(
1421 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1422 elif key
== 'PREFIX':
1423 g
['PREFIX'] = u2str(emojize(format_prefix(
1424 listname
=g
['listname'],
1425 keyword
=g
['keyword']
1428 printNicely(green('Updated successfully.'))
1431 printNicely(red('Just can not set the key.'))
1433 printNicely(light_magenta('Sorry I can\'s understand.'))
1436 def help_discover():
1441 # Discover the world
1443 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1444 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1445 'You can try ' + light_green('trend US') + ' or ' + \
1446 light_green('trend JP Tokyo') + '.\n'
1447 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1448 light_green('home 7') + ' will show 7 tweets.\n'
1450 light_green('notification') + ' will show your recent notification.\n'
1451 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1452 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1453 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1454 magenta('@mdo') + '.\n'
1455 usage
+= s
* 2 + light_green('view @mdo') + \
1456 ' will show ' + magenta('@mdo') + '\'s home.\n'
1457 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1458 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1459 'Search can be performed with or without hashtag.\n'
1470 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1471 usage
+= s
* 2 + light_green('t oops ') + \
1472 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1474 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1475 light_yellow('[id=12]') + '.\n'
1477 light_green('quote 12 ') + ' will quote the tweet with ' + \
1478 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1479 'the quote will be canceled.\n'
1481 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1482 light_yellow('[id=12]') + '.\n'
1483 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1484 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1485 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1486 light_yellow('oops') + '" to tweet with ' + \
1487 light_yellow('[id=12]') + '.\n'
1489 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1490 light_yellow('[id=12]') + '.\n'
1492 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1493 light_yellow('[id=12]') + '.\n'
1495 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1496 light_yellow('[id=12]') + '.\n'
1498 light_green('del 12 ') + ' will delete tweet with ' + \
1499 light_yellow('[id=12]') + '.\n'
1500 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1501 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1502 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1503 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1507 def help_messages():
1514 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1515 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1516 light_green('inbox 7') + ' will show newest 7 messages.\n'
1517 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1518 light_yellow('[thread_id=2]') + '.\n'
1519 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1520 magenta('@dtvd88') + '.\n'
1521 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1522 light_yellow('[message_id=5]') + '.\n'
1526 def help_friends_and_followers():
1528 Friends and Followers
1531 # Follower and following
1533 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1535 light_green('ls fl') + \
1536 ' will list all followers (people who are following you).\n'
1538 light_green('ls fr') + \
1539 ' will list all friends (people who you are following).\n'
1540 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1541 magenta('@dtvd88') + '.\n'
1542 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1543 magenta('@dtvd88') + '.\n'
1544 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1545 magenta('@dtvd88') + '.\n'
1546 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1547 magenta('@dtvd88') + '.\n'
1548 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1549 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1550 magenta('@dtvd88') + '.\n'
1551 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1552 magenta('@dtvd88') + '.\n'
1553 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1554 magenta('@dtvd88') + ' as a spam account.\n'
1565 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1566 usage
+= s
* 2 + light_green('list') + \
1567 ' will show all lists you are belong to.\n'
1568 usage
+= s
* 2 + light_green('list home') + \
1569 ' will show timeline of list. You will be asked for list\'s name.\n'
1570 usage
+= s
* 2 + light_green('list all_mem') + \
1571 ' will show list\'s all members.\n'
1572 usage
+= s
* 2 + light_green('list all_sub') + \
1573 ' will show list\'s all subscribers.\n'
1574 usage
+= s
* 2 + light_green('list add') + \
1575 ' will add specific person to a list owned by you.' + \
1576 ' You will be asked for list\'s name and person\'s name.\n'
1577 usage
+= s
* 2 + light_green('list rm') + \
1578 ' will remove specific person from a list owned by you.' + \
1579 ' You will be asked for list\'s name and person\'s name.\n'
1580 usage
+= s
* 2 + light_green('list sub') + \
1581 ' will subscribe you to a specific list.\n'
1582 usage
+= s
* 2 + light_green('list unsub') + \
1583 ' will unsubscribe you from a specific list.\n'
1584 usage
+= s
* 2 + light_green('list own') + \
1585 ' will show all list owned by you.\n'
1586 usage
+= s
* 2 + light_green('list new') + \
1587 ' will create a new list.\n'
1588 usage
+= s
* 2 + light_green('list update') + \
1589 ' will update a list owned by you.\n'
1590 usage
+= s
* 2 + light_green('list del') + \
1591 ' will delete a list owned by you.\n'
1602 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1603 usage
+= s
* 2 + light_green('switch public #AKB') + \
1604 ' will switch to public stream and follow "' + \
1605 light_yellow('AKB') + '" keyword.\n'
1606 usage
+= s
* 2 + light_green('switch mine') + \
1607 ' will switch to your personal stream.\n'
1608 usage
+= s
* 2 + light_green('switch mine -f ') + \
1609 ' will prompt to enter the filter.\n'
1610 usage
+= s
* 3 + light_yellow('Only nicks') + \
1611 ' filter will decide nicks will be INCLUDE ONLY.\n'
1612 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1613 ' filter will decide nicks will be EXCLUDE.\n'
1614 usage
+= s
* 2 + light_green('switch list') + \
1615 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1624 h
, w
= os
.popen('stty size', 'r').read().split()
1627 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1628 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1629 usage
+= s
+ 'You are ' + \
1630 light_yellow('already') + ' on your personal stream.\n'
1631 usage
+= s
+ 'Any update from Twitter will show up ' + \
1632 light_yellow('immediately') + '.\n'
1633 usage
+= s
+ 'In addition, following commands are available right now:\n'
1634 # Twitter help section
1636 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1637 usage
+= s
* 2 + light_green('h discover') + \
1638 ' will show help for discover commands.\n'
1639 usage
+= s
* 2 + light_green('h tweets') + \
1640 ' will show help for tweets commands.\n'
1641 usage
+= s
* 2 + light_green('h messages') + \
1642 ' will show help for messages commands.\n'
1643 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1644 ' will show help for friends and followers commands.\n'
1645 usage
+= s
* 2 + light_green('h list') + \
1646 ' will show help for list commands.\n'
1647 usage
+= s
* 2 + light_green('h stream') + \
1648 ' will show help for stream commands.\n'
1651 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1652 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1653 'will be evaluate by Python interpreter.\n'
1654 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1655 ' for current month.\n'
1658 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1659 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1660 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1661 ' theme immediately.\n'
1662 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1664 light_green('config ASCII_ART') + ' will output current value of ' +\
1665 light_yellow('ASCII_ART') + ' config key.\n'
1667 light_green('config TREND_MAX default') + ' will output default value of ' + \
1668 light_yellow('TREND_MAX') + ' config key.\n'
1670 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1671 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1673 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1674 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1675 light_yellow('True') + '.\n'
1678 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1679 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1680 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1681 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1682 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1683 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1684 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1687 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1688 usage
+= s
+ 'Have fun and hang tight! \n'
1691 'discover': help_discover
,
1692 'tweets': help_tweets
,
1693 'messages': help_messages
,
1694 'friends_and_followers': help_friends_and_followers
,
1696 'stream': help_stream
,
1701 lambda: printNicely(red('No such command.'))
1709 Pause stream display
1712 printNicely(green('Stream is paused'))
1720 printNicely(green('Stream is running back now'))
1736 printNicely(green('See you next time :)'))
1744 Reset prefix of line
1747 if c
.get('USER_JSON_ERROR'):
1748 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1749 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1751 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1754 printNicely(str(eval(g
['cmd'])))
1806 # Handle function set
1858 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1863 Listen to user's input
1868 ['public', 'mine', 'list'], # switch
1886 ['image'], # show image
1888 ['fl', 'fr'], # list
1890 [i
for i
in g
['message_threads']], # sent
1915 [key
for key
in dict(get_all_config())], # config
1916 g
['themes'], # theme
1921 'friends_and_followers',
1932 init_interactive_shell(d
)
1939 # Only use PREFIX as a string with raw_input
1940 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1943 # Save cmd to compare with readline buffer
1944 g
['cmd'] = line
.strip()
1945 # Get short cmd to pass to handle function
1947 cmd
= line
.split()[0]
1950 # Lock the semaphore
1952 # Save cmd to global variable and call process
1953 g
['stuff'] = ' '.join(line
.split()[1:])
1954 # Process the command
1957 if cmd
in ['switch', 't', 'rt', 'rep']:
1961 # Release the semaphore lock
1967 printNicely(red('OMG something is wrong with Twitter right now.'))
1970 def reconn_notice():
1972 Notice when Hangup or Timeout
1974 guide
= light_magenta("You can use ") + \
1975 light_green("switch") + \
1976 light_magenta(" command to return to your stream.\n")
1977 guide
+= light_magenta("Type ") + \
1978 light_green("h stream") + \
1979 light_magenta(" for more details.")
1981 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
1985 def stream(domain
, args
, name
='Rainbow Stream'):
1991 c
['USER_DOMAIN']: name
,
1992 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1993 c
['SITE_DOMAIN']: name
,
1996 ascii_art(art_dict
[domain
])
1997 # These arguments are optional:
1999 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2001 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2004 if args
.track_keywords
:
2005 query_args
['track'] = args
.track_keywords
2007 stream
= TwitterStream(
2012 if domain
== c
['USER_DOMAIN']:
2013 tweet_iter
= stream
.user(**query_args
)
2014 elif domain
== c
['SITE_DOMAIN']:
2015 tweet_iter
= stream
.site(**query_args
)
2017 if args
.track_keywords
:
2018 tweet_iter
= stream
.statuses
.filter(**query_args
)
2020 tweet_iter
= stream
.statuses
.sample()
2021 # Block new stream until other one exits
2022 StreamLock
.acquire()
2023 g
['stream_stop'] = False
2024 last_tweet_time
= time
.time()
2025 for tweet
in tweet_iter
:
2027 printNicely("-- None --")
2028 elif tweet
is Timeout
:
2029 # Because the stream check for each 0.3s
2030 # so we shouldn't output anything here
2031 if(g
['stream_stop']):
2032 StreamLock
.release()
2034 elif tweet
is HeartbeatTimeout
:
2035 printNicely("-- Heartbeat Timeout --")
2037 StreamLock
.release()
2039 elif tweet
is Hangup
:
2040 printNicely("-- Hangup --")
2042 StreamLock
.release()
2044 elif tweet
.get('text'):
2045 # Slow down the stream by STREAM_DELAY config key
2046 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2048 last_tweet_time
= time
.time()
2049 # Check the semaphore pause and lock (stream process only)
2057 keyword
=args
.track_keywords
,
2062 # Current readline buffer
2063 current_buffer
= readline
.get_line_buffer().strip()
2064 # There is an unexpected behaviour in MacOSX readline + Python 2:
2065 # after completely delete a word after typing it,
2066 # somehow readline buffer still contains
2067 # the 1st character of that word
2068 if current_buffer
and g
['cmd'] != current_buffer
:
2070 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2072 elif not c
['HIDE_PROMPT']:
2073 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2075 elif tweet
.get('direct_message'):
2076 # Check the semaphore pause and lock (stream process only)
2081 print_message(tweet
['direct_message'])
2082 elif tweet
.get('event'):
2083 c
['events'].append(tweet
)
2085 except TwitterHTTPError
as e
:
2088 magenta("We have connection problem with twitter'stream API right now :("))
2089 detail_twitter_error(e
)
2090 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2099 args
= parse_arguments()
2103 # Twitter API connection problem
2104 except TwitterHTTPError
as e
:
2107 magenta("We have connection problem with twitter'REST API right now :("))
2108 detail_twitter_error(e
)
2111 # Proxy connection problem
2112 except (socks
.ProxyConnectionError
, URLError
):
2114 magenta("There seems to be a connection problem."))
2116 magenta("You might want to check your proxy settings (host, port and type)!"))
2120 # Spawn stream thread
2121 th
= threading
.Thread(
2126 g
['original_name']))
2129 # Start listen process