15 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
16 from twitter
.api
import *
17 from twitter
.oauth
import OAuth
, read_token_file
18 from twitter
.oauth_dance
import oauth_dance
19 from twitter
.util
import printNicely
21 from urllib
import error
26 from .consumer
import *
27 from .interactive
import *
28 from .c_image
import *
29 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()
84 Authenticate with Twitter OAuth
86 # When using rainbow stream you must authorize.
87 twitter_credential
= os
.environ
.get(
91 '')) + os
.sep
+ '.rainbow_oauth'
92 if not os
.path
.exists(twitter_credential
):
93 oauth_dance("Rainbow Stream",
97 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
105 def build_mute_dict(dict_data
=False):
109 t
= Twitter(auth
=authen())
112 screen_name_list
= []
115 while next_cursor
!= 0:
116 list = t
.mutes
.users
.list(
117 screen_name
=g
['original_name'],
120 include_entities
=False,
122 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
123 name_list
+= [u
['name'] for u
in list['users']]
124 next_cursor
= list['next_cursor']
125 # Return dict or list
127 return dict(zip(screen_name_list
, name_list
))
129 return screen_name_list
134 Save traceback when run in debug mode
137 g
['traceback'].append(traceback
.format_exc())
140 def upgrade_center():
142 Check latest and notify to upgrade
145 current
= pkg_resources
.get_distribution("rainbowstream").version
146 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
147 readme
= requests
.get(url
).text
148 latest
= readme
.split("version = \'")[1].split("\'")[0]
149 if current
!= latest
:
150 notice
= light_magenta('RainbowStream latest version is ')
151 notice
+= light_green(latest
)
152 notice
+= light_magenta(' while your current version is ')
153 notice
+= light_yellow(current
) + '\n'
154 notice
+= light_magenta('You should upgrade with ')
155 notice
+= light_green('pip install -U rainbowstream')
166 ctrl_c_handler
= lambda signum
, frame
: quit()
167 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
171 t
= Twitter(auth
=authen())
172 credential
= t
.account
.verify_credentials()
173 screen_name
= '@' + credential
['screen_name']
174 name
= credential
['name']
175 if not get_config('PREFIX'):
176 set_config('PREFIX', screen_name
)
177 c
['PREFIX'] = emojize(c
['PREFIX'])
178 g
['PREFIX'] = u2str(c
['PREFIX'])
179 c
['original_name'] = g
['original_name'] = screen_name
[1:]
180 g
['full_name'] = name
181 g
['decorated_name'] = lambda x
: color_func(
182 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
184 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
185 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
188 g
['message_threads'] = {}
191 # Debug option default = True
198 # Init tweet dict and message dict
200 c
['message_dict'] = []
202 c
['IMAGE_ON_TERM'] = args
.image_on_term
203 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
204 # Check type of ONLY_LIST and IGNORE_LIST
205 if not isinstance(c
['ONLY_LIST'], list):
206 printNicely(red('ONLY_LIST is not a valid list value.'))
208 if not isinstance(c
['IGNORE_LIST'], list):
209 printNicely(red('IGNORE_LIST is not a valid list value.'))
210 c
['IGNORE_LIST'] = []
212 c
['IGNORE_LIST'] += build_mute_dict()
219 t
= Twitter(auth
=authen())
220 # Get country and town
222 country
= g
['stuff'].split()[0]
226 town
= g
['stuff'].split()[1]
229 avail
= t
.trends
.available()
232 trends
= t
.trends
.place(_id
=1)[0]['trends']
235 for location
in avail
:
236 # Search for country and Town
238 if location
['countryCode'] == country \
239 and location
['placeType']['name'] == 'Town' \
240 and location
['name'] == town
:
241 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
243 # Search for country only
245 if location
['countryCode'] == country \
246 and location
['placeType']['name'] == 'Country':
247 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
255 t
= Twitter(auth
=authen())
256 num
= c
['HOME_TWEET_NUM']
257 if g
['stuff'].isdigit():
258 num
= int(g
['stuff'])
259 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
269 for e
in c
['events']:
273 printNicely(magenta('Nothing at this time.'))
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
.mentions_timeline(count
=num
)):
291 Show profile of a specific user
293 t
= Twitter(auth
=authen())
294 screen_name
= g
['stuff'].split()[0]
295 if screen_name
.startswith('@'):
298 screen_name
=screen_name
[1:],
299 include_entities
=False)
303 printNicely(red('No user.'))
305 printNicely(red('A name should begin with a \'@\''))
312 t
= Twitter(auth
=authen())
313 user
= g
['stuff'].split()[0]
316 num
= int(g
['stuff'].split()[1])
318 num
= c
['HOME_TWEET_NUM']
319 for tweet
in reversed(
320 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
324 printNicely(red('A name should begin with a \'@\''))
331 t
= Twitter(auth
=authen())
333 query
= g
['stuff'].strip()
334 type = c
['SEARCH_TYPE']
335 if type not in ['mixed', 'recent', 'popular']:
337 max_record
= c
['SEARCH_MAX_RECORD']
338 count
= min(max_record
, 100)
340 rel
= t
.search
.tweets(
347 printNicely('Newest tweets:')
348 for i
in reversed(xrange(count
)):
349 draw(t
=rel
[i
], keyword
=query
)
352 printNicely(magenta('I\'m afraid there is no result'))
359 t
= Twitter(auth
=authen())
360 t
.statuses
.update(status
=g
['stuff'])
367 t
= Twitter(auth
=authen())
369 id = int(g
['stuff'].split()[0])
371 printNicely(red('Sorry I can\'t understand.'))
373 tid
= c
['tweet_dict'][id]
374 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
382 t
= Twitter(auth
=authen())
384 id = int(g
['stuff'].split()[0])
386 printNicely(red('Sorry I can\'t understand.'))
388 tid
= c
['tweet_dict'][id]
389 tweet
= t
.statuses
.show(id=tid
)
391 formater
= format_quote(tweet
)
395 prefix
= light_magenta('Compose your ', rl
=True) + \
396 light_green('#comment: ', rl
=True)
397 comment
= raw_input(prefix
)
399 quote
= comment
.join(formater
.split('#comment'))
400 t
.statuses
.update(status
=quote
)
402 printNicely(light_magenta('No text added.'))
409 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 # Get display num if exist
419 num
= int(g
['stuff'].split()[1])
421 num
= c
['RETWEETS_SHOW_NUM']
422 # Get result and display
423 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
425 printNicely(magenta('This tweet has no retweet.'))
427 for tweet
in reversed(rt_ary
):
436 t
= Twitter(auth
=authen())
438 id = int(g
['stuff'].split()[0])
440 printNicely(red('Sorry I can\'t understand.'))
442 tid
= c
['tweet_dict'][id]
443 tweet
= t
.statuses
.show(id=tid
)
444 limit
= c
['CONVERSATION_MAX']
446 thread_ref
.append(tweet
)
447 prev_tid
= tweet
['in_reply_to_status_id']
448 while prev_tid
and limit
:
450 tweet
= t
.statuses
.show(id=prev_tid
)
451 prev_tid
= tweet
['in_reply_to_status_id']
452 thread_ref
.append(tweet
)
454 for tweet
in reversed(thread_ref
):
463 t
= Twitter(auth
=authen())
465 id = int(g
['stuff'].split()[0])
467 printNicely(red('Sorry I can\'t understand.'))
469 tid
= c
['tweet_dict'][id]
470 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
471 status
= ' '.join(g
['stuff'].split()[1:])
472 status
= '@' + user
+ ' ' + str2u(status
)
473 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
480 t
= Twitter(auth
=authen())
482 id = int(g
['stuff'].split()[0])
484 printNicely(red('Sorry I can\'t understand.'))
486 tid
= c
['tweet_dict'][id]
487 t
.favorites
.create(_id
=tid
, include_entities
=False)
488 printNicely(green('Favorited.'))
489 draw(t
.statuses
.show(id=tid
))
497 t
= Twitter(auth
=authen())
499 id = int(g
['stuff'].split()[0])
501 printNicely(red('Sorry I can\'t understand.'))
503 tid
= c
['tweet_dict'][id]
504 t
.favorites
.destroy(_id
=tid
)
505 printNicely(green('Okay it\'s unfavorited.'))
506 draw(t
.statuses
.show(id=tid
))
512 Copy url of a tweet to clipboard
514 t
= Twitter(auth
=authen())
516 id = int(g
['stuff'].split()[0])
517 tid
= c
['tweet_dict'][id]
519 printNicely(red('Tweet id is not valid.'))
521 tweet
= t
.statuses
.show(id=tid
)
522 url
= 'https://twitter.com/' + \
523 tweet
['user']['screen_name'] + '/status/' + str(tid
)
525 if platform
.system().lower() == 'darwin':
526 os
.system("echo '%s' | pbcopy" % url
)
527 printNicely(green('Copied tweet\'s url to clipboard.'))
529 printNicely('Direct link: ' + yellow(url
))
536 t
= Twitter(auth
=authen())
538 id = int(g
['stuff'].split()[0])
540 printNicely(red('Sorry I can\'t understand.'))
542 tid
= c
['tweet_dict'][id]
543 t
.statuses
.destroy(id=tid
)
544 printNicely(green('Okay it\'s gone.'))
551 t
= Twitter(auth
=authen())
553 target
= g
['stuff'].split()[0]
554 if target
!= 'image':
556 id = int(g
['stuff'].split()[1])
557 tid
= c
['tweet_dict'][id]
558 tweet
= t
.statuses
.show(id=tid
)
559 media
= tweet
['entities']['media']
561 res
= requests
.get(m
['media_url'])
562 img
= Image
.open(BytesIO(res
.content
))
566 printNicely(red('Sorry I can\'t show this image.'))
573 t
= Twitter(auth
=authen())
575 if not g
['stuff'].isdigit():
577 tid
= c
['tweet_dict'][int(g
['stuff'])]
578 tweet
= t
.statuses
.show(id=tid
)
579 link_prefix
= ('http://', 'https://')
580 link_ary
= [u
for u
in tweet
['text'].split()
581 if u
.startswith(link_prefix
)]
583 printNicely(light_magenta('No url here @.@!'))
585 for link
in link_ary
:
586 webbrowser
.open(link
)
589 printNicely(red('Sorry I can\'t open url in this tweet.'))
596 t
= Twitter(auth
=authen())
597 num
= c
['MESSAGES_DISPLAY']
598 if g
['stuff'].isdigit():
604 inbox
= inbox
+ t
.direct_messages(
607 include_entities
=False,
612 inbox
= inbox
+ t
.direct_messages(
615 include_entities
=False,
619 num
= c
['MESSAGES_DISPLAY']
620 if g
['stuff'].isdigit():
625 sent
= sent
+ t
.direct_messages
.sent(
628 include_entities
=False,
633 sent
= sent
+ t
.direct_messages
.sent(
636 include_entities
=False,
641 uniq_inbox
= list(set(
642 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
644 uniq_sent
= list(set(
645 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
647 for partner
in uniq_inbox
:
648 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
650 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
651 d
[partner
] = inbox_ary
+ sent_ary
652 for partner
in uniq_sent
:
655 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
656 g
['message_threads'] = print_threads(d
)
661 View a thread of message
664 thread_id
= int(g
['stuff'])
666 g
['message_threads'][thread_id
],
671 printNicely(red('No such thread.'))
676 Send a direct message
678 t
= Twitter(auth
=authen())
680 user
= g
['stuff'].split()[0]
681 if user
[0].startswith('@'):
682 content
= ' '.join(g
['stuff'].split()[1:])
683 t
.direct_messages
.new(
684 screen_name
=user
[1:],
687 printNicely(green('Message sent.'))
689 printNicely(red('A name should begin with a \'@\''))
692 printNicely(red('Sorry I can\'t understand.'))
699 t
= Twitter(auth
=authen())
701 id = int(g
['stuff'].split()[0])
703 printNicely(red('Sorry I can\'t understand.'))
704 mid
= c
['message_dict'][id]
705 t
.direct_messages
.destroy(id=mid
)
706 printNicely(green('Message deleted.'))
711 List friends for followers
713 t
= Twitter(auth
=authen())
716 name
= g
['stuff'].split()[1]
717 if name
.startswith('@'):
720 printNicely(red('A name should begin with a \'@\''))
721 raise Exception('Invalid name')
723 name
= g
['original_name']
724 # Get list followers or friends
726 target
= g
['stuff'].split()[0]
728 printNicely(red('Omg some syntax is wrong.'))
730 d
= {'fl': 'followers', 'fr': 'friends'}
734 while next_cursor
!= 0:
735 list = getattr(t
, d
[target
]).list(
739 include_entities
=False,
741 for u
in list['users']:
742 rel
[u
['name']] = '@' + u
['screen_name']
743 next_cursor
= list['next_cursor']
745 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
747 user
= ' ' + cycle_color(name
)
748 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
756 t
= Twitter(auth
=authen())
757 screen_name
= g
['stuff'].split()[0]
758 if screen_name
.startswith('@'):
759 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
760 printNicely(green('You are following ' + screen_name
+ ' now!'))
762 printNicely(red('A name should begin with a \'@\''))
769 t
= Twitter(auth
=authen())
770 screen_name
= g
['stuff'].split()[0]
771 if screen_name
.startswith('@'):
772 t
.friendships
.destroy(
773 screen_name
=screen_name
[1:],
774 include_entities
=False)
775 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
777 printNicely(red('A name should begin with a \'@\''))
784 t
= Twitter(auth
=authen())
786 screen_name
= g
['stuff'].split()[0]
788 printNicely(red('A name should be specified. '))
790 if screen_name
.startswith('@'):
792 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
793 if isinstance(rel
, dict):
794 printNicely(green(screen_name
+ ' is muted.'))
795 c
['IGNORE_LIST'] += [unc(screen_name
)]
796 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
798 printNicely(red(rel
))
801 printNicely(red('Something is wrong, can not mute now :('))
803 printNicely(red('A name should begin with a \'@\''))
810 t
= Twitter(auth
=authen())
812 screen_name
= g
['stuff'].split()[0]
814 printNicely(red('A name should be specified. '))
816 if screen_name
.startswith('@'):
818 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
819 if isinstance(rel
, dict):
820 printNicely(green(screen_name
+ ' is unmuted.'))
821 c
['IGNORE_LIST'].remove(screen_name
)
823 printNicely(red(rel
))
825 printNicely(red('Maybe you are not muting this person ?'))
827 printNicely(red('A name should begin with a \'@\''))
834 # Get dict of muting users
835 md
= build_mute_dict(dict_data
=True)
836 printNicely('All: ' + str(len(md
)) + ' people.')
838 user
= ' ' + cycle_color(md
[name
])
839 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
841 # Update from Twitter
842 c
['IGNORE_LIST'] = [n
for n
in md
]
849 t
= Twitter(auth
=authen())
850 screen_name
= g
['stuff'].split()[0]
851 if screen_name
.startswith('@'):
853 screen_name
=screen_name
[1:],
854 include_entities
=False,
856 printNicely(green('You blocked ' + screen_name
+ '.'))
858 printNicely(red('A name should begin with a \'@\''))
865 t
= Twitter(auth
=authen())
866 screen_name
= g
['stuff'].split()[0]
867 if screen_name
.startswith('@'):
869 screen_name
=screen_name
[1:],
870 include_entities
=False,
872 printNicely(green('Unblock ' + screen_name
+ ' success!'))
874 printNicely(red('A name should begin with a \'@\''))
879 Report a user as a spam account
881 t
= Twitter(auth
=authen())
882 screen_name
= g
['stuff'].split()[0]
883 if screen_name
.startswith('@'):
885 screen_name
=screen_name
[1:])
886 printNicely(green('You reported ' + screen_name
+ '.'))
888 printNicely(red('Sorry I can\'t understand.'))
896 list_name
= raw_input(
897 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
898 # Get list name and owner
900 owner
, slug
= list_name
.split('/')
901 if slug
.startswith('@'):
906 light_magenta('List name should follow "@owner/list_name" format.'))
907 raise Exception('Wrong list name')
914 rel
= t
.lists
.list(screen_name
=g
['original_name'])
918 printNicely(light_magenta('You belong to no lists :)'))
925 owner
, slug
= get_slug()
926 res
= t
.lists
.statuses(
928 owner_screen_name
=owner
,
930 include_entities
=False)
931 for tweet
in reversed(res
):
940 owner
, slug
= get_slug()
944 while next_cursor
!= 0:
947 owner_screen_name
=owner
,
949 include_entities
=False)
951 rel
[u
['name']] = '@' + u
['screen_name']
952 next_cursor
= m
['next_cursor']
953 printNicely('All: ' + str(len(rel
)) + ' members.')
955 user
= ' ' + cycle_color(name
)
956 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
960 def list_subscribers(t
):
964 owner
, slug
= get_slug()
968 while next_cursor
!= 0:
969 m
= t
.lists
.subscribers(
971 owner_screen_name
=owner
,
973 include_entities
=False)
975 rel
[u
['name']] = '@' + u
['screen_name']
976 next_cursor
= m
['next_cursor']
977 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
979 user
= ' ' + cycle_color(name
)
980 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
986 Add specific user to a list
988 owner
, slug
= get_slug()
990 user_name
= raw_input(
992 'Give me name of the newbie: ',
994 if user_name
.startswith('@'):
995 user_name
= user_name
[1:]
997 t
.lists
.members
.create(
999 owner_screen_name
=owner
,
1000 screen_name
=user_name
)
1001 printNicely(green('Added.'))
1004 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1009 Remove specific user from a list
1011 owner
, slug
= get_slug()
1013 user_name
= raw_input(
1015 'Give me name of the unlucky one: ',
1017 if user_name
.startswith('@'):
1018 user_name
= user_name
[1:]
1020 t
.lists
.members
.destroy(
1022 owner_screen_name
=owner
,
1023 screen_name
=user_name
)
1024 printNicely(green('Gone.'))
1027 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1030 def list_subscribe(t
):
1034 owner
, slug
= get_slug()
1037 t
.lists
.subscribers
.create(
1039 owner_screen_name
=owner
)
1040 printNicely(green('Done.'))
1044 light_magenta('I\'m sorry you can not subscribe to this list.'))
1047 def list_unsubscribe(t
):
1051 owner
, slug
= get_slug()
1054 t
.lists
.subscribers
.destroy(
1056 owner_screen_name
=owner
)
1057 printNicely(green('Done.'))
1061 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1070 while next_cursor
!= 0:
1071 res
= t
.lists
.ownerships(
1072 screen_name
=g
['original_name'],
1075 next_cursor
= res
['next_cursor']
1079 printNicely(light_magenta('You own no lists :)'))
1086 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1089 'New list\'s mode (public/private): ',
1091 description
= raw_input(
1093 'New list\'s description: ',
1099 description
=description
)
1100 printNicely(green(name
+ ' list is created.'))
1103 printNicely(red('Oops something is wrong with Twitter :('))
1112 'Your list that you want to update: ',
1116 'Update name (leave blank to unchange): ',
1118 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1119 description
= raw_input(light_magenta('Update description: ', rl
=True))
1123 slug
='-'.join(slug
.split()),
1124 owner_screen_name
=g
['original_name'],
1127 description
=description
)
1131 owner_screen_name
=g
['original_name'],
1133 description
=description
)
1134 printNicely(green(slug
+ ' list is updated.'))
1137 printNicely(red('Oops something is wrong with Twitter :('))
1146 'Your list that you want to delete: ',
1150 slug
='-'.join(slug
.split()),
1151 owner_screen_name
=g
['original_name'])
1152 printNicely(green(slug
+ ' list is deleted.'))
1155 printNicely(red('Oops something is wrong with Twitter :('))
1162 t
= Twitter(auth
=authen())
1163 # List all lists or base on action
1165 g
['list_action'] = g
['stuff'].split()[0]
1172 'all_mem': list_members
,
1173 'all_sub': list_subscribers
,
1176 'sub': list_subscribe
,
1177 'unsub': list_unsubscribe
,
1180 'update': list_update
,
1184 return action_ary
[g
['list_action']](t
)
1186 printNicely(red('Please try again.'))
1194 target
= g
['stuff'].split()[0]
1196 args
= parse_arguments()
1198 if g
['stuff'].split()[-1] == '-f':
1199 guide
= 'To ignore an option, just hit Enter key.'
1200 printNicely(light_magenta(guide
))
1201 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1202 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1203 args
.filter = filter(None, only
.split(','))
1204 args
.ignore
= filter(None, ignore
.split(','))
1206 printNicely(red('Sorry, wrong format.'))
1209 if target
== 'public':
1210 keyword
= g
['stuff'].split()[1]
1211 if keyword
[0] == '#':
1212 keyword
= keyword
[1:]
1214 g
['stream_stop'] = True
1215 args
.track_keywords
= keyword
1217 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1219 th
= threading
.Thread(
1227 elif target
== 'mine':
1229 g
['stream_stop'] = True
1231 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1233 th
= threading
.Thread(
1238 g
['original_name']))
1241 # Stream base on list
1242 elif target
== 'list':
1243 owner
, slug
= get_slug()
1244 # Force python 2 not redraw readline buffer
1245 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1246 printNicely(light_yellow('getting list members ...'))
1248 t
= Twitter(auth
=authen())
1251 while next_cursor
!= 0:
1252 m
= t
.lists
.members(
1254 owner_screen_name
=owner
,
1256 include_entities
=False)
1257 for u
in m
['users']:
1258 members
.append('@' + u
['screen_name'])
1259 next_cursor
= m
['next_cursor']
1260 printNicely(light_yellow('... done.'))
1261 # Build thread filter array
1262 args
.filter = members
1264 g
['stream_stop'] = True
1266 th
= threading
.Thread(
1276 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1278 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1282 printNicely(red('Sorry I can\'t understand.'))
1287 Unix's command `cal`
1290 rel
= os
.popen('cal').read().split('\n')
1293 show_calendar(month
, date
, rel
)
1298 List and change theme
1302 for theme
in g
['themes']:
1303 line
= light_magenta(theme
)
1304 if c
['THEME'] == theme
:
1305 line
= ' ' * 2 + light_yellow('* ') + line
1307 line
= ' ' * 4 + line
1313 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1314 # Redefine decorated_name
1315 g
['decorated_name'] = lambda x
: color_func(
1316 c
['DECORATED_NAME'])(
1318 printNicely(green('Theme changed.'))
1320 printNicely(red('No such theme exists.'))
1325 Browse and change config
1327 all_config
= get_all_config()
1328 g
['stuff'] = g
['stuff'].strip()
1331 for k
in all_config
:
1333 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1335 guide
= 'Detailed explanation can be found at ' + \
1336 color_func(c
['TWEET']['link'])(
1337 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1339 # Print specific config
1340 elif len(g
['stuff'].split()) == 1:
1341 if g
['stuff'] in all_config
:
1344 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1347 printNicely(red('No such config key.'))
1348 # Print specific config's default value
1349 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1350 key
= g
['stuff'].split()[0]
1352 value
= get_default_config(key
)
1353 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1357 printNicely(red('Just can not get the default.'))
1358 # Delete specific config key in config file
1359 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1360 key
= g
['stuff'].split()[0]
1363 printNicely(green('Config key is dropped.'))
1366 printNicely(red('Just can not drop the key.'))
1367 # Set specific config
1368 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1369 key
= g
['stuff'].split()[0]
1370 value
= g
['stuff'].split()[-1]
1371 if key
== 'THEME' and not validate_theme(value
):
1372 printNicely(red('Invalid theme\'s value.'))
1375 set_config(key
, value
)
1376 # Keys that needs to be apply immediately
1378 c
['THEME'] = reload_theme(value
, c
['THEME'])
1379 g
['decorated_name'] = lambda x
: color_func(
1380 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1381 elif key
== 'PREFIX':
1382 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1384 printNicely(green('Updated successfully.'))
1387 printNicely(red('Just can not set the key.'))
1389 printNicely(light_magenta('Sorry I can\'s understand.'))
1392 def help_discover():
1397 # Discover the world
1399 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1400 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1401 'You can try ' + light_green('trend US') + ' or ' + \
1402 light_green('trend JP Tokyo') + '.\n'
1403 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1404 light_green('home 7') + ' will show 7 tweets.\n'
1406 light_green('notification') + ' will show your recent notification.\n'
1407 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1408 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1409 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1410 magenta('@mdo') + '.\n'
1411 usage
+= s
* 2 + light_green('view @mdo') + \
1412 ' will show ' + magenta('@mdo') + '\'s home.\n'
1413 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1414 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1415 'Search can be performed with or without hashtag.\n'
1426 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1427 usage
+= s
* 2 + light_green('t oops ') + \
1428 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1430 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1431 light_yellow('[id=12]') + '.\n'
1433 light_green('quote 12 ') + ' will quote the tweet with ' + \
1434 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1435 'the quote will be canceled.\n'
1437 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1438 light_yellow('[id=12]') + '.\n'
1439 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1440 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1441 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1442 light_yellow('oops') + '" to tweet with ' + \
1443 light_yellow('[id=12]') + '.\n'
1445 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1446 light_yellow('[id=12]') + '.\n'
1448 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1449 light_yellow('[id=12]') + '.\n'
1451 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1452 light_yellow('[id=12]') + '.\n'
1454 light_green('del 12 ') + ' will delete tweet with ' + \
1455 light_yellow('[id=12]') + '.\n'
1456 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1457 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1458 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1459 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1463 def help_messages():
1470 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1471 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1472 light_green('inbox 7') + ' will show newest 7 messages.\n'
1473 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1474 light_yellow('[thread_id=2]') + '.\n'
1475 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1476 magenta('@dtvd88') + '.\n'
1477 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1478 light_yellow('[message_id=5]') + '.\n'
1482 def help_friends_and_followers():
1484 Friends and Followers
1487 # Follower and following
1489 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1491 light_green('ls fl') + \
1492 ' will list all followers (people who are following you).\n'
1494 light_green('ls fr') + \
1495 ' will list all friends (people who you are following).\n'
1496 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1497 magenta('@dtvd88') + '.\n'
1498 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1499 magenta('@dtvd88') + '.\n'
1500 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1501 magenta('@dtvd88') + '.\n'
1502 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1503 magenta('@dtvd88') + '.\n'
1504 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1505 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1506 magenta('@dtvd88') + '.\n'
1507 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1508 magenta('@dtvd88') + '.\n'
1509 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1510 magenta('@dtvd88') + ' as a spam account.\n'
1521 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1522 usage
+= s
* 2 + light_green('list') + \
1523 ' will show all lists you are belong to.\n'
1524 usage
+= s
* 2 + light_green('list home') + \
1525 ' will show timeline of list. You will be asked for list\'s name.\n'
1526 usage
+= s
* 2 + light_green('list all_mem') + \
1527 ' will show list\'s all members.\n'
1528 usage
+= s
* 2 + light_green('list all_sub') + \
1529 ' will show list\'s all subscribers.\n'
1530 usage
+= s
* 2 + light_green('list add') + \
1531 ' will add specific person to a list owned by you.' + \
1532 ' You will be asked for list\'s name and person\'s name.\n'
1533 usage
+= s
* 2 + light_green('list rm') + \
1534 ' will remove specific person from a list owned by you.' + \
1535 ' You will be asked for list\'s name and person\'s name.\n'
1536 usage
+= s
* 2 + light_green('list sub') + \
1537 ' will subscribe you to a specific list.\n'
1538 usage
+= s
* 2 + light_green('list unsub') + \
1539 ' will unsubscribe you from a specific list.\n'
1540 usage
+= s
* 2 + light_green('list own') + \
1541 ' will show all list owned by you.\n'
1542 usage
+= s
* 2 + light_green('list new') + \
1543 ' will create a new list.\n'
1544 usage
+= s
* 2 + light_green('list update') + \
1545 ' will update a list owned by you.\n'
1546 usage
+= s
* 2 + light_green('list del') + \
1547 ' will delete a list owned by you.\n'
1558 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1559 usage
+= s
* 2 + light_green('switch public #AKB') + \
1560 ' will switch to public stream and follow "' + \
1561 light_yellow('AKB') + '" keyword.\n'
1562 usage
+= s
* 2 + light_green('switch mine') + \
1563 ' will switch to your personal stream.\n'
1564 usage
+= s
* 2 + light_green('switch mine -f ') + \
1565 ' will prompt to enter the filter.\n'
1566 usage
+= s
* 3 + light_yellow('Only nicks') + \
1567 ' filter will decide nicks will be INCLUDE ONLY.\n'
1568 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1569 ' filter will decide nicks will be EXCLUDE.\n'
1570 usage
+= s
* 2 + light_green('switch list') + \
1571 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1580 h
, w
= os
.popen('stty size', 'r').read().split()
1583 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1584 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1585 usage
+= s
+ 'You are ' + \
1586 light_yellow('already') + ' on your personal stream.\n'
1587 usage
+= s
+ 'Any update from Twitter will show up ' + \
1588 light_yellow('immediately') + '.\n'
1589 usage
+= s
+ 'In addition, following commands are available right now:\n'
1590 # Twitter help section
1592 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1593 usage
+= s
* 2 + light_green('h discover') + \
1594 ' will show help for discover commands.\n'
1595 usage
+= s
* 2 + light_green('h tweets') + \
1596 ' will show help for tweets commands.\n'
1597 usage
+= s
* 2 + light_green('h messages') + \
1598 ' will show help for messages commands.\n'
1599 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1600 ' will show help for friends and followers commands.\n'
1601 usage
+= s
* 2 + light_green('h list') + \
1602 ' will show help for list commands.\n'
1603 usage
+= s
* 2 + light_green('h stream') + \
1604 ' will show help for stream commands.\n'
1607 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1608 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1609 'will be evaluate by Python interpreter.\n'
1610 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1611 ' for current month.\n'
1614 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1615 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1616 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1617 ' theme immediately.\n'
1618 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1620 light_green('config ASCII_ART') + ' will output current value of ' +\
1621 light_yellow('ASCII_ART') + ' config key.\n'
1623 light_green('config TREND_MAX default') + ' will output default value of ' + \
1624 light_yellow('TREND_MAX') + ' config key.\n'
1626 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1627 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1629 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1630 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1631 light_yellow('True') + '.\n'
1634 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1635 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1636 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1637 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1638 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1639 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1642 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1643 usage
+= s
+ 'Have fun and hang tight! \n'
1646 'discover': help_discover
,
1647 'tweets': help_tweets
,
1648 'messages': help_messages
,
1649 'friends_and_followers': help_friends_and_followers
,
1651 'stream': help_stream
,
1656 lambda: printNicely(red('No such command.'))
1664 Pause stream display
1667 printNicely(green('Stream is paused'))
1675 printNicely(green('Stream is running back now'))
1691 printNicely(green('See you next time :)'))
1699 Reset prefix of line
1702 if c
.get('USER_JSON_ERROR'):
1703 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1704 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1706 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1709 printNicely(str(eval(g
['cmd'])))
1760 # Handle function set
1811 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1816 Listen to user's input
1821 ['public', 'mine', 'list'], # switch
1839 ['image'], # show image
1841 ['fl', 'fr'], # list
1843 [i
for i
in g
['message_threads']], # sent
1868 [key
for key
in dict(get_all_config())], # config
1869 g
['themes'], # theme
1874 'friends_and_followers',
1884 init_interactive_shell(d
)
1891 # Only use PREFIX as a string with raw_input
1892 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1895 # Save cmd to compare with readline buffer
1896 g
['cmd'] = line
.strip()
1897 # Get short cmd to pass to handle function
1899 cmd
= line
.split()[0]
1902 # Lock the semaphore
1904 # Save cmd to global variable and call process
1905 g
['stuff'] = ' '.join(line
.split()[1:])
1906 # Process the command
1909 if cmd
in ['switch', 't', 'rt', 'rep']:
1913 # Release the semaphore lock
1919 printNicely(red('OMG something is wrong with Twitter right now.'))
1922 def reconn_notice():
1924 Notice when Hangup or Timeout
1926 guide
= light_magenta("You can use ") + \
1927 light_green("switch") + \
1928 light_magenta(" command to return to your stream.\n")
1929 guide
+= light_magenta("Type ") + \
1930 light_green("h stream") + \
1931 light_magenta(" for more details.")
1933 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1937 def stream(domain
, args
, name
='Rainbow Stream'):
1943 c
['USER_DOMAIN']: name
,
1944 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1945 c
['SITE_DOMAIN']: name
,
1948 ascii_art(art_dict
[domain
])
1949 # These arguments are optional:
1951 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1953 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1956 if args
.track_keywords
:
1957 query_args
['track'] = args
.track_keywords
1959 stream
= TwitterStream(
1964 if domain
== c
['USER_DOMAIN']:
1965 tweet_iter
= stream
.user(**query_args
)
1966 elif domain
== c
['SITE_DOMAIN']:
1967 tweet_iter
= stream
.site(**query_args
)
1969 if args
.track_keywords
:
1970 tweet_iter
= stream
.statuses
.filter(**query_args
)
1972 tweet_iter
= stream
.statuses
.sample()
1973 # Block new stream until other one exits
1974 StreamLock
.acquire()
1975 g
['stream_stop'] = False
1976 for tweet
in tweet_iter
:
1978 printNicely("-- None --")
1979 elif tweet
is Timeout
:
1980 # Because the stream check for each 0.3s
1981 # so we shouldn't output anything here
1982 if(g
['stream_stop']):
1983 StreamLock
.release()
1985 elif tweet
is HeartbeatTimeout
:
1986 printNicely("-- Heartbeat Timeout --")
1988 StreamLock
.release()
1990 elif tweet
is Hangup
:
1991 printNicely("-- Hangup --")
1993 StreamLock
.release()
1995 elif tweet
.get('text'):
1996 # Check the semaphore pause and lock (stream process only)
2004 keyword
=args
.track_keywords
,
2009 # Current readline buffer
2010 current_buffer
= readline
.get_line_buffer().strip()
2011 # There is an unexpected behaviour in MacOSX readline + Python 2:
2012 # after completely delete a word after typing it,
2013 # somehow readline buffer still contains
2014 # the 1st character of that word
2015 if current_buffer
and g
['cmd'] != current_buffer
:
2017 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2019 elif not c
['HIDE_PROMPT']:
2020 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2022 elif tweet
.get('direct_message'):
2023 # Check the semaphore pause and lock (stream process only)
2028 print_message(tweet
['direct_message'])
2029 elif tweet
.get('event'):
2030 c
['events'].append(tweet
)
2032 except TwitterHTTPError
:
2035 magenta("We have maximum connection problem with twitter'stream API right now :("))
2043 args
= parse_arguments()
2046 # Setup proxy by monkeypatching the standard lib
2047 # You might want to check https://github.com/Anorov/PySocks for further
2049 if args
.proxy_type
.lower() == "socks5" or not args
.proxy_type
:
2050 socks
.set_default_proxy(socks
.SOCKS5
, args
.proxy_host
, int(args
.proxy_port
))
2051 elif args
.proxy_type
.lower() == "http":
2052 socks
.set_default_proxy(socks
.HTTP
, args
.proxy_host
, int(args
.proxy_port
))
2053 elif args
.proxy_type
.lower() == "socks4":
2054 socks
.set_default_proxy(socks
.SOCKS4
, args
.proxy_host
, int(args
.proxy_port
))
2056 printNicely(magenta("Sorry, wrong proxy type specified! Aborting..."))
2058 socket
.socket
= socks
.socksocket
2060 except TwitterHTTPError
:
2063 magenta("We have connection problem with twitter'stream API right now :("))
2064 printNicely(magenta("Let's try again later."))
2067 except (ConnectionRefusedError
, socks
.ProxyConnectionError
, error
.URLError
):
2069 magenta("There seems to be a connection problem."))
2071 magenta("You might want to check your proxy settings (host, port and type)!"))
2075 # Spawn stream thread
2076 th
= threading
.Thread(
2081 g
['original_name']))
2084 # Start listen process