13 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
14 from twitter
.api
import *
15 from twitter
.oauth
import OAuth
, read_token_file
16 from twitter
.oauth_dance
import oauth_dance
17 from twitter
.util
import printNicely
22 from .consumer
import *
23 from .interactive
import *
24 from .c_image
import *
25 from .py3patch
import *
32 StreamLock
= threading
.Lock()
35 def parse_arguments():
39 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
43 help='Timeout for the stream (seconds).')
47 help='Search the stream for specific text.')
51 help='Filter specific screen_name.')
55 help='Ignore specific screen_name.')
60 help='Display all image on terminal.')
61 return parser
.parse_args()
66 Authenticate with Twitter OAuth
68 # When using rainbow stream you must authorize.
69 twitter_credential
= os
.environ
.get(
73 '')) + os
.sep
+ '.rainbow_oauth'
74 if not os
.path
.exists(twitter_credential
):
75 oauth_dance("Rainbow Stream",
79 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
87 def build_mute_dict(dict_data
=False):
91 t
= Twitter(auth
=authen())
97 while next_cursor
!= 0:
98 list = t
.mutes
.users
.list(
99 screen_name
=g
['original_name'],
102 include_entities
=False,
104 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
105 name_list
+= [u
['name'] for u
in list['users']]
106 next_cursor
= list['next_cursor']
107 # Return dict or list
109 return dict(zip(screen_name_list
, name_list
))
111 return screen_name_list
116 Save traceback when run in debug mode
119 g
['traceback'].append(traceback
.format_exc())
122 def upgrade_center():
124 Check latest and notify to upgrade
127 current
= pkg_resources
.get_distribution("rainbowstream").version
128 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
129 readme
= requests
.get(url
).text
130 latest
= readme
.split("version = \'")[1].split("\'")[0]
131 if current
!= latest
:
132 notice
= light_magenta('RainbowStream latest version is ')
133 notice
+= light_green(latest
)
134 notice
+= light_magenta(' while your current version is ')
135 notice
+= light_yellow(current
) + '\n'
136 notice
+= light_magenta('You should upgrade with ')
137 notice
+= light_green('pip install -U rainbowstream')
148 ctrl_c_handler
= lambda signum
, frame
: quit()
149 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
153 t
= Twitter(auth
=authen())
154 credential
= t
.account
.verify_credentials()
155 screen_name
= '@' + credential
['screen_name']
156 name
= credential
['name']
157 if not get_config('PREFIX'):
158 set_config('PREFIX', screen_name
)
159 c
['PREFIX'] = emojize(c
['PREFIX'])
160 g
['PREFIX'] = u2str(c
['PREFIX'])
161 c
['original_name'] = g
['original_name'] = screen_name
[1:]
162 g
['full_name'] = name
163 g
['decorated_name'] = lambda x
: color_func(
164 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
166 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
167 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
170 g
['message_threads'] = {}
173 # Debug option default = True
180 # Init tweet dict and message dict
182 c
['message_dict'] = []
184 c
['IMAGE_ON_TERM'] = args
.image_on_term
185 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
187 c
['IGNORE_LIST'] += build_mute_dict()
194 t
= Twitter(auth
=authen())
195 # Get country and town
197 country
= g
['stuff'].split()[0]
201 town
= g
['stuff'].split()[1]
204 avail
= t
.trends
.available()
207 trends
= t
.trends
.place(_id
=1)[0]['trends']
210 for location
in avail
:
211 # Search for country and Town
213 if location
['countryCode'] == country \
214 and location
['placeType']['name'] == 'Town' \
215 and location
['name'] == town
:
216 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
218 # Search for country only
220 if location
['countryCode'] == country \
221 and location
['placeType']['name'] == 'Country':
222 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
230 t
= Twitter(auth
=authen())
231 num
= c
['HOME_TWEET_NUM']
232 if g
['stuff'].isdigit():
233 num
= int(g
['stuff'])
234 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
244 for e
in c
['events']:
248 printNicely(magenta('Nothing at this time.'))
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
.mentions_timeline(count
=num
)):
266 Show profile of a specific user
268 t
= Twitter(auth
=authen())
269 screen_name
= g
['stuff'].split()[0]
270 if screen_name
.startswith('@'):
273 screen_name
=screen_name
[1:],
274 include_entities
=False)
278 printNicely(red('No user.'))
280 printNicely(red('A name should begin with a \'@\''))
287 t
= Twitter(auth
=authen())
288 user
= g
['stuff'].split()[0]
291 num
= int(g
['stuff'].split()[1])
293 num
= c
['HOME_TWEET_NUM']
294 for tweet
in reversed(
295 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
299 printNicely(red('A name should begin with a \'@\''))
306 t
= Twitter(auth
=authen())
308 query
= g
['stuff'].strip()
309 type = c
['SEARCH_TYPE']
310 if type not in ['mixed', 'recent', 'popular']:
312 max_record
= c
['SEARCH_MAX_RECORD']
313 count
= min(max_record
, 100)
315 rel
= t
.search
.tweets(
322 printNicely('Newest tweets:')
323 for i
in reversed(xrange(count
)):
324 draw(t
=rel
[i
], keyword
=query
)
327 printNicely(magenta('I\'m afraid there is no result'))
334 t
= Twitter(auth
=authen())
335 t
.statuses
.update(status
=g
['stuff'])
342 t
= Twitter(auth
=authen())
344 id = int(g
['stuff'].split()[0])
346 printNicely(red('Sorry I can\'t understand.'))
348 tid
= c
['tweet_dict'][id]
349 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
357 t
= Twitter(auth
=authen())
359 id = int(g
['stuff'].split()[0])
361 printNicely(red('Sorry I can\'t understand.'))
363 tid
= c
['tweet_dict'][id]
364 tweet
= t
.statuses
.show(id=tid
)
366 formater
= format_quote(tweet
)
370 prefix
= light_magenta('Compose your ', rl
=True) + \
371 light_green('#comment: ', rl
=True)
372 comment
= raw_input(prefix
)
374 quote
= comment
.join(formater
.split('#comment'))
375 t
.statuses
.update(status
=quote
)
377 printNicely(light_magenta('No text added.'))
384 t
= Twitter(auth
=authen())
387 id = int(g
['stuff'].split()[0])
389 printNicely(red('Sorry I can\'t understand.'))
391 tid
= c
['tweet_dict'][id]
392 # Get display num if exist
394 num
= int(g
['stuff'].split()[1])
396 num
= c
['RETWEETS_SHOW_NUM']
397 # Get result and display
398 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
400 printNicely(magenta('This tweet has no retweet.'))
402 for tweet
in reversed(rt_ary
):
411 t
= Twitter(auth
=authen())
413 id = int(g
['stuff'].split()[0])
415 printNicely(red('Sorry I can\'t understand.'))
417 tid
= c
['tweet_dict'][id]
418 tweet
= t
.statuses
.show(id=tid
)
419 limit
= c
['CONVERSATION_MAX']
421 thread_ref
.append(tweet
)
422 prev_tid
= tweet
['in_reply_to_status_id']
423 while prev_tid
and limit
:
425 tweet
= t
.statuses
.show(id=prev_tid
)
426 prev_tid
= tweet
['in_reply_to_status_id']
427 thread_ref
.append(tweet
)
429 for tweet
in reversed(thread_ref
):
438 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 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
446 status
= ' '.join(g
['stuff'].split()[1:])
447 status
= '@' + user
+ ' ' + str2u(status
)
448 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
455 t
= Twitter(auth
=authen())
457 id = int(g
['stuff'].split()[0])
459 printNicely(red('Sorry I can\'t understand.'))
461 tid
= c
['tweet_dict'][id]
462 t
.favorites
.create(_id
=tid
, include_entities
=False)
463 printNicely(green('Favorited.'))
464 draw(t
.statuses
.show(id=tid
))
472 t
= Twitter(auth
=authen())
474 id = int(g
['stuff'].split()[0])
476 printNicely(red('Sorry I can\'t understand.'))
478 tid
= c
['tweet_dict'][id]
479 t
.favorites
.destroy(_id
=tid
)
480 printNicely(green('Okay it\'s unfavorited.'))
481 draw(t
.statuses
.show(id=tid
))
489 t
= Twitter(auth
=authen())
491 id = int(g
['stuff'].split()[0])
493 printNicely(red('Sorry I can\'t understand.'))
495 tid
= c
['tweet_dict'][id]
496 t
.statuses
.destroy(id=tid
)
497 printNicely(green('Okay it\'s gone.'))
504 t
= Twitter(auth
=authen())
506 target
= g
['stuff'].split()[0]
507 if target
!= 'image':
509 id = int(g
['stuff'].split()[1])
510 tid
= c
['tweet_dict'][id]
511 tweet
= t
.statuses
.show(id=tid
)
512 media
= tweet
['entities']['media']
514 res
= requests
.get(m
['media_url'])
515 img
= Image
.open(BytesIO(res
.content
))
519 printNicely(red('Sorry I can\'t show this image.'))
526 t
= Twitter(auth
=authen())
528 if not g
['stuff'].isdigit():
530 tid
= c
['tweet_dict'][int(g
['stuff'])]
531 tweet
= t
.statuses
.show(id=tid
)
532 link_prefix
= ('http://', 'https://')
533 link_ary
= [u
for u
in tweet
['text'].split()
534 if u
.startswith(link_prefix
)]
536 printNicely(light_magenta('No url here @.@!'))
538 for link
in link_ary
:
539 webbrowser
.open(link
)
542 printNicely(red('Sorry I can\'t open url in this tweet.'))
549 t
= Twitter(auth
=authen())
550 num
= c
['MESSAGES_DISPLAY']
551 if g
['stuff'].isdigit():
557 inbox
= inbox
+ t
.direct_messages(
560 include_entities
=False,
565 inbox
= inbox
+ t
.direct_messages(
568 include_entities
=False,
572 num
= c
['MESSAGES_DISPLAY']
573 if g
['stuff'].isdigit():
578 sent
= sent
+ t
.direct_messages
.sent(
581 include_entities
=False,
586 sent
= sent
+ t
.direct_messages
.sent(
589 include_entities
=False,
594 uniq_inbox
= list(set(
595 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
597 uniq_sent
= list(set(
598 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
600 for partner
in uniq_inbox
:
601 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
603 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
604 d
[partner
] = inbox_ary
+ sent_ary
605 for partner
in uniq_sent
:
608 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
609 g
['message_threads'] = print_threads(d
)
614 View a thread of message
617 thread_id
= int(g
['stuff'])
619 g
['message_threads'][thread_id
],
624 printNicely(red('No such thread.'))
629 Send a direct message
631 t
= Twitter(auth
=authen())
633 user
= g
['stuff'].split()[0]
634 if user
[0].startswith('@'):
635 content
= ' '.join(g
['stuff'].split()[1:])
636 t
.direct_messages
.new(
637 screen_name
=user
[1:],
640 printNicely(green('Message sent.'))
642 printNicely(red('A name should begin with a \'@\''))
645 printNicely(red('Sorry I can\'t understand.'))
652 t
= Twitter(auth
=authen())
654 id = int(g
['stuff'].split()[0])
656 printNicely(red('Sorry I can\'t understand.'))
657 mid
= c
['message_dict'][id]
658 t
.direct_messages
.destroy(id=mid
)
659 printNicely(green('Message deleted.'))
664 List friends for followers
666 t
= Twitter(auth
=authen())
669 name
= g
['stuff'].split()[1]
670 if name
.startswith('@'):
673 printNicely(red('A name should begin with a \'@\''))
674 raise Exception('Invalid name')
676 name
= g
['original_name']
677 # Get list followers or friends
679 target
= g
['stuff'].split()[0]
681 printNicely(red('Omg some syntax is wrong.'))
683 d
= {'fl': 'followers', 'fr': 'friends'}
687 while next_cursor
!= 0:
688 list = getattr(t
, d
[target
]).list(
692 include_entities
=False,
694 for u
in list['users']:
695 rel
[u
['name']] = '@' + u
['screen_name']
696 next_cursor
= list['next_cursor']
698 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
700 user
= ' ' + cycle_color(name
)
701 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
709 t
= Twitter(auth
=authen())
710 screen_name
= g
['stuff'].split()[0]
711 if screen_name
.startswith('@'):
712 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
713 printNicely(green('You are following ' + screen_name
+ ' now!'))
715 printNicely(red('A name should begin with a \'@\''))
722 t
= Twitter(auth
=authen())
723 screen_name
= g
['stuff'].split()[0]
724 if screen_name
.startswith('@'):
725 t
.friendships
.destroy(
726 screen_name
=screen_name
[1:],
727 include_entities
=False)
728 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
730 printNicely(red('A name should begin with a \'@\''))
737 t
= Twitter(auth
=authen())
739 screen_name
= g
['stuff'].split()[0]
741 printNicely(red('A name should be specified. '))
743 if screen_name
.startswith('@'):
745 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
746 if isinstance(rel
, dict):
747 printNicely(green(screen_name
+ ' is muted.'))
748 c
['IGNORE_LIST'] += [unc(screen_name
)]
749 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
751 printNicely(red(rel
))
754 printNicely(red('Something is wrong, can not mute now :('))
756 printNicely(red('A name should begin with a \'@\''))
763 t
= Twitter(auth
=authen())
765 screen_name
= g
['stuff'].split()[0]
767 printNicely(red('A name should be specified. '))
769 if screen_name
.startswith('@'):
771 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
772 if isinstance(rel
, dict):
773 printNicely(green(screen_name
+ ' is unmuted.'))
774 c
['IGNORE_LIST'].remove(screen_name
)
776 printNicely(red(rel
))
778 printNicely(red('Maybe you are not muting this person ?'))
780 printNicely(red('A name should begin with a \'@\''))
787 # Get dict of muting users
788 md
= build_mute_dict(dict_data
=True)
789 printNicely('All: ' + str(len(md
)) + ' people.')
791 user
= ' ' + cycle_color(md
[name
])
792 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
794 # Update from Twitter
795 c
['IGNORE_LIST'] = [n
for n
in md
]
802 t
= Twitter(auth
=authen())
803 screen_name
= g
['stuff'].split()[0]
804 if screen_name
.startswith('@'):
806 screen_name
=screen_name
[1:],
807 include_entities
=False,
809 printNicely(green('You blocked ' + screen_name
+ '.'))
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('@'):
822 screen_name
=screen_name
[1:],
823 include_entities
=False,
825 printNicely(green('Unblock ' + screen_name
+ ' success!'))
827 printNicely(red('A name should begin with a \'@\''))
832 Report a user as a spam account
834 t
= Twitter(auth
=authen())
835 screen_name
= g
['stuff'].split()[0]
836 if screen_name
.startswith('@'):
838 screen_name
=screen_name
[1:])
839 printNicely(green('You reported ' + screen_name
+ '.'))
841 printNicely(red('Sorry I can\'t understand.'))
849 list_name
= raw_input(
850 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
851 # Get list name and owner
853 owner
, slug
= list_name
.split('/')
854 if slug
.startswith('@'):
859 light_magenta('List name should follow "@owner/list_name" format.'))
860 raise Exception('Wrong list name')
867 rel
= t
.lists
.list(screen_name
=g
['original_name'])
871 printNicely(light_magenta('You belong to no lists :)'))
878 owner
, slug
= get_slug()
879 res
= t
.lists
.statuses(
881 owner_screen_name
=owner
,
883 include_entities
=False)
893 owner
, slug
= get_slug()
897 while next_cursor
!= 0:
900 owner_screen_name
=owner
,
902 include_entities
=False)
904 rel
[u
['name']] = '@' + u
['screen_name']
905 next_cursor
= m
['next_cursor']
906 printNicely('All: ' + str(len(rel
)) + ' members.')
908 user
= ' ' + cycle_color(name
)
909 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
913 def list_subscribers(t
):
917 owner
, slug
= get_slug()
921 while next_cursor
!= 0:
922 m
= t
.lists
.subscribers(
924 owner_screen_name
=owner
,
926 include_entities
=False)
928 rel
[u
['name']] = '@' + u
['screen_name']
929 next_cursor
= m
['next_cursor']
930 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
932 user
= ' ' + cycle_color(name
)
933 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
939 Add specific user to a list
941 owner
, slug
= get_slug()
943 user_name
= raw_input(
945 'Give me name of the newbie: ',
947 if user_name
.startswith('@'):
948 user_name
= user_name
[1:]
950 t
.lists
.members
.create(
952 owner_screen_name
=owner
,
953 screen_name
=user_name
)
954 printNicely(green('Added.'))
957 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
962 Remove specific user from a list
964 owner
, slug
= get_slug()
966 user_name
= raw_input(
968 'Give me name of the unlucky one: ',
970 if user_name
.startswith('@'):
971 user_name
= user_name
[1:]
973 t
.lists
.members
.destroy(
975 owner_screen_name
=owner
,
976 screen_name
=user_name
)
977 printNicely(green('Gone.'))
980 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
983 def list_subscribe(t
):
987 owner
, slug
= get_slug()
990 t
.lists
.subscribers
.create(
992 owner_screen_name
=owner
)
993 printNicely(green('Done.'))
997 light_magenta('I\'m sorry you can not subscribe to this list.'))
1000 def list_unsubscribe(t
):
1004 owner
, slug
= get_slug()
1007 t
.lists
.subscribers
.destroy(
1009 owner_screen_name
=owner
)
1010 printNicely(green('Done.'))
1014 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1023 while next_cursor
!= 0:
1024 res
= t
.lists
.ownerships(
1025 screen_name
=g
['original_name'],
1028 next_cursor
= res
['next_cursor']
1032 printNicely(light_magenta('You own no lists :)'))
1039 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1042 'New list\'s mode (public/private): ',
1044 description
= raw_input(
1046 'New list\'s description: ',
1052 description
=description
)
1053 printNicely(green(name
+ ' list is created.'))
1056 printNicely(red('Oops something is wrong with Twitter :('))
1065 'Your list that you want to update: ',
1069 'Update name (leave blank to unchange): ',
1071 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1072 description
= raw_input(light_magenta('Update description: ', rl
=True))
1076 slug
='-'.join(slug
.split()),
1077 owner_screen_name
=g
['original_name'],
1080 description
=description
)
1084 owner_screen_name
=g
['original_name'],
1086 description
=description
)
1087 printNicely(green(slug
+ ' list is updated.'))
1090 printNicely(red('Oops something is wrong with Twitter :('))
1099 'Your list that you want to delete: ',
1103 slug
='-'.join(slug
.split()),
1104 owner_screen_name
=g
['original_name'])
1105 printNicely(green(slug
+ ' list is deleted.'))
1108 printNicely(red('Oops something is wrong with Twitter :('))
1115 t
= Twitter(auth
=authen())
1116 # List all lists or base on action
1118 g
['list_action'] = g
['stuff'].split()[0]
1125 'all_mem': list_members
,
1126 'all_sub': list_subscribers
,
1129 'sub': list_subscribe
,
1130 'unsub': list_unsubscribe
,
1133 'update': list_update
,
1137 return action_ary
[g
['list_action']](t
)
1139 printNicely(red('Please try again.'))
1147 target
= g
['stuff'].split()[0]
1149 args
= parse_arguments()
1151 if g
['stuff'].split()[-1] == '-f':
1152 guide
= 'To ignore an option, just hit Enter key.'
1153 printNicely(light_magenta(guide
))
1154 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1155 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1156 args
.filter = filter(None, only
.split(','))
1157 args
.ignore
= filter(None, ignore
.split(','))
1158 elif g
['stuff'].split()[-1] == '-d':
1159 args
.filter = c
['ONLY_LIST']
1160 args
.ignore
= c
['IGNORE_LIST']
1162 printNicely(red('Sorry, wrong format.'))
1165 if target
== 'public':
1166 keyword
= g
['stuff'].split()[1]
1167 if keyword
[0] == '#':
1168 keyword
= keyword
[1:]
1170 g
['stream_stop'] = True
1171 args
.track_keywords
= keyword
1173 th
= threading
.Thread(
1181 elif target
== 'mine':
1183 g
['stream_stop'] = True
1185 th
= threading
.Thread(
1190 g
['original_name']))
1193 # Stream base on list
1194 elif target
== 'list':
1195 owner
, slug
= get_slug()
1196 # Force python 2 not redraw readline buffer
1197 g
['cmd'] = '/'.join([owner
, slug
])
1198 printNicely(light_yellow('getting list members ...'))
1200 t
= Twitter(auth
=authen())
1203 while next_cursor
!= 0:
1204 m
= t
.lists
.members(
1206 owner_screen_name
=owner
,
1208 include_entities
=False)
1209 for u
in m
['users']:
1210 members
.append('@' + u
['screen_name'])
1211 next_cursor
= m
['next_cursor']
1212 printNicely(light_yellow('... done.'))
1213 # Build thread filter array
1214 args
.filter = members
1216 g
['stream_stop'] = True
1218 th
= threading
.Thread(
1228 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1230 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1234 printNicely(red('Sorry I can\'t understand.'))
1239 Unix's command `cal`
1242 rel
= os
.popen('cal').read().split('\n')
1245 show_calendar(month
, date
, rel
)
1250 List and change theme
1254 for theme
in g
['themes']:
1255 line
= light_magenta(theme
)
1256 if c
['THEME'] == theme
:
1257 line
= ' ' * 2 + light_yellow('* ') + line
1259 line
= ' ' * 4 + line
1265 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1266 # Redefine decorated_name
1267 g
['decorated_name'] = lambda x
: color_func(
1268 c
['DECORATED_NAME'])(
1270 printNicely(green('Theme changed.'))
1272 printNicely(red('No such theme exists.'))
1277 Browse and change config
1279 all_config
= get_all_config()
1280 g
['stuff'] = g
['stuff'].strip()
1283 for k
in all_config
:
1285 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1287 guide
= 'Detailed explanation can be found at ' + \
1288 color_func(c
['TWEET']['link'])(
1289 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1291 # Print specific config
1292 elif len(g
['stuff'].split()) == 1:
1293 if g
['stuff'] in all_config
:
1296 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1299 printNicely(red('No such config key.'))
1300 # Print specific config's default value
1301 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1302 key
= g
['stuff'].split()[0]
1304 value
= get_default_config(key
)
1305 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1307 except Exception as e
:
1309 # Delete specific config key in config file
1310 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1311 key
= g
['stuff'].split()[0]
1314 printNicely(green('Config key is dropped.'))
1315 except Exception as e
:
1317 # Set specific config
1318 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1319 key
= g
['stuff'].split()[0]
1320 value
= g
['stuff'].split()[-1]
1321 if key
== 'THEME' and not validate_theme(value
):
1322 printNicely(red('Invalid theme\'s value.'))
1325 set_config(key
, value
)
1326 # Apply theme immediately
1328 c
['THEME'] = reload_theme(value
, c
['THEME'])
1329 g
['decorated_name'] = lambda x
: color_func(
1330 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1332 printNicely(green('Updated successfully.'))
1333 except Exception as e
:
1336 printNicely(light_magenta('Sorry I can\'s understand.'))
1339 def help_discover():
1344 # Discover the world
1346 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1347 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1348 'You can try ' + light_green('trend US') + ' or ' + \
1349 light_green('trend JP Tokyo') + '.\n'
1350 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1351 light_green('home 7') + ' will show 7 tweets.\n'
1353 light_green('notification') + ' will show your recent notification.\n'
1354 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1355 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1356 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1357 magenta('@mdo') + '.\n'
1358 usage
+= s
* 2 + light_green('view @mdo') + \
1359 ' will show ' + magenta('@mdo') + '\'s home.\n'
1360 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1361 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1362 'Search can be performed with or without hashtag.\n'
1373 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1374 usage
+= s
* 2 + light_green('t oops ') + \
1375 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1377 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1378 light_yellow('[id=12]') + '.\n'
1380 light_green('quote 12 ') + ' will quote the tweet with ' + \
1381 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1382 'the quote will be canceled.\n'
1384 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1385 light_yellow('[id=12]') + '.\n'
1386 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1387 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1388 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1389 light_yellow('oops') + '" to tweet with ' + \
1390 light_yellow('[id=12]') + '.\n'
1392 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1393 light_yellow('[id=12]') + '.\n'
1395 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1396 light_yellow('[id=12]') + '.\n'
1398 light_green('del 12 ') + ' will delete tweet with ' + \
1399 light_yellow('[id=12]') + '.\n'
1400 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1401 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1402 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1403 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1407 def help_messages():
1414 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1415 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1416 light_green('inbox 7') + ' will show newest 7 messages.\n'
1417 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1418 light_yellow('[thread_id=2]') + '.\n'
1419 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1420 magenta('@dtvd88') + '.\n'
1421 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1422 light_yellow('[message_id=5]') + '.\n'
1426 def help_friends_and_followers():
1428 Friends and Followers
1431 # Follower and following
1433 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1435 light_green('ls fl') + \
1436 ' will list all followers (people who are following you).\n'
1438 light_green('ls fr') + \
1439 ' will list all friends (people who you are following).\n'
1440 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1441 magenta('@dtvd88') + '.\n'
1442 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1443 magenta('@dtvd88') + '.\n'
1444 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1445 magenta('@dtvd88') + '.\n'
1446 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1447 magenta('@dtvd88') + '.\n'
1448 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1449 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1450 magenta('@dtvd88') + '.\n'
1451 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1452 magenta('@dtvd88') + '.\n'
1453 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1454 magenta('@dtvd88') + ' as a spam account.\n'
1465 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1466 usage
+= s
* 2 + light_green('list') + \
1467 ' will show all lists you are belong to.\n'
1468 usage
+= s
* 2 + light_green('list home') + \
1469 ' will show timeline of list. You will be asked for list\'s name.\n'
1470 usage
+= s
* 2 + light_green('list all_mem') + \
1471 ' will show list\'s all members.\n'
1472 usage
+= s
* 2 + light_green('list all_sub') + \
1473 ' will show list\'s all subscribers.\n'
1474 usage
+= s
* 2 + light_green('list add') + \
1475 ' will add specific person to a list owned by you.' + \
1476 ' You will be asked for list\'s name and person\'s name.\n'
1477 usage
+= s
* 2 + light_green('list rm') + \
1478 ' will remove specific person from a list owned by you.' + \
1479 ' You will be asked for list\'s name and person\'s name.\n'
1480 usage
+= s
* 2 + light_green('list sub') + \
1481 ' will subscribe you to a specific list.\n'
1482 usage
+= s
* 2 + light_green('list unsub') + \
1483 ' will unsubscribe you from a specific list.\n'
1484 usage
+= s
* 2 + light_green('list own') + \
1485 ' will show all list owned by you.\n'
1486 usage
+= s
* 2 + light_green('list new') + \
1487 ' will create a new list.\n'
1488 usage
+= s
* 2 + light_green('list update') + \
1489 ' will update a list owned by you.\n'
1490 usage
+= s
* 2 + light_green('list del') + \
1491 ' will delete a list owned by you.\n'
1502 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1503 usage
+= s
* 2 + light_green('switch public #AKB') + \
1504 ' will switch to public stream and follow "' + \
1505 light_yellow('AKB') + '" keyword.\n'
1506 usage
+= s
* 2 + light_green('switch mine') + \
1507 ' will switch to your personal stream.\n'
1508 usage
+= s
* 2 + light_green('switch mine -f ') + \
1509 ' will prompt to enter the filter.\n'
1510 usage
+= s
* 3 + light_yellow('Only nicks') + \
1511 ' filter will decide nicks will be INCLUDE ONLY.\n'
1512 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1513 ' filter will decide nicks will be EXCLUDE.\n'
1514 usage
+= s
* 2 + light_green('switch mine -d') + \
1515 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1516 usage
+= s
* 2 + light_green('switch list') + \
1517 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1526 h
, w
= os
.popen('stty size', 'r').read().split()
1529 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1530 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1531 usage
+= s
+ 'You are ' + \
1532 light_yellow('already') + ' on your personal stream.\n'
1533 usage
+= s
+ 'Any update from Twitter will show up ' + \
1534 light_yellow('immediately') + '.\n'
1535 usage
+= s
+ 'In addition, following commands are available right now:\n'
1536 # Twitter help section
1538 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1539 usage
+= s
* 2 + light_green('h discover') + \
1540 ' will show help for discover commands.\n'
1541 usage
+= s
* 2 + light_green('h tweets') + \
1542 ' will show help for tweets commands.\n'
1543 usage
+= s
* 2 + light_green('h messages') + \
1544 ' will show help for messages commands.\n'
1545 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1546 ' will show help for friends and followers commands.\n'
1547 usage
+= s
* 2 + light_green('h list') + \
1548 ' will show help for list commands.\n'
1549 usage
+= s
* 2 + light_green('h stream') + \
1550 ' will show help for stream commands.\n'
1553 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1554 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1555 'will be evaluate by Python interpreter.\n'
1556 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1557 ' for current month.\n'
1560 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1561 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1562 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1563 ' theme immediately.\n'
1564 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1566 light_green('config ASCII_ART') + ' will output current value of ' +\
1567 light_yellow('ASCII_ART') + ' config key.\n'
1569 light_green('config TREND_MAX default') + ' will output default value of ' + \
1570 light_yellow('TREND_MAX') + ' config key.\n'
1572 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1573 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1575 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1576 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1577 light_yellow('True') + '.\n'
1580 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1581 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1582 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1583 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1584 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1585 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1588 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1589 usage
+= s
+ 'Have fun and hang tight! \n'
1592 'discover': help_discover
,
1593 'tweets': help_tweets
,
1594 'messages': help_messages
,
1595 'friends_and_followers': help_friends_and_followers
,
1597 'stream': help_stream
,
1602 lambda: printNicely(red('No such command.'))
1610 Pause stream display
1613 printNicely(green('Stream is paused'))
1621 printNicely(green('Stream is running back now'))
1637 printNicely(green('See you next time :)'))
1645 Reset prefix of line
1648 if c
.get('USER_JSON_ERROR'):
1649 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1650 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1652 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1655 printNicely(str(eval(g
['cmd'])))
1705 # Handle function set
1755 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1760 Listen to user's input
1765 ['public', 'mine', 'list'], # switch
1782 ['image'], # show image
1784 ['fl', 'fr'], # list
1786 [i
for i
in g
['message_threads']], # sent
1811 [key
for key
in dict(get_all_config())], # config
1812 g
['themes'], # theme
1817 'friends_and_followers',
1827 init_interactive_shell(d
)
1834 # Only use PREFIX as a string with raw_input
1835 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1838 # Save cmd to compare with readline buffer
1839 g
['cmd'] = line
.strip()
1840 # Get short cmd to pass to handle function
1842 cmd
= line
.split()[0]
1845 # Lock the semaphore
1847 # Save cmd to global variable and call process
1848 g
['stuff'] = ' '.join(line
.split()[1:])
1849 # Process the command
1852 if cmd
in ['switch', 't', 'rt', 'rep']:
1856 # Release the semaphore lock
1862 printNicely(red('OMG something is wrong with Twitter right now.'))
1865 def stream(domain
, args
, name
='Rainbow Stream'):
1871 c
['USER_DOMAIN']: name
,
1872 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1873 c
['SITE_DOMAIN']: name
,
1876 ascii_art(art_dict
[domain
])
1877 # These arguments are optional:
1879 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1881 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1884 if args
.track_keywords
:
1885 query_args
['track'] = args
.track_keywords
1887 stream
= TwitterStream(
1892 if domain
== c
['USER_DOMAIN']:
1893 tweet_iter
= stream
.user(**query_args
)
1894 elif domain
== c
['SITE_DOMAIN']:
1895 tweet_iter
= stream
.site(**query_args
)
1897 if args
.track_keywords
:
1898 tweet_iter
= stream
.statuses
.filter(**query_args
)
1900 tweet_iter
= stream
.statuses
.sample()
1901 # Block new stream until other one exits
1902 StreamLock
.acquire()
1903 g
['stream_stop'] = False
1904 for tweet
in tweet_iter
:
1906 printNicely("-- None --")
1907 elif tweet
is Timeout
:
1908 if(g
['stream_stop']):
1909 StreamLock
.release()
1911 elif tweet
is HeartbeatTimeout
:
1912 printNicely("-- Heartbeat Timeout --")
1913 guide
= light_magenta("You can use ") + \
1914 light_green("switch") + \
1915 light_magenta(" command to return to your stream.\n")
1916 guide
+= light_magenta("Type ") + \
1917 light_green("h stream") + \
1918 light_magenta(" for more details.")
1920 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1922 StreamLock
.release()
1924 elif tweet
is Hangup
:
1925 printNicely("-- Hangup --")
1926 elif tweet
.get('text'):
1927 # Check the semaphore pause and lock (stream process only)
1935 keyword
=args
.track_keywords
,
1940 # Current readline buffer
1941 current_buffer
= readline
.get_line_buffer().strip()
1942 # There is an unexpected behaviour in MacOSX readline + Python 2:
1943 # after completely delete a word after typing it,
1944 # somehow readline buffer still contains
1945 # the 1st character of that word
1946 if current_buffer
and g
['cmd'] != current_buffer
:
1948 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1950 elif not c
['HIDE_PROMPT']:
1951 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1953 elif tweet
.get('direct_message'):
1954 # Check the semaphore pause and lock (stream process only)
1959 print_message(tweet
['direct_message'])
1960 elif tweet
.get('event'):
1961 c
['events'].append(tweet
)
1963 except TwitterHTTPError
:
1966 magenta("We have maximum connection problem with twitter'stream API right now :("))
1974 args
= parse_arguments()
1977 except TwitterHTTPError
:
1980 magenta("We have connection problem with twitter'stream API right now :("))
1981 printNicely(magenta("Let's try again later."))
1984 # Spawn stream thread
1985 th
= threading
.Thread(
1990 g
['original_name']))
1993 # Start listen process