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
+ ']: ', 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(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
298 printNicely(red('A name should begin with a \'@\''))
305 t
= Twitter(auth
=authen())
307 query
= g
['stuff'].strip()
308 type = c
['SEARCH_TYPE']
309 if type not in ['mixed', 'recent', 'popular']:
311 max_record
= c
['SEARCH_MAX_RECORD']
312 count
= min(max_record
, 100)
314 rel
= t
.search
.tweets(
321 printNicely('Newest tweets:')
322 for i
in reversed(xrange(count
)):
323 draw(t
=rel
[i
], keyword
=query
)
326 printNicely(magenta('I\'m afraid there is no result'))
333 t
= Twitter(auth
=authen())
334 t
.statuses
.update(status
=g
['stuff'])
341 t
= Twitter(auth
=authen())
343 id = int(g
['stuff'].split()[0])
345 printNicely(red('Sorry I can\'t understand.'))
347 tid
= c
['tweet_dict'][id]
348 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
356 t
= Twitter(auth
=authen())
358 id = int(g
['stuff'].split()[0])
360 printNicely(red('Sorry I can\'t understand.'))
362 tid
= c
['tweet_dict'][id]
363 tweet
= t
.statuses
.show(id=tid
)
365 formater
= format_quote(tweet
)
369 prefix
= light_magenta('Compose your ', rl
=True) + \
370 light_green('#comment: ', rl
=True)
371 comment
= raw_input(prefix
)
373 quote
= comment
.join(formater
.split('#comment'))
374 t
.statuses
.update(status
=quote
)
376 printNicely(light_magenta('No text added.'))
383 t
= Twitter(auth
=authen())
386 id = int(g
['stuff'].split()[0])
388 printNicely(red('Sorry I can\'t understand.'))
390 tid
= c
['tweet_dict'][id]
391 # Get display num if exist
393 num
= int(g
['stuff'].split()[1])
395 num
= c
['RETWEETS_SHOW_NUM']
396 # Get result and display
397 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
399 printNicely(magenta('This tweet has no retweet.'))
401 for tweet
in reversed(rt_ary
):
410 t
= Twitter(auth
=authen())
412 id = int(g
['stuff'].split()[0])
414 printNicely(red('Sorry I can\'t understand.'))
416 tid
= c
['tweet_dict'][id]
417 tweet
= t
.statuses
.show(id=tid
)
418 limit
= c
['CONVERSATION_MAX']
420 thread_ref
.append(tweet
)
421 prev_tid
= tweet
['in_reply_to_status_id']
422 while prev_tid
and limit
:
424 tweet
= t
.statuses
.show(id=prev_tid
)
425 prev_tid
= tweet
['in_reply_to_status_id']
426 thread_ref
.append(tweet
)
428 for tweet
in reversed(thread_ref
):
437 t
= Twitter(auth
=authen())
439 id = int(g
['stuff'].split()[0])
441 printNicely(red('Sorry I can\'t understand.'))
443 tid
= c
['tweet_dict'][id]
444 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
445 status
= ' '.join(g
['stuff'].split()[1:])
446 status
= '@' + user
+ ' ' + str2u(status
)
447 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
454 t
= Twitter(auth
=authen())
456 id = int(g
['stuff'].split()[0])
458 printNicely(red('Sorry I can\'t understand.'))
460 tid
= c
['tweet_dict'][id]
461 t
.favorites
.create(_id
=tid
, include_entities
=False)
462 printNicely(green('Favorited.'))
463 draw(t
.statuses
.show(id=tid
))
471 t
= Twitter(auth
=authen())
473 id = int(g
['stuff'].split()[0])
475 printNicely(red('Sorry I can\'t understand.'))
477 tid
= c
['tweet_dict'][id]
478 t
.favorites
.destroy(_id
=tid
)
479 printNicely(green('Okay it\'s unfavorited.'))
480 draw(t
.statuses
.show(id=tid
))
488 t
= Twitter(auth
=authen())
490 id = int(g
['stuff'].split()[0])
492 printNicely(red('Sorry I can\'t understand.'))
494 tid
= c
['tweet_dict'][id]
495 t
.statuses
.destroy(id=tid
)
496 printNicely(green('Okay it\'s gone.'))
503 t
= Twitter(auth
=authen())
505 target
= g
['stuff'].split()[0]
506 if target
!= 'image':
508 id = int(g
['stuff'].split()[1])
509 tid
= c
['tweet_dict'][id]
510 tweet
= t
.statuses
.show(id=tid
)
511 media
= tweet
['entities']['media']
513 res
= requests
.get(m
['media_url'])
514 img
= Image
.open(BytesIO(res
.content
))
518 printNicely(red('Sorry I can\'t show this image.'))
525 t
= Twitter(auth
=authen())
527 if not g
['stuff'].isdigit():
529 tid
= c
['tweet_dict'][int(g
['stuff'])]
530 tweet
= t
.statuses
.show(id=tid
)
531 link_prefix
= ('http://', 'https://')
532 link_ary
= [u
for u
in tweet
['text'].split()
533 if u
.startswith(link_prefix
)]
535 printNicely(light_magenta('No url here @.@!'))
537 for link
in link_ary
:
538 webbrowser
.open(link
)
541 printNicely(red('Sorry I can\'t open url in this tweet.'))
548 t
= Twitter(auth
=authen())
549 num
= c
['MESSAGES_DISPLAY']
550 if g
['stuff'].isdigit():
556 inbox
= inbox
+ t
.direct_messages(
559 include_entities
=False,
564 inbox
= inbox
+ t
.direct_messages(
567 include_entities
=False,
571 num
= c
['MESSAGES_DISPLAY']
572 if g
['stuff'].isdigit():
577 sent
= sent
+ t
.direct_messages
.sent(
580 include_entities
=False,
585 sent
= sent
+ t
.direct_messages
.sent(
588 include_entities
=False,
593 uniq_inbox
= list(set(
594 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
596 uniq_sent
= list(set(
597 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
599 for partner
in uniq_inbox
:
600 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
602 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
603 d
[partner
] = inbox_ary
+ sent_ary
604 for partner
in uniq_sent
:
607 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
608 g
['message_threads'] = print_threads(d
)
613 View a thread of message
616 thread_id
= int(g
['stuff'])
618 g
['message_threads'][thread_id
],
623 printNicely(red('No such thread.'))
628 Send a direct message
630 t
= Twitter(auth
=authen())
632 user
= g
['stuff'].split()[0]
633 if user
[0].startswith('@'):
634 content
= ' '.join(g
['stuff'].split()[1:])
635 t
.direct_messages
.new(
636 screen_name
=user
[1:],
639 printNicely(green('Message sent.'))
641 printNicely(red('A name should begin with a \'@\''))
644 printNicely(red('Sorry I can\'t understand.'))
651 t
= Twitter(auth
=authen())
653 id = int(g
['stuff'].split()[0])
655 printNicely(red('Sorry I can\'t understand.'))
656 mid
= c
['message_dict'][id]
657 t
.direct_messages
.destroy(id=mid
)
658 printNicely(green('Message deleted.'))
663 List friends for followers
665 t
= Twitter(auth
=authen())
668 name
= g
['stuff'].split()[1]
669 if name
.startswith('@'):
672 printNicely(red('A name should begin with a \'@\''))
673 raise Exception('Invalid name')
675 name
= g
['original_name']
676 # Get list followers or friends
678 target
= g
['stuff'].split()[0]
680 printNicely(red('Omg some syntax is wrong.'))
682 d
= {'fl': 'followers', 'fr': 'friends'}
686 while next_cursor
!= 0:
687 list = getattr(t
, d
[target
]).list(
691 include_entities
=False,
693 for u
in list['users']:
694 rel
[u
['name']] = '@' + u
['screen_name']
695 next_cursor
= list['next_cursor']
697 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
699 user
= ' ' + cycle_color(name
)
700 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
708 t
= Twitter(auth
=authen())
709 screen_name
= g
['stuff'].split()[0]
710 if screen_name
.startswith('@'):
711 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
712 printNicely(green('You are following ' + screen_name
+ ' now!'))
714 printNicely(red('A name should begin with a \'@\''))
721 t
= Twitter(auth
=authen())
722 screen_name
= g
['stuff'].split()[0]
723 if screen_name
.startswith('@'):
724 t
.friendships
.destroy(
725 screen_name
=screen_name
[1:],
726 include_entities
=False)
727 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
729 printNicely(red('A name should begin with a \'@\''))
736 t
= Twitter(auth
=authen())
738 screen_name
= g
['stuff'].split()[0]
740 printNicely(red('A name should be specified. '))
742 if screen_name
.startswith('@'):
744 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
745 if isinstance(rel
, dict):
746 printNicely(green(screen_name
+ ' is muted.'))
747 c
['IGNORE_LIST'] += [unc(screen_name
)]
748 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
750 printNicely(red(rel
))
753 printNicely(red('Something is wrong, can not mute now :('))
755 printNicely(red('A name should begin with a \'@\''))
762 t
= Twitter(auth
=authen())
764 screen_name
= g
['stuff'].split()[0]
766 printNicely(red('A name should be specified. '))
768 if screen_name
.startswith('@'):
770 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
771 if isinstance(rel
, dict):
772 printNicely(green(screen_name
+ ' is unmuted.'))
773 c
['IGNORE_LIST'].remove(screen_name
)
775 printNicely(red(rel
))
777 printNicely(red('Maybe you are not muting this person ?'))
779 printNicely(red('A name should begin with a \'@\''))
786 # Get dict of muting users
787 md
= build_mute_dict(dict_data
=True)
788 printNicely('All: ' + str(len(md
)) + ' people.')
790 user
= ' ' + cycle_color(md
[name
])
791 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
793 # Update from Twitter
794 c
['IGNORE_LIST'] = [n
for n
in md
]
801 t
= Twitter(auth
=authen())
802 screen_name
= g
['stuff'].split()[0]
803 if screen_name
.startswith('@'):
805 screen_name
=screen_name
[1:],
806 include_entities
=False,
808 printNicely(green('You blocked ' + screen_name
+ '.'))
810 printNicely(red('A name should begin with a \'@\''))
817 t
= Twitter(auth
=authen())
818 screen_name
= g
['stuff'].split()[0]
819 if screen_name
.startswith('@'):
821 screen_name
=screen_name
[1:],
822 include_entities
=False,
824 printNicely(green('Unblock ' + screen_name
+ ' success!'))
826 printNicely(red('A name should begin with a \'@\''))
831 Report a user as a spam account
833 t
= Twitter(auth
=authen())
834 screen_name
= g
['stuff'].split()[0]
835 if screen_name
.startswith('@'):
837 screen_name
=screen_name
[1:])
838 printNicely(green('You reported ' + screen_name
+ '.'))
840 printNicely(red('Sorry I can\'t understand.'))
848 list_name
= raw_input(
849 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
850 # Get list name and owner
852 owner
, slug
= list_name
.split('/')
853 if slug
.startswith('@'):
858 light_magenta('List name should follow "@owner/list_name" format.'))
859 raise Exception('Wrong list name')
866 rel
= t
.lists
.list(screen_name
=g
['original_name'])
870 printNicely(light_magenta('You belong to no lists :)'))
877 owner
, slug
= get_slug()
878 res
= t
.lists
.statuses(
880 owner_screen_name
=owner
,
882 include_entities
=False)
892 owner
, slug
= get_slug()
896 while next_cursor
!= 0:
899 owner_screen_name
=owner
,
901 include_entities
=False)
903 rel
[u
['name']] = '@' + u
['screen_name']
904 next_cursor
= m
['next_cursor']
905 printNicely('All: ' + str(len(rel
)) + ' members.')
907 user
= ' ' + cycle_color(name
)
908 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
912 def list_subscribers(t
):
916 owner
, slug
= get_slug()
920 while next_cursor
!= 0:
921 m
= t
.lists
.subscribers(
923 owner_screen_name
=owner
,
925 include_entities
=False)
927 rel
[u
['name']] = '@' + u
['screen_name']
928 next_cursor
= m
['next_cursor']
929 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
931 user
= ' ' + cycle_color(name
)
932 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
938 Add specific user to a list
940 owner
, slug
= get_slug()
942 user_name
= raw_input(
944 'Give me name of the newbie: ',
946 if user_name
.startswith('@'):
947 user_name
= user_name
[1:]
949 t
.lists
.members
.create(
951 owner_screen_name
=owner
,
952 screen_name
=user_name
)
953 printNicely(green('Added.'))
956 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
961 Remove specific user from a list
963 owner
, slug
= get_slug()
965 user_name
= raw_input(
967 'Give me name of the unlucky one: ',
969 if user_name
.startswith('@'):
970 user_name
= user_name
[1:]
972 t
.lists
.members
.destroy(
974 owner_screen_name
=owner
,
975 screen_name
=user_name
)
976 printNicely(green('Gone.'))
979 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
982 def list_subscribe(t
):
986 owner
, slug
= get_slug()
989 t
.lists
.subscribers
.create(
991 owner_screen_name
=owner
)
992 printNicely(green('Done.'))
996 light_magenta('I\'m sorry you can not subscribe to this list.'))
999 def list_unsubscribe(t
):
1003 owner
, slug
= get_slug()
1006 t
.lists
.subscribers
.destroy(
1008 owner_screen_name
=owner
)
1009 printNicely(green('Done.'))
1013 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1022 while next_cursor
!= 0:
1023 res
= t
.lists
.ownerships(
1024 screen_name
=g
['original_name'],
1027 next_cursor
= res
['next_cursor']
1031 printNicely(light_magenta('You own no lists :)'))
1038 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1041 'New list\'s mode (public/private): ',
1043 description
= raw_input(
1045 'New list\'s description: ',
1051 description
=description
)
1052 printNicely(green(name
+ ' list is created.'))
1055 printNicely(red('Oops something is wrong with Twitter :('))
1064 'Your list that you want to update: ',
1068 'Update name (leave blank to unchange): ',
1070 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1071 description
= raw_input(light_magenta('Update description: ', rl
=True))
1075 slug
='-'.join(slug
.split()),
1076 owner_screen_name
=g
['original_name'],
1079 description
=description
)
1083 owner_screen_name
=g
['original_name'],
1085 description
=description
)
1086 printNicely(green(slug
+ ' list is updated.'))
1089 printNicely(red('Oops something is wrong with Twitter :('))
1098 'Your list that you want to delete: ',
1102 slug
='-'.join(slug
.split()),
1103 owner_screen_name
=g
['original_name'])
1104 printNicely(green(slug
+ ' list is deleted.'))
1107 printNicely(red('Oops something is wrong with Twitter :('))
1114 t
= Twitter(auth
=authen())
1115 # List all lists or base on action
1117 g
['list_action'] = g
['stuff'].split()[0]
1124 'all_mem': list_members
,
1125 'all_sub': list_subscribers
,
1128 'sub': list_subscribe
,
1129 'unsub': list_unsubscribe
,
1132 'update': list_update
,
1136 return action_ary
[g
['list_action']](t
)
1138 printNicely(red('Please try again.'))
1146 target
= g
['stuff'].split()[0]
1148 args
= parse_arguments()
1150 if g
['stuff'].split()[-1] == '-f':
1151 guide
= 'To ignore an option, just hit Enter key.'
1152 printNicely(light_magenta(guide
))
1153 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1154 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1155 args
.filter = filter(None, only
.split(','))
1156 args
.ignore
= filter(None, ignore
.split(','))
1157 elif g
['stuff'].split()[-1] == '-d':
1158 args
.filter = c
['ONLY_LIST']
1159 args
.ignore
= c
['IGNORE_LIST']
1161 printNicely(red('Sorry, wrong format.'))
1164 if target
== 'public':
1165 keyword
= g
['stuff'].split()[1]
1166 if keyword
[0] == '#':
1167 keyword
= keyword
[1:]
1169 g
['stream_stop'] = True
1170 args
.track_keywords
= keyword
1172 th
= threading
.Thread(
1180 elif target
== 'mine':
1182 g
['stream_stop'] = True
1184 th
= threading
.Thread(
1189 g
['original_name']))
1192 # Stream base on list
1193 elif target
== 'list':
1194 owner
, slug
= get_slug()
1195 # Force python 2 not redraw readline buffer
1196 g
['cmd'] = '/'.join([owner
, slug
])
1197 printNicely(light_yellow('getting list members ...'))
1199 t
= Twitter(auth
=authen())
1202 while next_cursor
!= 0:
1203 m
= t
.lists
.members(
1205 owner_screen_name
=owner
,
1207 include_entities
=False)
1208 for u
in m
['users']:
1209 members
.append('@' + u
['screen_name'])
1210 next_cursor
= m
['next_cursor']
1211 printNicely(light_yellow('... done.'))
1212 # Build thread filter array
1213 args
.filter = members
1215 g
['stream_stop'] = True
1217 th
= threading
.Thread(
1227 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1229 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1233 printNicely(red('Sorry I can\'t understand.'))
1238 Unix's command `cal`
1241 rel
= os
.popen('cal').read().split('\n')
1244 show_calendar(month
, date
, rel
)
1249 List and change theme
1253 for theme
in g
['themes']:
1254 line
= light_magenta(theme
)
1255 if c
['THEME'] == theme
:
1256 line
= ' ' * 2 + light_yellow('* ') + line
1258 line
= ' ' * 4 + line
1264 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1265 # Redefine decorated_name
1266 g
['decorated_name'] = lambda x
: color_func(
1267 c
['DECORATED_NAME'])(
1269 printNicely(green('Theme changed.'))
1271 printNicely(red('No such theme exists.'))
1276 Browse and change config
1278 all_config
= get_all_config()
1279 g
['stuff'] = g
['stuff'].strip()
1282 for k
in all_config
:
1284 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1286 guide
= 'Detailed explanation can be found at ' + \
1287 color_func(c
['TWEET']['link'])(
1288 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1290 # Print specific config
1291 elif len(g
['stuff'].split()) == 1:
1292 if g
['stuff'] in all_config
:
1295 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1298 printNicely(red('No such config key.'))
1299 # Print specific config's default value
1300 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1301 key
= g
['stuff'].split()[0]
1303 value
= get_default_config(key
)
1304 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1306 except Exception as e
:
1308 # Delete specific config key in config file
1309 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1310 key
= g
['stuff'].split()[0]
1313 printNicely(green('Config key is dropped.'))
1314 except Exception as e
:
1316 # Set specific config
1317 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1318 key
= g
['stuff'].split()[0]
1319 value
= g
['stuff'].split()[-1]
1320 if key
== 'THEME' and not validate_theme(value
):
1321 printNicely(red('Invalid theme\'s value.'))
1324 set_config(key
, value
)
1325 # Apply theme immediately
1327 c
['THEME'] = reload_theme(value
, c
['THEME'])
1328 g
['decorated_name'] = lambda x
: color_func(
1329 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1331 printNicely(green('Updated successfully.'))
1332 except Exception as e
:
1335 printNicely(light_magenta('Sorry I can\'s understand.'))
1338 def help_discover():
1343 # Discover the world
1345 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1346 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1347 'You can try ' + light_green('trend US') + ' or ' + \
1348 light_green('trend JP Tokyo') + '.\n'
1349 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1350 light_green('home 7') + ' will show 7 tweets.\n'
1352 light_green('notification') + ' will show your recent notification.\n'
1353 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1354 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1355 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1356 magenta('@mdo') + '.\n'
1357 usage
+= s
* 2 + light_green('view @mdo') + \
1358 ' will show ' + magenta('@mdo') + '\'s home.\n'
1359 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1360 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1361 'Search can be performed with or without hashtag.\n'
1372 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1373 usage
+= s
* 2 + light_green('t oops ') + \
1374 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1376 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1377 light_yellow('[id=12]') + '.\n'
1379 light_green('quote 12 ') + ' will quote the tweet with ' + \
1380 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1381 'the quote will be canceled.\n'
1383 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1384 light_yellow('[id=12]') + '.\n'
1385 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1386 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1387 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1388 light_yellow('oops') + '" to tweet with ' + \
1389 light_yellow('[id=12]') + '.\n'
1391 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1392 light_yellow('[id=12]') + '.\n'
1394 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1395 light_yellow('[id=12]') + '.\n'
1397 light_green('del 12 ') + ' will delete tweet with ' + \
1398 light_yellow('[id=12]') + '.\n'
1399 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1400 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1401 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1402 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1406 def help_messages():
1413 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1414 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1415 light_green('inbox 7') + ' will show newest 7 messages.\n'
1416 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1417 light_yellow('[thread_id=2]') + '.\n'
1418 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1419 magenta('@dtvd88') + '.\n'
1420 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1421 light_yellow('[message_id=5]') + '.\n'
1425 def help_friends_and_followers():
1427 Friends and Followers
1430 # Follower and following
1432 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1434 light_green('ls fl') + \
1435 ' will list all followers (people who are following you).\n'
1437 light_green('ls fr') + \
1438 ' will list all friends (people who you are following).\n'
1439 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1440 magenta('@dtvd88') + '.\n'
1441 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1442 magenta('@dtvd88') + '.\n'
1443 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1444 magenta('@dtvd88') + '.\n'
1445 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1446 magenta('@dtvd88') + '.\n'
1447 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1448 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1449 magenta('@dtvd88') + '.\n'
1450 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1451 magenta('@dtvd88') + '.\n'
1452 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1453 magenta('@dtvd88') + ' as a spam account.\n'
1464 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1465 usage
+= s
* 2 + light_green('list') + \
1466 ' will show all lists you are belong to.\n'
1467 usage
+= s
* 2 + light_green('list home') + \
1468 ' will show timeline of list. You will be asked for list\'s name.\n'
1469 usage
+= s
* 2 + light_green('list all_mem') + \
1470 ' will show list\'s all members.\n'
1471 usage
+= s
* 2 + light_green('list all_sub') + \
1472 ' will show list\'s all subscribers.\n'
1473 usage
+= s
* 2 + light_green('list add') + \
1474 ' will add specific person to a list owned by you.' + \
1475 ' You will be asked for list\'s name and person\'s name.\n'
1476 usage
+= s
* 2 + light_green('list rm') + \
1477 ' will remove specific person from a list owned by you.' + \
1478 ' You will be asked for list\'s name and person\'s name.\n'
1479 usage
+= s
* 2 + light_green('list sub') + \
1480 ' will subscribe you to a specific list.\n'
1481 usage
+= s
* 2 + light_green('list unsub') + \
1482 ' will unsubscribe you from a specific list.\n'
1483 usage
+= s
* 2 + light_green('list own') + \
1484 ' will show all list owned by you.\n'
1485 usage
+= s
* 2 + light_green('list new') + \
1486 ' will create a new list.\n'
1487 usage
+= s
* 2 + light_green('list update') + \
1488 ' will update a list owned by you.\n'
1489 usage
+= s
* 2 + light_green('list del') + \
1490 ' will delete a list owned by you.\n'
1501 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1502 usage
+= s
* 2 + light_green('switch public #AKB') + \
1503 ' will switch to public stream and follow "' + \
1504 light_yellow('AKB') + '" keyword.\n'
1505 usage
+= s
* 2 + light_green('switch mine') + \
1506 ' will switch to your personal stream.\n'
1507 usage
+= s
* 2 + light_green('switch mine -f ') + \
1508 ' will prompt to enter the filter.\n'
1509 usage
+= s
* 3 + light_yellow('Only nicks') + \
1510 ' filter will decide nicks will be INCLUDE ONLY.\n'
1511 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1512 ' filter will decide nicks will be EXCLUDE.\n'
1513 usage
+= s
* 2 + light_green('switch mine -d') + \
1514 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1515 usage
+= s
* 2 + light_green('switch list') + \
1516 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1525 h
, w
= os
.popen('stty size', 'r').read().split()
1528 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1529 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1530 usage
+= s
+ 'You are ' + \
1531 light_yellow('already') + ' on your personal stream.\n'
1532 usage
+= s
+ 'Any update from Twitter will show up ' + \
1533 light_yellow('immediately') + '.\n'
1534 usage
+= s
+ 'In addition, following commands are available right now:\n'
1535 # Twitter help section
1537 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1538 usage
+= s
* 2 + light_green('h discover') + \
1539 ' will show help for discover commands.\n'
1540 usage
+= s
* 2 + light_green('h tweets') + \
1541 ' will show help for tweets commands.\n'
1542 usage
+= s
* 2 + light_green('h messages') + \
1543 ' will show help for messages commands.\n'
1544 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1545 ' will show help for friends and followers commands.\n'
1546 usage
+= s
* 2 + light_green('h list') + \
1547 ' will show help for list commands.\n'
1548 usage
+= s
* 2 + light_green('h stream') + \
1549 ' will show help for stream commands.\n'
1552 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1553 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1554 'will be evaluate by Python interpreter.\n'
1555 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1556 ' for current month.\n'
1559 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1560 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1561 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1562 ' theme immediately.\n'
1563 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1565 light_green('config ASCII_ART') + ' will output current value of ' +\
1566 light_yellow('ASCII_ART') + ' config key.\n'
1568 light_green('config TREND_MAX default') + ' will output default value of ' + \
1569 light_yellow('TREND_MAX') + ' config key.\n'
1571 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1572 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1574 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1575 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1576 light_yellow('True') + '.\n'
1579 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1580 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1581 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1582 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1583 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1584 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1587 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1588 usage
+= s
+ 'Have fun and hang tight! \n'
1591 'discover': help_discover
,
1592 'tweets': help_tweets
,
1593 'messages': help_messages
,
1594 'friends_and_followers': help_friends_and_followers
,
1596 'stream': help_stream
,
1601 lambda: printNicely(red('No such command.'))
1609 Pause stream display
1612 printNicely(green('Stream is paused'))
1620 printNicely(green('Stream is running back now'))
1636 printNicely(green('See you next time :)'))
1644 Reset prefix of line
1647 if c
.get('USER_JSON_ERROR'):
1648 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1649 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1651 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1654 printNicely(str(eval(g
['cmd'])))
1704 # Handle function set
1754 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1759 Listen to user's input
1764 ['public', 'mine', 'list'], # switch
1781 ['image'], # show image
1783 ['fl', 'fr'], # list
1785 [i
for i
in g
['message_threads']], # sent
1810 [key
for key
in dict(get_all_config())], # config
1811 g
['themes'], # theme
1816 'friends_and_followers',
1826 init_interactive_shell(d
)
1833 # Only use PREFIX as a string with raw_input
1834 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1837 # Save cmd to compare with readline buffer
1838 g
['cmd'] = line
.strip()
1839 # Get short cmd to pass to handle function
1841 cmd
= line
.split()[0]
1844 # Lock the semaphore
1846 # Save cmd to global variable and call process
1847 g
['stuff'] = ' '.join(line
.split()[1:])
1848 # Process the command
1851 if cmd
in ['switch', 't', 'rt', 'rep']:
1855 # Release the semaphore lock
1861 printNicely(red('OMG something is wrong with Twitter right now.'))
1864 def stream(domain
, args
, name
='Rainbow Stream'):
1870 c
['USER_DOMAIN']: name
,
1871 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1872 c
['SITE_DOMAIN']: name
,
1875 ascii_art(art_dict
[domain
])
1876 # These arguments are optional:
1878 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1880 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1883 if args
.track_keywords
:
1884 query_args
['track'] = args
.track_keywords
1886 stream
= TwitterStream(
1891 if domain
== c
['USER_DOMAIN']:
1892 tweet_iter
= stream
.user(**query_args
)
1893 elif domain
== c
['SITE_DOMAIN']:
1894 tweet_iter
= stream
.site(**query_args
)
1896 if args
.track_keywords
:
1897 tweet_iter
= stream
.statuses
.filter(**query_args
)
1899 tweet_iter
= stream
.statuses
.sample()
1900 # Block new stream until other one exits
1901 StreamLock
.acquire()
1902 g
['stream_stop'] = False
1903 for tweet
in tweet_iter
:
1905 printNicely("-- None --")
1906 elif tweet
is Timeout
:
1907 if(g
['stream_stop']):
1908 StreamLock
.release()
1910 elif tweet
is HeartbeatTimeout
:
1911 printNicely("-- Heartbeat Timeout --")
1912 guide
= light_magenta("You can use ") + \
1913 light_green("switch") + \
1914 light_magenta(" command to return to your stream.\n")
1915 guide
+= light_magenta("Type ") + \
1916 light_green("h stream") + \
1917 light_magenta(" for more details.")
1919 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1921 StreamLock
.release()
1923 elif tweet
is Hangup
:
1924 printNicely("-- Hangup --")
1925 elif tweet
.get('text'):
1926 # Check the semaphore pause and lock (stream process only)
1934 keyword
=args
.track_keywords
,
1939 # Current readline buffer
1940 current_buffer
= readline
.get_line_buffer().strip()
1941 # There is an unexpected behaviour in MacOSX readline + Python 2:
1942 # after completely delete a word after typing it,
1943 # somehow readline buffer still contains
1944 # the 1st character of that word
1945 if current_buffer
and g
['cmd'] != current_buffer
:
1947 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1949 elif not c
['HIDE_PROMPT']:
1950 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1952 elif tweet
.get('direct_message'):
1953 # Check the semaphore pause and lock (stream process only)
1958 print_message(tweet
['direct_message'])
1959 elif tweet
.get('event'):
1960 c
['events'].append(tweet
)
1962 except TwitterHTTPError
:
1965 magenta("We have maximum connection problem with twitter'stream API right now :("))
1973 args
= parse_arguments()
1976 except TwitterHTTPError
:
1979 magenta("We have connection problem with twitter'stream API right now :("))
1980 printNicely(magenta("Let's try again later."))
1983 # Spawn stream thread
1984 th
= threading
.Thread(
1989 g
['original_name']))
1992 # Start listen process