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
).content
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
+ ']: ')
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'] = {}
175 # Debug option default = True
178 # Retweet of mine events
182 # Init tweet dict and message dict
184 c
['message_dict'] = []
186 c
['IMAGE_ON_TERM'] = args
.image_on_term
187 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
189 c
['IGNORE_LIST'] += build_mute_dict()
196 t
= Twitter(auth
=authen())
197 # Get country and town
199 country
= g
['stuff'].split()[0]
203 town
= g
['stuff'].split()[1]
206 avail
= t
.trends
.available()
209 trends
= t
.trends
.place(_id
=1)[0]['trends']
212 for location
in avail
:
213 # Search for country and Town
215 if location
['countryCode'] == country \
216 and location
['placeType']['name'] == 'Town' \
217 and location
['name'] == town
:
218 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
220 # Search for country only
222 if location
['countryCode'] == country \
223 and location
['placeType']['name'] == 'Country':
224 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
232 t
= Twitter(auth
=authen())
233 num
= c
['HOME_TWEET_NUM']
234 if g
['stuff'].isdigit():
235 num
= int(g
['stuff'])
236 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
245 g
['events'] = g
['events'] + c
['events']
247 for e
in g
['events']:
251 printNicely(magenta('Nothing at this time.'))
258 t
= Twitter(auth
=authen())
259 num
= c
['HOME_TWEET_NUM']
260 if g
['stuff'].isdigit():
261 num
= int(g
['stuff'])
262 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
269 Show profile of a specific user
271 t
= Twitter(auth
=authen())
272 screen_name
= g
['stuff'].split()[0]
273 if screen_name
.startswith('@'):
276 screen_name
=screen_name
[1:],
277 include_entities
=False)
281 printNicely(red('No user.'))
283 printNicely(red('A name should begin with a \'@\''))
290 t
= Twitter(auth
=authen())
291 user
= g
['stuff'].split()[0]
294 num
= int(g
['stuff'].split()[1])
296 num
= c
['HOME_TWEET_NUM']
297 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
301 printNicely(red('A name should begin with a \'@\''))
308 t
= Twitter(auth
=authen())
310 query
= g
['stuff'].strip()
311 type = c
['SEARCH_TYPE']
312 if type not in ['mixed', 'recent', 'popular']:
314 max_record
= c
['SEARCH_MAX_RECORD']
315 count
= min(max_record
, 100)
317 rel
= t
.search
.tweets(
324 printNicely('Newest tweets:')
325 for i
in reversed(xrange(count
)):
326 draw(t
=rel
[i
], keyword
=query
)
329 printNicely(magenta('I\'m afraid there is no result'))
336 t
= Twitter(auth
=authen())
337 t
.statuses
.update(status
=g
['stuff'])
344 t
= Twitter(auth
=authen())
346 id = int(g
['stuff'].split()[0])
348 printNicely(red('Sorry I can\'t understand.'))
350 tid
= c
['tweet_dict'][id]
351 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
359 t
= Twitter(auth
=authen())
361 id = int(g
['stuff'].split()[0])
363 printNicely(red('Sorry I can\'t understand.'))
365 tid
= c
['tweet_dict'][id]
366 tweet
= t
.statuses
.show(id=tid
)
368 formater
= format_quote(tweet
)
372 prefix
= light_magenta('Compose your ') + light_green('#comment: ')
373 comment
= raw_input(prefix
)
375 quote
= comment
.join(formater
.split('#comment'))
376 t
.statuses
.update(status
=quote
)
378 printNicely(light_magenta('No text added.'))
385 t
= Twitter(auth
=authen())
388 id = int(g
['stuff'].split()[0])
390 printNicely(red('Sorry I can\'t understand.'))
392 tid
= c
['tweet_dict'][id]
393 # Get display num if exist
395 num
= int(g
['stuff'].split()[1])
397 num
= c
['RETWEETS_SHOW_NUM']
398 # Get result and display
399 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
401 printNicely(magenta('This tweet has no retweet.'))
403 for tweet
in reversed(rt_ary
):
412 t
= Twitter(auth
=authen())
414 id = int(g
['stuff'].split()[0])
416 printNicely(red('Sorry I can\'t understand.'))
418 tid
= c
['tweet_dict'][id]
419 tweet
= t
.statuses
.show(id=tid
)
420 limit
= c
['CONVERSATION_MAX']
422 thread_ref
.append(tweet
)
423 prev_tid
= tweet
['in_reply_to_status_id']
424 while prev_tid
and limit
:
426 tweet
= t
.statuses
.show(id=prev_tid
)
427 prev_tid
= tweet
['in_reply_to_status_id']
428 thread_ref
.append(tweet
)
430 for tweet
in reversed(thread_ref
):
439 t
= Twitter(auth
=authen())
441 id = int(g
['stuff'].split()[0])
443 printNicely(red('Sorry I can\'t understand.'))
445 tid
= c
['tweet_dict'][id]
446 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
447 status
= ' '.join(g
['stuff'].split()[1:])
448 status
= '@' + user
+ ' ' + str2u(status
)
449 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
456 t
= Twitter(auth
=authen())
458 id = int(g
['stuff'].split()[0])
460 printNicely(red('Sorry I can\'t understand.'))
462 tid
= c
['tweet_dict'][id]
463 t
.favorites
.create(_id
=tid
, include_entities
=False)
464 printNicely(green('Favorited.'))
465 draw(t
.statuses
.show(id=tid
))
473 t
= Twitter(auth
=authen())
475 id = int(g
['stuff'].split()[0])
477 printNicely(red('Sorry I can\'t understand.'))
479 tid
= c
['tweet_dict'][id]
480 t
.favorites
.destroy(_id
=tid
)
481 printNicely(green('Okay it\'s unfavorited.'))
482 draw(t
.statuses
.show(id=tid
))
490 t
= Twitter(auth
=authen())
492 id = int(g
['stuff'].split()[0])
494 printNicely(red('Sorry I can\'t understand.'))
496 tid
= c
['tweet_dict'][id]
497 t
.statuses
.destroy(id=tid
)
498 printNicely(green('Okay it\'s gone.'))
505 t
= Twitter(auth
=authen())
507 target
= g
['stuff'].split()[0]
508 if target
!= 'image':
510 id = int(g
['stuff'].split()[1])
511 tid
= c
['tweet_dict'][id]
512 tweet
= t
.statuses
.show(id=tid
)
513 media
= tweet
['entities']['media']
515 res
= requests
.get(m
['media_url'])
516 img
= Image
.open(BytesIO(res
.content
))
520 printNicely(red('Sorry I can\'t show this image.'))
527 t
= Twitter(auth
=authen())
529 if not g
['stuff'].isdigit():
531 tid
= c
['tweet_dict'][int(g
['stuff'])]
532 tweet
= t
.statuses
.show(id=tid
)
533 link_prefix
= ('http://', 'https://')
534 link_ary
= [u
for u
in tweet
['text'].split()
535 if u
.startswith(link_prefix
)]
537 printNicely(light_magenta('No url here @.@!'))
539 for link
in link_ary
:
540 webbrowser
.open(link
)
543 printNicely(red('Sorry I can\'t open url in this tweet.'))
550 t
= Twitter(auth
=authen())
551 num
= c
['MESSAGES_DISPLAY']
552 if g
['stuff'].isdigit():
558 inbox
= inbox
+ t
.direct_messages(
561 include_entities
=False,
566 inbox
= inbox
+ t
.direct_messages(
569 include_entities
=False,
573 num
= c
['MESSAGES_DISPLAY']
574 if g
['stuff'].isdigit():
579 sent
= sent
+ t
.direct_messages
.sent(
582 include_entities
=False,
587 sent
= sent
+ t
.direct_messages
.sent(
590 include_entities
=False,
595 uniq_inbox
= list(set(
596 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
598 uniq_sent
= list(set(
599 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
601 for partner
in uniq_inbox
:
602 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
604 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
605 d
[partner
] = inbox_ary
+ sent_ary
606 for partner
in uniq_sent
:
609 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
610 g
['message_threads'] = print_threads(d
)
615 View a thread of message
618 thread_id
= int(g
['stuff'])
620 g
['message_threads'][thread_id
],
625 printNicely(red('No such thread.'))
630 Send a direct message
632 t
= Twitter(auth
=authen())
634 user
= g
['stuff'].split()[0]
635 if user
[0].startswith('@'):
636 content
= ' '.join(g
['stuff'].split()[1:])
637 t
.direct_messages
.new(
638 screen_name
=user
[1:],
641 printNicely(green('Message sent.'))
643 printNicely(red('A name should begin with a \'@\''))
646 printNicely(red('Sorry I can\'t understand.'))
653 t
= Twitter(auth
=authen())
655 id = int(g
['stuff'].split()[0])
657 printNicely(red('Sorry I can\'t understand.'))
658 mid
= c
['message_dict'][id]
659 t
.direct_messages
.destroy(id=mid
)
660 printNicely(green('Message deleted.'))
665 List friends for followers
667 t
= Twitter(auth
=authen())
670 name
= g
['stuff'].split()[1]
671 if name
.startswith('@'):
674 printNicely(red('A name should begin with a \'@\''))
675 raise Exception('Invalid name')
677 name
= g
['original_name']
678 # Get list followers or friends
680 target
= g
['stuff'].split()[0]
682 printNicely(red('Omg some syntax is wrong.'))
684 d
= {'fl': 'followers', 'fr': 'friends'}
688 while next_cursor
!= 0:
689 list = getattr(t
, d
[target
]).list(
693 include_entities
=False,
695 for u
in list['users']:
696 rel
[u
['name']] = '@' + u
['screen_name']
697 next_cursor
= list['next_cursor']
699 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
701 user
= ' ' + cycle_color(name
)
702 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
710 t
= Twitter(auth
=authen())
711 screen_name
= g
['stuff'].split()[0]
712 if screen_name
.startswith('@'):
713 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
714 printNicely(green('You are following ' + screen_name
+ ' now!'))
716 printNicely(red('A name should begin with a \'@\''))
723 t
= Twitter(auth
=authen())
724 screen_name
= g
['stuff'].split()[0]
725 if screen_name
.startswith('@'):
726 t
.friendships
.destroy(
727 screen_name
=screen_name
[1:],
728 include_entities
=False)
729 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
731 printNicely(red('A name should begin with a \'@\''))
738 t
= Twitter(auth
=authen())
740 screen_name
= g
['stuff'].split()[0]
742 printNicely(red('A name should be specified. '))
744 if screen_name
.startswith('@'):
746 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
747 if isinstance(rel
, dict):
748 printNicely(green(screen_name
+ ' is muted.'))
749 c
['IGNORE_LIST'] += [unc(screen_name
)]
750 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
752 printNicely(red(rel
))
755 printNicely(red('Something is wrong, can not mute now :('))
757 printNicely(red('A name should begin with a \'@\''))
764 t
= Twitter(auth
=authen())
766 screen_name
= g
['stuff'].split()[0]
768 printNicely(red('A name should be specified. '))
770 if screen_name
.startswith('@'):
772 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
773 if isinstance(rel
, dict):
774 printNicely(green(screen_name
+ ' is unmuted.'))
775 c
['IGNORE_LIST'].remove(screen_name
)
777 printNicely(red(rel
))
779 printNicely(red('Maybe you are not muting this person ?'))
781 printNicely(red('A name should begin with a \'@\''))
788 # Get dict of muting users
789 md
= build_mute_dict(dict_data
=True)
790 printNicely('All: ' + str(len(md
)) + ' people.')
792 user
= ' ' + cycle_color(md
[name
])
793 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
795 # Update from Twitter
796 c
['IGNORE_LIST'] = [n
for n
in md
]
803 t
= Twitter(auth
=authen())
804 screen_name
= g
['stuff'].split()[0]
805 if screen_name
.startswith('@'):
807 screen_name
=screen_name
[1:],
808 include_entities
=False,
810 printNicely(green('You blocked ' + screen_name
+ '.'))
812 printNicely(red('A name should begin with a \'@\''))
819 t
= Twitter(auth
=authen())
820 screen_name
= g
['stuff'].split()[0]
821 if screen_name
.startswith('@'):
823 screen_name
=screen_name
[1:],
824 include_entities
=False,
826 printNicely(green('Unblock ' + screen_name
+ ' success!'))
828 printNicely(red('A name should begin with a \'@\''))
833 Report a user as a spam account
835 t
= Twitter(auth
=authen())
836 screen_name
= g
['stuff'].split()[0]
837 if screen_name
.startswith('@'):
839 screen_name
=screen_name
[1:])
840 printNicely(green('You reported ' + screen_name
+ '.'))
842 printNicely(red('Sorry I can\'t understand.'))
850 list_name
= raw_input(light_magenta('Give me the list\'s name: '))
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(light_magenta('Give me name of the newbie: '))
944 if user_name
.startswith('@'):
945 user_name
= user_name
[1:]
947 t
.lists
.members
.create(
949 owner_screen_name
=owner
,
950 screen_name
=user_name
)
951 printNicely(green('Added.'))
954 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
959 Remove specific user from a list
961 owner
, slug
= get_slug()
963 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
964 if user_name
.startswith('@'):
965 user_name
= user_name
[1:]
967 t
.lists
.members
.destroy(
969 owner_screen_name
=owner
,
970 screen_name
=user_name
)
971 printNicely(green('Gone.'))
974 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
977 def list_subscribe(t
):
981 owner
, slug
= get_slug()
984 t
.lists
.subscribers
.create(
986 owner_screen_name
=owner
)
987 printNicely(green('Done.'))
991 light_magenta('I\'m sorry you can not subscribe to this list.'))
994 def list_unsubscribe(t
):
998 owner
, slug
= get_slug()
1001 t
.lists
.subscribers
.destroy(
1003 owner_screen_name
=owner
)
1004 printNicely(green('Done.'))
1008 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1017 while next_cursor
!= 0:
1018 res
= t
.lists
.ownerships(
1019 screen_name
=g
['original_name'],
1022 next_cursor
= res
['next_cursor']
1026 printNicely(light_magenta('You own no lists :)'))
1033 name
= raw_input(light_magenta('New list\'s name: '))
1034 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1035 description
= raw_input(light_magenta('New list\'s description: '))
1040 description
=description
)
1041 printNicely(green(name
+ ' list is created.'))
1044 printNicely(red('Oops something is wrong with Twitter :('))
1051 slug
= raw_input(light_magenta('Your list that you want to update: '))
1052 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1053 mode
= raw_input(light_magenta('Update mode (public/private): '))
1054 description
= raw_input(light_magenta('Update description: '))
1058 slug
='-'.join(slug
.split()),
1059 owner_screen_name
=g
['original_name'],
1062 description
=description
)
1066 owner_screen_name
=g
['original_name'],
1068 description
=description
)
1069 printNicely(green(slug
+ ' list is updated.'))
1072 printNicely(red('Oops something is wrong with Twitter :('))
1079 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1082 slug
='-'.join(slug
.split()),
1083 owner_screen_name
=g
['original_name'])
1084 printNicely(green(slug
+ ' list is deleted.'))
1087 printNicely(red('Oops something is wrong with Twitter :('))
1094 t
= Twitter(auth
=authen())
1095 # List all lists or base on action
1097 g
['list_action'] = g
['stuff'].split()[0]
1104 'all_mem': list_members
,
1105 'all_sub': list_subscribers
,
1108 'sub': list_subscribe
,
1109 'unsub': list_unsubscribe
,
1112 'update': list_update
,
1116 return action_ary
[g
['list_action']](t
)
1118 printNicely(red('Please try again.'))
1126 target
= g
['stuff'].split()[0]
1128 args
= parse_arguments()
1130 if g
['stuff'].split()[-1] == '-f':
1131 guide
= 'To ignore an option, just hit Enter key.'
1132 printNicely(light_magenta(guide
))
1133 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1134 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1135 args
.filter = filter(None, only
.split(','))
1136 args
.ignore
= filter(None, ignore
.split(','))
1137 elif g
['stuff'].split()[-1] == '-d':
1138 args
.filter = c
['ONLY_LIST']
1139 args
.ignore
= c
['IGNORE_LIST']
1141 printNicely(red('Sorry, wrong format.'))
1144 if target
== 'public':
1145 keyword
= g
['stuff'].split()[1]
1146 if keyword
[0] == '#':
1147 keyword
= keyword
[1:]
1149 g
['stream_stop'] = True
1150 args
.track_keywords
= keyword
1152 th
= threading
.Thread(
1160 elif target
== 'mine':
1162 g
['stream_stop'] = True
1164 th
= threading
.Thread(
1169 g
['original_name']))
1174 printNicely(cyan('Only: ' + str(args
.filter)))
1176 printNicely(red('Ignore: ' + str(args
.ignore
)))
1179 printNicely(red('Sorry I can\'t understand.'))
1184 Unix's command `cal`
1187 rel
= os
.popen('cal').read().split('\n')
1190 show_calendar(month
, date
, rel
)
1195 List and change theme
1199 for theme
in g
['themes']:
1200 line
= light_magenta(theme
)
1201 if c
['THEME'] == theme
:
1202 line
= ' ' * 2 + light_yellow('* ') + line
1204 line
= ' ' * 4 + line
1210 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1211 # Redefine decorated_name
1212 g
['decorated_name'] = lambda x
: color_func(
1213 c
['DECORATED_NAME'])(
1215 printNicely(green('Theme changed.'))
1217 printNicely(red('No such theme exists.'))
1222 Browse and change config
1224 all_config
= get_all_config()
1225 g
['stuff'] = g
['stuff'].strip()
1228 for k
in all_config
:
1230 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1232 guide
= 'Detailed explanation can be found at ' + \
1233 color_func(c
['TWEET']['link'])(
1234 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1236 # Print specific config
1237 elif len(g
['stuff'].split()) == 1:
1238 if g
['stuff'] in all_config
:
1241 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1244 printNicely(red('No such config key.'))
1245 # Print specific config's default value
1246 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1247 key
= g
['stuff'].split()[0]
1249 value
= get_default_config(key
)
1250 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1252 except Exception as e
:
1254 # Delete specific config key in config file
1255 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1256 key
= g
['stuff'].split()[0]
1259 printNicely(green('Config key is dropped.'))
1260 except Exception as e
:
1262 # Set specific config
1263 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1264 key
= g
['stuff'].split()[0]
1265 value
= g
['stuff'].split()[-1]
1266 if key
== 'THEME' and not validate_theme(value
):
1267 printNicely(red('Invalid theme\'s value.'))
1270 set_config(key
, value
)
1271 # Apply theme immediately
1273 c
['THEME'] = reload_theme(value
, c
['THEME'])
1274 g
['decorated_name'] = lambda x
: color_func(
1275 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1277 printNicely(green('Updated successfully.'))
1278 except Exception as e
:
1281 printNicely(light_magenta('Sorry I can\'s understand.'))
1284 def help_discover():
1289 # Discover the world
1291 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1292 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1293 'You can try ' + light_green('trend US') + ' or ' + \
1294 light_green('trend JP Tokyo') + '.\n'
1295 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1296 light_green('home 7') + ' will show 7 tweets.\n'
1298 light_green('notification') + ' will show your recent notification.\n'
1299 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1300 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1301 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1302 magenta('@mdo') + '.\n'
1303 usage
+= s
* 2 + light_green('view @mdo') + \
1304 ' will show ' + magenta('@mdo') + '\'s home.\n'
1305 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1306 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1307 'Search can be performed with or without hashtag.\n'
1318 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1319 usage
+= s
* 2 + light_green('t oops ') + \
1320 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1322 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1323 light_yellow('[id=12]') + '.\n'
1325 light_green('quote 12 ') + ' will quote the tweet with ' + \
1326 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1327 'the quote will be canceled.\n'
1329 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1330 light_yellow('[id=12]') + '.\n'
1331 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1332 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1333 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1334 light_yellow('oops') + '" to tweet with ' + \
1335 light_yellow('[id=12]') + '.\n'
1337 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1338 light_yellow('[id=12]') + '.\n'
1340 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1341 light_yellow('[id=12]') + '.\n'
1343 light_green('del 12 ') + ' will delete tweet with ' + \
1344 light_yellow('[id=12]') + '.\n'
1345 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1346 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1347 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1348 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1352 def help_messages():
1359 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1360 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1361 light_green('inbox 7') + ' will show newest 7 messages.\n'
1362 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1363 light_yellow('[thread_id=2]') + '.\n'
1364 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1365 magenta('@dtvd88') + '.\n'
1366 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1367 light_yellow('[message_id=5]') + '.\n'
1371 def help_friends_and_followers():
1373 Friends and Followers
1376 # Follower and following
1378 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1380 light_green('ls fl') + \
1381 ' will list all followers (people who are following you).\n'
1383 light_green('ls fr') + \
1384 ' will list all friends (people who you are following).\n'
1385 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1386 magenta('@dtvd88') + '.\n'
1387 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1388 magenta('@dtvd88') + '.\n'
1389 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1390 magenta('@dtvd88') + '.\n'
1391 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1392 magenta('@dtvd88') + '.\n'
1393 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1394 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1395 magenta('@dtvd88') + '.\n'
1396 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1397 magenta('@dtvd88') + '.\n'
1398 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1399 magenta('@dtvd88') + ' as a spam account.\n'
1410 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1411 usage
+= s
* 2 + light_green('list') + \
1412 ' will show all lists you are belong to.\n'
1413 usage
+= s
* 2 + light_green('list home') + \
1414 ' will show timeline of list. You will be asked for list\'s name.\n'
1415 usage
+= s
* 2 + light_green('list all_mem') + \
1416 ' will show list\'s all members.\n'
1417 usage
+= s
* 2 + light_green('list all_sub') + \
1418 ' will show list\'s all subscribers.\n'
1419 usage
+= s
* 2 + light_green('list add') + \
1420 ' will add specific person to a list owned by you.' + \
1421 ' You will be asked for list\'s name and person\'s name.\n'
1422 usage
+= s
* 2 + light_green('list rm') + \
1423 ' will remove specific person from a list owned by you.' + \
1424 ' You will be asked for list\'s name and person\'s name.\n'
1425 usage
+= s
* 2 + light_green('list sub') + \
1426 ' will subscribe you to a specific list.\n'
1427 usage
+= s
* 2 + light_green('list unsub') + \
1428 ' will unsubscribe you from a specific list.\n'
1429 usage
+= s
* 2 + light_green('list own') + \
1430 ' will show all list owned by you.\n'
1431 usage
+= s
* 2 + light_green('list new') + \
1432 ' will create a new list.\n'
1433 usage
+= s
* 2 + light_green('list update') + \
1434 ' will update a list owned by you.\n'
1435 usage
+= s
* 2 + light_green('list del') + \
1436 ' will delete a list owned by you.\n'
1447 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1448 usage
+= s
* 2 + light_green('switch public #AKB') + \
1449 ' will switch to public stream and follow "' + \
1450 light_yellow('AKB') + '" keyword.\n'
1451 usage
+= s
* 2 + light_green('switch mine') + \
1452 ' will switch to your personal stream.\n'
1453 usage
+= s
* 2 + light_green('switch mine -f ') + \
1454 ' will prompt to enter the filter.\n'
1455 usage
+= s
* 3 + light_yellow('Only nicks') + \
1456 ' filter will decide nicks will be INCLUDE ONLY.\n'
1457 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1458 ' filter will decide nicks will be EXCLUDE.\n'
1459 usage
+= s
* 2 + light_green('switch mine -d') + \
1460 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1469 h
, w
= os
.popen('stty size', 'r').read().split()
1472 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1473 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1474 usage
+= s
+ 'You are ' + \
1475 light_yellow('already') + ' on your personal stream.\n'
1476 usage
+= s
+ 'Any update from Twitter will show up ' + \
1477 light_yellow('immediately') + '.\n'
1478 usage
+= s
+ 'In addition, following commands are available right now:\n'
1479 # Twitter help section
1481 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1482 usage
+= s
* 2 + light_green('h discover') + \
1483 ' will show help for discover commands.\n'
1484 usage
+= s
* 2 + light_green('h tweets') + \
1485 ' will show help for tweets commands.\n'
1486 usage
+= s
* 2 + light_green('h messages') + \
1487 ' will show help for messages commands.\n'
1488 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1489 ' will show help for friends and followers commands.\n'
1490 usage
+= s
* 2 + light_green('h list') + \
1491 ' will show help for list commands.\n'
1492 usage
+= s
* 2 + light_green('h stream') + \
1493 ' will show help for stream commands.\n'
1496 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1497 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1498 'will be evaluate by Python interpreter.\n'
1499 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1500 ' for current month.\n'
1503 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1504 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1505 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1506 ' theme immediately.\n'
1507 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1509 light_green('config ASCII_ART') + ' will output current value of ' +\
1510 light_yellow('ASCII_ART') + ' config key.\n'
1512 light_green('config TREND_MAX default') + ' will output default value of ' + \
1513 light_yellow('TREND_MAX') + ' config key.\n'
1515 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1516 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1518 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1519 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1520 light_yellow('True') + '.\n'
1523 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1524 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1525 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1526 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1527 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1528 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1531 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1532 usage
+= s
+ 'Have fun and hang tight! \n'
1535 'discover': help_discover
,
1536 'tweets': help_tweets
,
1537 'messages': help_messages
,
1538 'friends_and_followers': help_friends_and_followers
,
1540 'stream': help_stream
,
1545 lambda: printNicely(red('No such command.'))
1553 Pause stream display
1556 printNicely(green('Stream is paused'))
1564 printNicely(green('Stream is running back now'))
1580 printNicely(green('See you next time :)'))
1588 Reset prefix of line
1591 if c
.get('USER_JSON_ERROR'):
1592 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1593 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1595 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1598 printNicely(str(eval(g
['cmd'])))
1648 # Handle function set
1698 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1703 Listen to user's input
1708 ['public', 'mine'], # switch
1725 ['image'], # show image
1727 ['fl', 'fr'], # list
1729 [i
for i
in g
['message_threads']], # sent
1754 [key
for key
in dict(get_all_config())], # config
1755 g
['themes'], # theme
1760 'friends_and_followers',
1770 init_interactive_shell(d
)
1777 # Only use PREFIX as a string with raw_input
1778 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1781 # Save cmd to compare with readline buffer
1782 g
['cmd'] = line
.strip()
1783 # Get short cmd to pass to handle function
1785 cmd
= line
.split()[0]
1788 # Lock the semaphore
1790 # Save cmd to global variable and call process
1791 g
['stuff'] = ' '.join(line
.split()[1:])
1792 # Process the command
1795 if cmd
in ['switch', 't', 'rt', 'rep']:
1799 # Release the semaphore lock
1805 printNicely(red('OMG something is wrong with Twitter right now.'))
1808 def stream(domain
, args
, name
='Rainbow Stream'):
1814 c
['USER_DOMAIN']: name
,
1815 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1816 c
['SITE_DOMAIN']: name
,
1819 ascii_art(art_dict
[domain
])
1820 # These arguments are optional:
1822 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1824 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1827 if args
.track_keywords
:
1828 query_args
['track'] = args
.track_keywords
1830 stream
= TwitterStream(
1835 if domain
== c
['USER_DOMAIN']:
1836 tweet_iter
= stream
.user(**query_args
)
1837 elif domain
== c
['SITE_DOMAIN']:
1838 tweet_iter
= stream
.site(**query_args
)
1840 if args
.track_keywords
:
1841 tweet_iter
= stream
.statuses
.filter(**query_args
)
1843 tweet_iter
= stream
.statuses
.sample()
1844 # Block new stream until other one exits
1845 StreamLock
.acquire()
1846 g
['stream_stop'] = False
1847 for tweet
in tweet_iter
:
1849 printNicely("-- None --")
1850 elif tweet
is Timeout
:
1851 if(g
['stream_stop']):
1852 StreamLock
.release()
1854 elif tweet
is HeartbeatTimeout
:
1855 printNicely("-- Heartbeat Timeout --")
1856 guide
= light_magenta("You can use ") + \
1857 light_green("switch") + \
1858 light_magenta(" command to return to your stream.\n")
1859 guide
+= light_magenta("Type ") + \
1860 light_green("h stream") + \
1861 light_magenta(" for more details.")
1863 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1865 StreamLock
.release()
1867 elif tweet
is Hangup
:
1868 printNicely("-- Hangup --")
1869 elif tweet
.get('text'):
1870 # Check the semaphore pause and lock (stream process only)
1878 keyword
=args
.track_keywords
,
1883 # Current readline buffer
1884 current_buffer
= readline
.get_line_buffer().strip()
1885 # There is an unexpected behaviour in MacOSX readline + Python 2:
1886 # after completely delete a word after typing it,
1887 # somehow readline buffer still contains
1888 # the 1st character of that word
1889 if current_buffer
and g
['cmd'] != current_buffer
:
1891 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1893 elif not c
['HIDE_PROMPT']:
1894 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1896 elif tweet
.get('direct_message'):
1897 # Check the semaphore pause and lock (stream process only)
1902 print_message(tweet
['direct_message'])
1903 elif tweet
.get('event'):
1904 g
['events'].append(tweet
)
1906 except TwitterHTTPError
:
1909 magenta("We have maximum connection problem with twitter'stream API right now :("))
1917 args
= parse_arguments()
1920 except TwitterHTTPError
:
1923 magenta("We have connection problem with twitter'stream API right now :("))
1924 printNicely(magenta("Let's try again later."))
1927 # Spawn stream thread
1928 th
= threading
.Thread(
1933 g
['original_name']))
1936 # Start listen process