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 original_tweet
= t
.statuses
.show(id=tid
)
516 text
= original_tweet
['text']
517 owner
= '@' + original_tweet
['user']['screen_name']
518 nick_ary
= ['@' + re
.sub('[\W_]', '', w
)
519 for w
in text
.split() if w
.startswith('@')] + [owner
]
520 status
= ' '.join(g
['stuff'].split()[1:])
521 status
= ' '.join(nick_ary
) + ' ' + str2u(status
)
522 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
529 t
= Twitter(auth
=authen())
531 id = int(g
['stuff'].split()[0])
533 printNicely(red('Sorry I can\'t understand.'))
535 tid
= c
['tweet_dict'][id]
536 t
.favorites
.create(_id
=tid
, include_entities
=False)
537 printNicely(green('Favorited.'))
538 draw(t
.statuses
.show(id=tid
))
546 t
= Twitter(auth
=authen())
548 id = int(g
['stuff'].split()[0])
550 printNicely(red('Sorry I can\'t understand.'))
552 tid
= c
['tweet_dict'][id]
553 t
.favorites
.destroy(_id
=tid
)
554 printNicely(green('Okay it\'s unfavorited.'))
555 draw(t
.statuses
.show(id=tid
))
561 Copy url of a tweet to clipboard
563 t
= Twitter(auth
=authen())
565 id = int(g
['stuff'].split()[0])
566 tid
= c
['tweet_dict'][id]
568 printNicely(red('Tweet id is not valid.'))
570 tweet
= t
.statuses
.show(id=tid
)
571 url
= 'https://twitter.com/' + \
572 tweet
['user']['screen_name'] + '/status/' + str(tid
)
574 if platform
.system().lower() == 'darwin':
575 os
.system("echo '%s' | pbcopy" % url
)
576 printNicely(green('Copied tweet\'s url to clipboard.'))
578 printNicely('Direct link: ' + yellow(url
))
585 t
= Twitter(auth
=authen())
587 id = int(g
['stuff'].split()[0])
589 printNicely(red('Sorry I can\'t understand.'))
591 tid
= c
['tweet_dict'][id]
592 t
.statuses
.destroy(id=tid
)
593 printNicely(green('Okay it\'s gone.'))
600 t
= Twitter(auth
=authen())
602 target
= g
['stuff'].split()[0]
603 if target
!= 'image':
605 id = int(g
['stuff'].split()[1])
606 tid
= c
['tweet_dict'][id]
607 tweet
= t
.statuses
.show(id=tid
)
608 media
= tweet
['entities']['media']
610 res
= requests
.get(m
['media_url'])
611 img
= Image
.open(BytesIO(res
.content
))
615 printNicely(red('Sorry I can\'t show this image.'))
622 t
= Twitter(auth
=authen())
624 if not g
['stuff'].isdigit():
626 tid
= c
['tweet_dict'][int(g
['stuff'])]
627 tweet
= t
.statuses
.show(id=tid
)
628 link_prefix
= ('http://', 'https://')
629 link_ary
= [u
for u
in tweet
['text'].split()
630 if u
.startswith(link_prefix
)]
632 printNicely(light_magenta('No url here @.@!'))
634 for link
in link_ary
:
635 webbrowser
.open(link
)
638 printNicely(red('Sorry I can\'t open url in this tweet.'))
645 t
= Twitter(auth
=authen())
646 num
= c
['MESSAGES_DISPLAY']
647 if g
['stuff'].isdigit():
653 inbox
= inbox
+ t
.direct_messages(
656 include_entities
=False,
661 inbox
= inbox
+ t
.direct_messages(
664 include_entities
=False,
668 num
= c
['MESSAGES_DISPLAY']
669 if g
['stuff'].isdigit():
674 sent
= sent
+ t
.direct_messages
.sent(
677 include_entities
=False,
682 sent
= sent
+ t
.direct_messages
.sent(
685 include_entities
=False,
690 uniq_inbox
= list(set(
691 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
693 uniq_sent
= list(set(
694 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
696 for partner
in uniq_inbox
:
697 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
699 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
700 d
[partner
] = inbox_ary
+ sent_ary
701 for partner
in uniq_sent
:
704 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
705 g
['message_threads'] = print_threads(d
)
710 View a thread of message
713 thread_id
= int(g
['stuff'])
715 g
['message_threads'][thread_id
],
720 printNicely(red('No such thread.'))
725 Send a direct message
727 t
= Twitter(auth
=authen())
729 user
= g
['stuff'].split()[0]
730 if user
[0].startswith('@'):
731 content
= ' '.join(g
['stuff'].split()[1:])
732 t
.direct_messages
.new(
733 screen_name
=user
[1:],
736 printNicely(green('Message sent.'))
738 printNicely(red('A name should begin with a \'@\''))
741 printNicely(red('Sorry I can\'t understand.'))
748 t
= Twitter(auth
=authen())
750 id = int(g
['stuff'].split()[0])
752 printNicely(red('Sorry I can\'t understand.'))
753 mid
= c
['message_dict'][id]
754 t
.direct_messages
.destroy(id=mid
)
755 printNicely(green('Message deleted.'))
760 List friends for followers
762 t
= Twitter(auth
=authen())
765 name
= g
['stuff'].split()[1]
766 if name
.startswith('@'):
769 printNicely(red('A name should begin with a \'@\''))
770 raise Exception('Invalid name')
772 name
= g
['original_name']
773 # Get list followers or friends
775 target
= g
['stuff'].split()[0]
777 printNicely(red('Omg some syntax is wrong.'))
779 d
= {'fl': 'followers', 'fr': 'friends'}
783 while next_cursor
!= 0:
784 list = getattr(t
, d
[target
]).list(
788 include_entities
=False,
790 for u
in list['users']:
791 rel
[u
['name']] = '@' + u
['screen_name']
792 next_cursor
= list['next_cursor']
794 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
796 user
= ' ' + cycle_color(name
)
797 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
805 t
= Twitter(auth
=authen())
806 screen_name
= g
['stuff'].split()[0]
807 if screen_name
.startswith('@'):
808 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
809 printNicely(green('You are following ' + screen_name
+ ' now!'))
811 printNicely(red('A name should begin with a \'@\''))
818 t
= Twitter(auth
=authen())
819 screen_name
= g
['stuff'].split()[0]
820 if screen_name
.startswith('@'):
821 t
.friendships
.destroy(
822 screen_name
=screen_name
[1:],
823 include_entities
=False)
824 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
826 printNicely(red('A name should begin with a \'@\''))
833 t
= Twitter(auth
=authen())
835 screen_name
= g
['stuff'].split()[0]
837 printNicely(red('A name should be specified. '))
839 if screen_name
.startswith('@'):
841 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
842 if isinstance(rel
, dict):
843 printNicely(green(screen_name
+ ' is muted.'))
844 c
['IGNORE_LIST'] += [unc(screen_name
)]
845 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
847 printNicely(red(rel
))
850 printNicely(red('Something is wrong, can not mute now :('))
852 printNicely(red('A name should begin with a \'@\''))
859 t
= Twitter(auth
=authen())
861 screen_name
= g
['stuff'].split()[0]
863 printNicely(red('A name should be specified. '))
865 if screen_name
.startswith('@'):
867 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
868 if isinstance(rel
, dict):
869 printNicely(green(screen_name
+ ' is unmuted.'))
870 c
['IGNORE_LIST'].remove(screen_name
)
872 printNicely(red(rel
))
874 printNicely(red('Maybe you are not muting this person ?'))
876 printNicely(red('A name should begin with a \'@\''))
883 # Get dict of muting users
884 md
= build_mute_dict(dict_data
=True)
885 printNicely('All: ' + str(len(md
)) + ' people.')
887 user
= ' ' + cycle_color(md
[name
])
888 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
890 # Update from Twitter
891 c
['IGNORE_LIST'] = [n
for n
in md
]
898 t
= Twitter(auth
=authen())
899 screen_name
= g
['stuff'].split()[0]
900 if screen_name
.startswith('@'):
902 screen_name
=screen_name
[1:],
903 include_entities
=False,
905 printNicely(green('You blocked ' + screen_name
+ '.'))
907 printNicely(red('A name should begin with a \'@\''))
914 t
= Twitter(auth
=authen())
915 screen_name
= g
['stuff'].split()[0]
916 if screen_name
.startswith('@'):
918 screen_name
=screen_name
[1:],
919 include_entities
=False,
921 printNicely(green('Unblock ' + screen_name
+ ' success!'))
923 printNicely(red('A name should begin with a \'@\''))
928 Report a user as a spam account
930 t
= Twitter(auth
=authen())
931 screen_name
= g
['stuff'].split()[0]
932 if screen_name
.startswith('@'):
934 screen_name
=screen_name
[1:])
935 printNicely(green('You reported ' + screen_name
+ '.'))
937 printNicely(red('Sorry I can\'t understand.'))
945 list_name
= raw_input(
946 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
947 # Get list name and owner
949 owner
, slug
= list_name
.split('/')
950 if slug
.startswith('@'):
955 light_magenta('List name should follow "@owner/list_name" format.'))
956 raise Exception('Wrong list name')
963 rel
= t
.lists
.list(screen_name
=g
['original_name'])
967 printNicely(light_magenta('You belong to no lists :)'))
974 owner
, slug
= get_slug()
975 res
= t
.lists
.statuses(
977 owner_screen_name
=owner
,
979 include_entities
=False)
980 for tweet
in reversed(res
):
989 owner
, slug
= get_slug()
993 while next_cursor
!= 0:
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
)) + ' members.')
1004 user
= ' ' + cycle_color(name
)
1005 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1009 def list_subscribers(t
):
1013 owner
, slug
= get_slug()
1017 while next_cursor
!= 0:
1018 m
= t
.lists
.subscribers(
1020 owner_screen_name
=owner
,
1022 include_entities
=False)
1023 for u
in m
['users']:
1024 rel
[u
['name']] = '@' + u
['screen_name']
1025 next_cursor
= m
['next_cursor']
1026 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
1028 user
= ' ' + cycle_color(name
)
1029 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
1035 Add specific user to a list
1037 owner
, slug
= get_slug()
1039 user_name
= raw_input(
1041 'Give me name of the newbie: ',
1043 if user_name
.startswith('@'):
1044 user_name
= user_name
[1:]
1046 t
.lists
.members
.create(
1048 owner_screen_name
=owner
,
1049 screen_name
=user_name
)
1050 printNicely(green('Added.'))
1053 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1058 Remove specific user from a list
1060 owner
, slug
= get_slug()
1062 user_name
= raw_input(
1064 'Give me name of the unlucky one: ',
1066 if user_name
.startswith('@'):
1067 user_name
= user_name
[1:]
1069 t
.lists
.members
.destroy(
1071 owner_screen_name
=owner
,
1072 screen_name
=user_name
)
1073 printNicely(green('Gone.'))
1076 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1079 def list_subscribe(t
):
1083 owner
, slug
= get_slug()
1086 t
.lists
.subscribers
.create(
1088 owner_screen_name
=owner
)
1089 printNicely(green('Done.'))
1093 light_magenta('I\'m sorry you can not subscribe to this list.'))
1096 def list_unsubscribe(t
):
1100 owner
, slug
= get_slug()
1103 t
.lists
.subscribers
.destroy(
1105 owner_screen_name
=owner
)
1106 printNicely(green('Done.'))
1110 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1119 while next_cursor
!= 0:
1120 res
= t
.lists
.ownerships(
1121 screen_name
=g
['original_name'],
1124 next_cursor
= res
['next_cursor']
1128 printNicely(light_magenta('You own no lists :)'))
1135 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1138 'New list\'s mode (public/private): ',
1140 description
= raw_input(
1142 'New list\'s description: ',
1148 description
=description
)
1149 printNicely(green(name
+ ' list is created.'))
1152 printNicely(red('Oops something is wrong with Twitter :('))
1161 'Your list that you want to update: ',
1165 'Update name (leave blank to unchange): ',
1167 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1168 description
= raw_input(light_magenta('Update description: ', rl
=True))
1172 slug
='-'.join(slug
.split()),
1173 owner_screen_name
=g
['original_name'],
1176 description
=description
)
1180 owner_screen_name
=g
['original_name'],
1182 description
=description
)
1183 printNicely(green(slug
+ ' list is updated.'))
1186 printNicely(red('Oops something is wrong with Twitter :('))
1195 'Your list that you want to delete: ',
1199 slug
='-'.join(slug
.split()),
1200 owner_screen_name
=g
['original_name'])
1201 printNicely(green(slug
+ ' list is deleted.'))
1204 printNicely(red('Oops something is wrong with Twitter :('))
1211 t
= Twitter(auth
=authen())
1212 # List all lists or base on action
1214 g
['list_action'] = g
['stuff'].split()[0]
1221 'all_mem': list_members
,
1222 'all_sub': list_subscribers
,
1225 'sub': list_subscribe
,
1226 'unsub': list_unsubscribe
,
1229 'update': list_update
,
1233 return action_ary
[g
['list_action']](t
)
1235 printNicely(red('Please try again.'))
1243 target
= g
['stuff'].split()[0]
1245 args
= parse_arguments()
1247 if g
['stuff'].split()[-1] == '-f':
1248 guide
= 'To ignore an option, just hit Enter key.'
1249 printNicely(light_magenta(guide
))
1250 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1251 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1252 args
.filter = filter(None, only
.split(','))
1253 args
.ignore
= filter(None, ignore
.split(','))
1255 printNicely(red('Sorry, wrong format.'))
1258 if target
== 'public':
1259 keyword
= g
['stuff'].split()[1]
1260 if keyword
[0] == '#':
1261 keyword
= keyword
[1:]
1263 g
['stream_stop'] = True
1264 args
.track_keywords
= keyword
1265 # Set the variable to tracked keyword
1266 # and reset the listname
1267 g
['keyword'] = keyword
1270 g
['PREFIX'] = u2str(emojize(format_prefix(keyword
=g
['keyword'])))
1272 th
= threading
.Thread(
1280 elif target
== 'mine':
1282 g
['stream_stop'] = True
1283 # Reset the tracked keyword and listname
1284 g
['keyword'] = g
['listname'] = ''
1286 g
['PREFIX'] = u2str(emojize(format_prefix()))
1288 th
= threading
.Thread(
1293 g
['original_name']))
1296 # Stream base on list
1297 elif target
== 'list':
1298 owner
, slug
= get_slug()
1299 # Force python 2 not redraw readline buffer
1300 listname
= '/'.join([owner
, slug
])
1301 # Set the listname variable
1302 # and reset tracked keyword
1303 g
['listname'] = listname
1305 g
['PREFIX'] = g
['cmd'] = u2str(emojize(format_prefix(
1306 listname
=g
['listname']
1308 printNicely(light_yellow('getting list members ...'))
1310 t
= Twitter(auth
=authen())
1313 while next_cursor
!= 0:
1314 m
= t
.lists
.members(
1316 owner_screen_name
=owner
,
1318 include_entities
=False)
1319 for u
in m
['users']:
1320 members
.append('@' + u
['screen_name'])
1321 next_cursor
= m
['next_cursor']
1322 printNicely(light_yellow('... done.'))
1323 # Build thread filter array
1324 args
.filter = members
1326 g
['stream_stop'] = True
1328 th
= threading
.Thread(
1338 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1340 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1344 printNicely(red('Sorry I can\'t understand.'))
1349 Unix's command `cal`
1352 rel
= os
.popen('cal').read().split('\n')
1355 show_calendar(month
, date
, rel
)
1360 List and change theme
1364 for theme
in g
['themes']:
1365 line
= light_magenta(theme
)
1366 if c
['THEME'] == theme
:
1367 line
= ' ' * 2 + light_yellow('* ') + line
1369 line
= ' ' * 4 + line
1375 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1376 # Redefine decorated_name
1377 g
['decorated_name'] = lambda x
: color_func(
1378 c
['DECORATED_NAME'])(
1380 printNicely(green('Theme changed.'))
1382 printNicely(red('No such theme exists.'))
1387 Browse and change config
1389 all_config
= get_all_config()
1390 g
['stuff'] = g
['stuff'].strip()
1393 for k
in all_config
:
1395 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1397 guide
= 'Detailed explanation can be found at ' + \
1398 color_func(c
['TWEET']['link'])(
1399 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1401 # Print specific config
1402 elif len(g
['stuff'].split()) == 1:
1403 if g
['stuff'] in all_config
:
1406 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1409 printNicely(red('No such config key.'))
1410 # Print specific config's default value
1411 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1412 key
= g
['stuff'].split()[0]
1414 value
= get_default_config(key
)
1415 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1419 printNicely(red('Just can not get the default.'))
1420 # Delete specific config key in config file
1421 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1422 key
= g
['stuff'].split()[0]
1425 printNicely(green('Config key is dropped.'))
1428 printNicely(red('Just can not drop the key.'))
1429 # Set specific config
1430 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1431 key
= g
['stuff'].split()[0]
1432 value
= g
['stuff'].split()[-1]
1433 if key
== 'THEME' and not validate_theme(value
):
1434 printNicely(red('Invalid theme\'s value.'))
1437 set_config(key
, value
)
1438 # Keys that needs to be apply immediately
1440 c
['THEME'] = reload_theme(value
, c
['THEME'])
1441 g
['decorated_name'] = lambda x
: color_func(
1442 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1443 elif key
== 'PREFIX':
1444 g
['PREFIX'] = u2str(emojize(format_prefix(
1445 listname
=g
['listname'],
1446 keyword
=g
['keyword']
1449 printNicely(green('Updated successfully.'))
1452 printNicely(red('Just can not set the key.'))
1454 printNicely(light_magenta('Sorry I can\'s understand.'))
1457 def help_discover():
1462 # Discover the world
1464 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1465 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1466 'You can try ' + light_green('trend US') + ' or ' + \
1467 light_green('trend JP Tokyo') + '.\n'
1468 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1469 light_green('home 7') + ' will show 7 tweets.\n'
1471 light_green('notification') + ' will show your recent notification.\n'
1472 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1473 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1474 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1475 magenta('@mdo') + '.\n'
1476 usage
+= s
* 2 + light_green('view @mdo') + \
1477 ' will show ' + magenta('@mdo') + '\'s home.\n'
1478 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1479 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1480 'Search can be performed with or without hashtag.\n'
1491 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1492 usage
+= s
* 2 + light_green('t oops ') + \
1493 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1495 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1496 light_yellow('[id=12]') + '.\n'
1498 light_green('quote 12 ') + ' will quote the tweet with ' + \
1499 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1500 'the quote will be canceled.\n'
1502 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1503 light_yellow('[id=12]') + '.\n'
1504 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1505 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1506 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1507 light_yellow('oops') + '" to the owner of the tweet with ' + \
1508 light_yellow('[id=12]') + '.\n'
1509 usage
+= s
* 2 + light_green('repall 12 oops') + ' will reply "' + \
1510 light_yellow('oops') + '" to all people in the tweet with ' + \
1511 light_yellow('[id=12]') + '.\n'
1513 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1514 light_yellow('[id=12]') + '.\n'
1516 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1517 light_yellow('[id=12]') + '.\n'
1519 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1520 light_yellow('[id=12]') + '.\n'
1522 light_green('del 12 ') + ' will delete tweet with ' + \
1523 light_yellow('[id=12]') + '.\n'
1524 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1525 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1526 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1527 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1531 def help_messages():
1538 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1539 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1540 light_green('inbox 7') + ' will show newest 7 messages.\n'
1541 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1542 light_yellow('[thread_id=2]') + '.\n'
1543 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1544 magenta('@dtvd88') + '.\n'
1545 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1546 light_yellow('[message_id=5]') + '.\n'
1550 def help_friends_and_followers():
1552 Friends and Followers
1555 # Follower and following
1557 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1559 light_green('ls fl') + \
1560 ' will list all followers (people who are following you).\n'
1562 light_green('ls fr') + \
1563 ' will list all friends (people who you are following).\n'
1564 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1565 magenta('@dtvd88') + '.\n'
1566 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1567 magenta('@dtvd88') + '.\n'
1568 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1569 magenta('@dtvd88') + '.\n'
1570 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1571 magenta('@dtvd88') + '.\n'
1572 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1573 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1574 magenta('@dtvd88') + '.\n'
1575 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1576 magenta('@dtvd88') + '.\n'
1577 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1578 magenta('@dtvd88') + ' as a spam account.\n'
1589 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1590 usage
+= s
* 2 + light_green('list') + \
1591 ' will show all lists you are belong to.\n'
1592 usage
+= s
* 2 + light_green('list home') + \
1593 ' will show timeline of list. You will be asked for list\'s name.\n'
1594 usage
+= s
* 2 + light_green('list all_mem') + \
1595 ' will show list\'s all members.\n'
1596 usage
+= s
* 2 + light_green('list all_sub') + \
1597 ' will show list\'s all subscribers.\n'
1598 usage
+= s
* 2 + light_green('list add') + \
1599 ' will add specific person to a list owned by you.' + \
1600 ' You will be asked for list\'s name and person\'s name.\n'
1601 usage
+= s
* 2 + light_green('list rm') + \
1602 ' will remove specific person from a list owned by you.' + \
1603 ' You will be asked for list\'s name and person\'s name.\n'
1604 usage
+= s
* 2 + light_green('list sub') + \
1605 ' will subscribe you to a specific list.\n'
1606 usage
+= s
* 2 + light_green('list unsub') + \
1607 ' will unsubscribe you from a specific list.\n'
1608 usage
+= s
* 2 + light_green('list own') + \
1609 ' will show all list owned by you.\n'
1610 usage
+= s
* 2 + light_green('list new') + \
1611 ' will create a new list.\n'
1612 usage
+= s
* 2 + light_green('list update') + \
1613 ' will update a list owned by you.\n'
1614 usage
+= s
* 2 + light_green('list del') + \
1615 ' will delete a list owned by you.\n'
1626 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1627 usage
+= s
* 2 + light_green('switch public #AKB') + \
1628 ' will switch to public stream and follow "' + \
1629 light_yellow('AKB') + '" keyword.\n'
1630 usage
+= s
* 2 + light_green('switch mine') + \
1631 ' will switch to your personal stream.\n'
1632 usage
+= s
* 2 + light_green('switch mine -f ') + \
1633 ' will prompt to enter the filter.\n'
1634 usage
+= s
* 3 + light_yellow('Only nicks') + \
1635 ' filter will decide nicks will be INCLUDE ONLY.\n'
1636 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1637 ' filter will decide nicks will be EXCLUDE.\n'
1638 usage
+= s
* 2 + light_green('switch list') + \
1639 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1648 h
, w
= os
.popen('stty size', 'r').read().split()
1651 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1652 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1653 usage
+= s
+ 'You are ' + \
1654 light_yellow('already') + ' on your personal stream.\n'
1655 usage
+= s
+ 'Any update from Twitter will show up ' + \
1656 light_yellow('immediately') + '.\n'
1657 usage
+= s
+ 'In addition, following commands are available right now:\n'
1658 # Twitter help section
1660 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1661 usage
+= s
* 2 + light_green('h discover') + \
1662 ' will show help for discover commands.\n'
1663 usage
+= s
* 2 + light_green('h tweets') + \
1664 ' will show help for tweets commands.\n'
1665 usage
+= s
* 2 + light_green('h messages') + \
1666 ' will show help for messages commands.\n'
1667 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1668 ' will show help for friends and followers commands.\n'
1669 usage
+= s
* 2 + light_green('h list') + \
1670 ' will show help for list commands.\n'
1671 usage
+= s
* 2 + light_green('h stream') + \
1672 ' will show help for stream commands.\n'
1675 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1676 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1677 'will be evaluate by Python interpreter.\n'
1678 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1679 ' for current month.\n'
1682 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1683 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1684 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1685 ' theme immediately.\n'
1686 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1688 light_green('config ASCII_ART') + ' will output current value of ' +\
1689 light_yellow('ASCII_ART') + ' config key.\n'
1691 light_green('config TREND_MAX default') + ' will output default value of ' + \
1692 light_yellow('TREND_MAX') + ' config key.\n'
1694 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1695 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1697 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1698 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1699 light_yellow('True') + '.\n'
1702 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1703 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1704 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1705 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1706 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1707 usage
+= s
* 2 + light_green('v') + ' will show version info.\n'
1708 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1711 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1712 usage
+= s
+ 'Have fun and hang tight! \n'
1715 'discover': help_discover
,
1716 'tweets': help_tweets
,
1717 'messages': help_messages
,
1718 'friends_and_followers': help_friends_and_followers
,
1720 'stream': help_stream
,
1725 lambda: printNicely(red('No such command.'))
1733 Pause stream display
1736 printNicely(green('Stream is paused'))
1744 printNicely(green('Stream is running back now'))
1760 printNicely(green('See you next time :)'))
1768 Reset prefix of line
1771 if c
.get('USER_JSON_ERROR'):
1772 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1773 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1775 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1778 printNicely(str(eval(g
['cmd'])))
1831 # Handle function set
1884 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1889 Listen to user's input
1894 ['public', 'mine', 'list'], # switch
1913 ['image'], # show image
1915 ['fl', 'fr'], # list
1917 [i
for i
in g
['message_threads']], # sent
1942 [key
for key
in dict(get_all_config())], # config
1943 g
['themes'], # theme
1948 'friends_and_followers',
1959 init_interactive_shell(d
)
1966 # Only use PREFIX as a string with raw_input
1967 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1970 # Save cmd to compare with readline buffer
1971 g
['cmd'] = line
.strip()
1972 # Get short cmd to pass to handle function
1974 cmd
= line
.split()[0]
1977 # Lock the semaphore
1979 # Save cmd to global variable and call process
1980 g
['stuff'] = ' '.join(line
.split()[1:])
1981 # Process the command
1984 if cmd
in ['switch', 't', 'rt', 'rep']:
1988 # Release the semaphore lock
1994 printNicely(red('OMG something is wrong with Twitter right now.'))
1997 def reconn_notice():
1999 Notice when Hangup or Timeout
2001 guide
= light_magenta('You can use ') + \
2002 light_green('switch') + \
2003 light_magenta(' command to return to your stream.\n')
2004 guide
+= light_magenta('Type ') + \
2005 light_green('h stream') + \
2006 light_magenta(' for more details.')
2008 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2012 def stream(domain
, args
, name
='Rainbow Stream'):
2018 c
['USER_DOMAIN']: name
,
2019 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
2020 c
['SITE_DOMAIN']: name
,
2023 ascii_art(art_dict
[domain
])
2024 # These arguments are optional:
2026 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
2028 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
2031 if args
.track_keywords
:
2032 query_args
['track'] = args
.track_keywords
2034 stream
= TwitterStream(
2039 if domain
== c
['USER_DOMAIN']:
2040 tweet_iter
= stream
.user(**query_args
)
2041 elif domain
== c
['SITE_DOMAIN']:
2042 tweet_iter
= stream
.site(**query_args
)
2044 if args
.track_keywords
:
2045 tweet_iter
= stream
.statuses
.filter(**query_args
)
2047 tweet_iter
= stream
.statuses
.sample()
2048 # Block new stream until other one exits
2049 StreamLock
.acquire()
2050 g
['stream_stop'] = False
2051 last_tweet_time
= time
.time()
2052 for tweet
in tweet_iter
:
2054 printNicely('-- None --')
2055 elif tweet
is Timeout
:
2056 # Because the stream check for each 0.3s
2057 # so we shouldn't output anything here
2058 if(g
['stream_stop']):
2059 StreamLock
.release()
2061 elif tweet
is HeartbeatTimeout
:
2062 printNicely('-- Heartbeat Timeout --')
2064 StreamLock
.release()
2066 elif tweet
is Hangup
:
2067 printNicely('-- Hangup --')
2069 StreamLock
.release()
2071 elif tweet
.get('text'):
2072 # Slow down the stream by STREAM_DELAY config key
2073 if time
.time() - last_tweet_time
< c
['STREAM_DELAY']:
2075 last_tweet_time
= time
.time()
2076 # Check the semaphore pause and lock (stream process only)
2084 keyword
=args
.track_keywords
,
2089 # Current readline buffer
2090 current_buffer
= readline
.get_line_buffer().strip()
2091 # There is an unexpected behaviour in MacOSX readline + Python 2:
2092 # after completely delete a word after typing it,
2093 # somehow readline buffer still contains
2094 # the 1st character of that word
2095 if current_buffer
and g
['cmd'] != current_buffer
:
2097 g
['decorated_name'](g
['PREFIX']) + current_buffer
)
2099 elif not c
['HIDE_PROMPT']:
2100 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2102 elif tweet
.get('direct_message'):
2103 # Check the semaphore pause and lock (stream process only)
2108 print_message(tweet
['direct_message'])
2109 elif tweet
.get('event'):
2110 c
['events'].append(tweet
)
2112 except TwitterHTTPError
as e
:
2115 magenta('We have connection problem with twitter stream API right now :('))
2116 detail_twitter_error(e
)
2117 sys
.stdout
.write(g
['decorated_name'](g
['PREFIX']))
2119 except (URLError
, ConnectionResetError
):
2121 magenta('There seems to be a connection problem.'))
2131 args
= parse_arguments()
2135 # Twitter API connection problem
2136 except TwitterHTTPError
as e
:
2139 magenta('We have connection problem with twitter REST API right now :('))
2140 detail_twitter_error(e
)
2143 # Proxy connection problem
2144 except (socks
.ProxyConnectionError
, URLError
):
2146 magenta('There seems to be a connection problem.'))
2148 magenta('You might want to check your proxy settings (host, port and type)!'))
2152 # Spawn stream thread
2153 th
= threading
.Thread(
2158 g
['original_name']))
2161 # Start listen process