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'] = {}
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 ') + light_green('#comment: ')
370 comment
= raw_input(prefix
)
372 quote
= comment
.join(formater
.split('#comment'))
373 t
.statuses
.update(status
=quote
)
375 printNicely(light_magenta('No text added.'))
382 t
= Twitter(auth
=authen())
385 id = int(g
['stuff'].split()[0])
387 printNicely(red('Sorry I can\'t understand.'))
389 tid
= c
['tweet_dict'][id]
390 # Get display num if exist
392 num
= int(g
['stuff'].split()[1])
394 num
= c
['RETWEETS_SHOW_NUM']
395 # Get result and display
396 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
398 printNicely(magenta('This tweet has no retweet.'))
400 for tweet
in reversed(rt_ary
):
409 t
= Twitter(auth
=authen())
411 id = int(g
['stuff'].split()[0])
413 printNicely(red('Sorry I can\'t understand.'))
415 tid
= c
['tweet_dict'][id]
416 tweet
= t
.statuses
.show(id=tid
)
417 limit
= c
['CONVERSATION_MAX']
419 thread_ref
.append(tweet
)
420 prev_tid
= tweet
['in_reply_to_status_id']
421 while prev_tid
and limit
:
423 tweet
= t
.statuses
.show(id=prev_tid
)
424 prev_tid
= tweet
['in_reply_to_status_id']
425 thread_ref
.append(tweet
)
427 for tweet
in reversed(thread_ref
):
436 t
= Twitter(auth
=authen())
438 id = int(g
['stuff'].split()[0])
440 printNicely(red('Sorry I can\'t understand.'))
442 tid
= c
['tweet_dict'][id]
443 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
444 status
= ' '.join(g
['stuff'].split()[1:])
445 status
= '@' + user
+ ' ' + str2u(status
)
446 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
453 t
= Twitter(auth
=authen())
455 id = int(g
['stuff'].split()[0])
457 printNicely(red('Sorry I can\'t understand.'))
459 tid
= c
['tweet_dict'][id]
460 t
.favorites
.create(_id
=tid
, include_entities
=False)
461 printNicely(green('Favorited.'))
462 draw(t
.statuses
.show(id=tid
))
470 t
= Twitter(auth
=authen())
472 id = int(g
['stuff'].split()[0])
474 printNicely(red('Sorry I can\'t understand.'))
476 tid
= c
['tweet_dict'][id]
477 t
.favorites
.destroy(_id
=tid
)
478 printNicely(green('Okay it\'s unfavorited.'))
479 draw(t
.statuses
.show(id=tid
))
487 t
= Twitter(auth
=authen())
489 id = int(g
['stuff'].split()[0])
491 printNicely(red('Sorry I can\'t understand.'))
493 tid
= c
['tweet_dict'][id]
494 t
.statuses
.destroy(id=tid
)
495 printNicely(green('Okay it\'s gone.'))
502 t
= Twitter(auth
=authen())
504 target
= g
['stuff'].split()[0]
505 if target
!= 'image':
507 id = int(g
['stuff'].split()[1])
508 tid
= c
['tweet_dict'][id]
509 tweet
= t
.statuses
.show(id=tid
)
510 media
= tweet
['entities']['media']
512 res
= requests
.get(m
['media_url'])
513 img
= Image
.open(BytesIO(res
.content
))
517 printNicely(red('Sorry I can\'t show this image.'))
524 t
= Twitter(auth
=authen())
526 if not g
['stuff'].isdigit():
528 tid
= c
['tweet_dict'][int(g
['stuff'])]
529 tweet
= t
.statuses
.show(id=tid
)
530 link_prefix
= ('http://', 'https://')
531 link_ary
= [u
for u
in tweet
['text'].split()
532 if u
.startswith(link_prefix
)]
534 printNicely(light_magenta('No url here @.@!'))
536 for link
in link_ary
:
537 webbrowser
.open(link
)
540 printNicely(red('Sorry I can\'t open url in this tweet.'))
547 t
= Twitter(auth
=authen())
548 num
= c
['MESSAGES_DISPLAY']
549 if g
['stuff'].isdigit():
555 inbox
= inbox
+ t
.direct_messages(
558 include_entities
=False,
563 inbox
= inbox
+ t
.direct_messages(
566 include_entities
=False,
570 num
= c
['MESSAGES_DISPLAY']
571 if g
['stuff'].isdigit():
576 sent
= sent
+ t
.direct_messages
.sent(
579 include_entities
=False,
584 sent
= sent
+ t
.direct_messages
.sent(
587 include_entities
=False,
592 uniq_inbox
= list(set(
593 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
595 uniq_sent
= list(set(
596 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
598 for partner
in uniq_inbox
:
599 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
601 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
602 d
[partner
] = inbox_ary
+ sent_ary
603 for partner
in uniq_sent
:
606 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
607 g
['message_threads'] = print_threads(d
)
612 View a thread of message
615 thread_id
= int(g
['stuff'])
617 g
['message_threads'][thread_id
],
622 printNicely(red('No such thread.'))
627 Send a direct message
629 t
= Twitter(auth
=authen())
631 user
= g
['stuff'].split()[0]
632 if user
[0].startswith('@'):
633 content
= ' '.join(g
['stuff'].split()[1:])
634 t
.direct_messages
.new(
635 screen_name
=user
[1:],
638 printNicely(green('Message sent.'))
640 printNicely(red('A name should begin with a \'@\''))
643 printNicely(red('Sorry I can\'t understand.'))
650 t
= Twitter(auth
=authen())
652 id = int(g
['stuff'].split()[0])
654 printNicely(red('Sorry I can\'t understand.'))
655 mid
= c
['message_dict'][id]
656 t
.direct_messages
.destroy(id=mid
)
657 printNicely(green('Message deleted.'))
662 List friends for followers
664 t
= Twitter(auth
=authen())
667 name
= g
['stuff'].split()[1]
668 if name
.startswith('@'):
671 printNicely(red('A name should begin with a \'@\''))
672 raise Exception('Invalid name')
674 name
= g
['original_name']
675 # Get list followers or friends
677 target
= g
['stuff'].split()[0]
679 printNicely(red('Omg some syntax is wrong.'))
681 d
= {'fl': 'followers', 'fr': 'friends'}
685 while next_cursor
!= 0:
686 list = getattr(t
, d
[target
]).list(
690 include_entities
=False,
692 for u
in list['users']:
693 rel
[u
['name']] = '@' + u
['screen_name']
694 next_cursor
= list['next_cursor']
696 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
698 user
= ' ' + cycle_color(name
)
699 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
707 t
= Twitter(auth
=authen())
708 screen_name
= g
['stuff'].split()[0]
709 if screen_name
.startswith('@'):
710 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
711 printNicely(green('You are following ' + screen_name
+ ' now!'))
713 printNicely(red('A name should begin with a \'@\''))
720 t
= Twitter(auth
=authen())
721 screen_name
= g
['stuff'].split()[0]
722 if screen_name
.startswith('@'):
723 t
.friendships
.destroy(
724 screen_name
=screen_name
[1:],
725 include_entities
=False)
726 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
728 printNicely(red('A name should begin with a \'@\''))
735 t
= Twitter(auth
=authen())
737 screen_name
= g
['stuff'].split()[0]
739 printNicely(red('A name should be specified. '))
741 if screen_name
.startswith('@'):
743 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
744 if isinstance(rel
, dict):
745 printNicely(green(screen_name
+ ' is muted.'))
746 c
['IGNORE_LIST'] += [unc(screen_name
)]
747 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
749 printNicely(red(rel
))
752 printNicely(red('Something is wrong, can not mute now :('))
754 printNicely(red('A name should begin with a \'@\''))
761 t
= Twitter(auth
=authen())
763 screen_name
= g
['stuff'].split()[0]
765 printNicely(red('A name should be specified. '))
767 if screen_name
.startswith('@'):
769 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
770 if isinstance(rel
, dict):
771 printNicely(green(screen_name
+ ' is unmuted.'))
772 c
['IGNORE_LIST'].remove(screen_name
)
774 printNicely(red(rel
))
776 printNicely(red('Maybe you are not muting this person ?'))
778 printNicely(red('A name should begin with a \'@\''))
785 # Get dict of muting users
786 md
= build_mute_dict(dict_data
=True)
787 printNicely('All: ' + str(len(md
)) + ' people.')
789 user
= ' ' + cycle_color(md
[name
])
790 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
792 # Update from Twitter
793 c
['IGNORE_LIST'] = [n
for n
in md
]
800 t
= Twitter(auth
=authen())
801 screen_name
= g
['stuff'].split()[0]
802 if screen_name
.startswith('@'):
804 screen_name
=screen_name
[1:],
805 include_entities
=False,
807 printNicely(green('You blocked ' + screen_name
+ '.'))
809 printNicely(red('A name should begin with a \'@\''))
816 t
= Twitter(auth
=authen())
817 screen_name
= g
['stuff'].split()[0]
818 if screen_name
.startswith('@'):
820 screen_name
=screen_name
[1:],
821 include_entities
=False,
823 printNicely(green('Unblock ' + screen_name
+ ' success!'))
825 printNicely(red('A name should begin with a \'@\''))
830 Report a user as a spam account
832 t
= Twitter(auth
=authen())
833 screen_name
= g
['stuff'].split()[0]
834 if screen_name
.startswith('@'):
836 screen_name
=screen_name
[1:])
837 printNicely(green('You reported ' + screen_name
+ '.'))
839 printNicely(red('Sorry I can\'t understand.'))
847 list_name
= raw_input(light_magenta('Give me the list\'s name ("@owner/list_name"): '))
848 # Get list name and owner
850 owner
, slug
= list_name
.split('/')
851 if slug
.startswith('@'):
856 light_magenta('List name should follow "@owner/list_name" format.'))
857 raise Exception('Wrong list name')
864 rel
= t
.lists
.list(screen_name
=g
['original_name'])
868 printNicely(light_magenta('You belong to no lists :)'))
875 owner
, slug
= get_slug()
876 res
= t
.lists
.statuses(
878 owner_screen_name
=owner
,
880 include_entities
=False)
890 owner
, slug
= get_slug()
894 while next_cursor
!= 0:
897 owner_screen_name
=owner
,
899 include_entities
=False)
901 rel
[u
['name']] = '@' + u
['screen_name']
902 next_cursor
= m
['next_cursor']
903 printNicely('All: ' + str(len(rel
)) + ' members.')
905 user
= ' ' + cycle_color(name
)
906 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
910 def list_subscribers(t
):
914 owner
, slug
= get_slug()
918 while next_cursor
!= 0:
919 m
= t
.lists
.subscribers(
921 owner_screen_name
=owner
,
923 include_entities
=False)
925 rel
[u
['name']] = '@' + u
['screen_name']
926 next_cursor
= m
['next_cursor']
927 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
929 user
= ' ' + cycle_color(name
)
930 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
936 Add specific user to a list
938 owner
, slug
= get_slug()
940 user_name
= raw_input(light_magenta('Give me name of the newbie: '))
941 if user_name
.startswith('@'):
942 user_name
= user_name
[1:]
944 t
.lists
.members
.create(
946 owner_screen_name
=owner
,
947 screen_name
=user_name
)
948 printNicely(green('Added.'))
951 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
956 Remove specific user from a list
958 owner
, slug
= get_slug()
960 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
961 if user_name
.startswith('@'):
962 user_name
= user_name
[1:]
964 t
.lists
.members
.destroy(
966 owner_screen_name
=owner
,
967 screen_name
=user_name
)
968 printNicely(green('Gone.'))
971 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
974 def list_subscribe(t
):
978 owner
, slug
= get_slug()
981 t
.lists
.subscribers
.create(
983 owner_screen_name
=owner
)
984 printNicely(green('Done.'))
988 light_magenta('I\'m sorry you can not subscribe to this list.'))
991 def list_unsubscribe(t
):
995 owner
, slug
= get_slug()
998 t
.lists
.subscribers
.destroy(
1000 owner_screen_name
=owner
)
1001 printNicely(green('Done.'))
1005 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1014 while next_cursor
!= 0:
1015 res
= t
.lists
.ownerships(
1016 screen_name
=g
['original_name'],
1019 next_cursor
= res
['next_cursor']
1023 printNicely(light_magenta('You own no lists :)'))
1030 name
= raw_input(light_magenta('New list\'s name: '))
1031 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1032 description
= raw_input(light_magenta('New list\'s description: '))
1037 description
=description
)
1038 printNicely(green(name
+ ' list is created.'))
1041 printNicely(red('Oops something is wrong with Twitter :('))
1048 slug
= raw_input(light_magenta('Your list that you want to update: '))
1049 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1050 mode
= raw_input(light_magenta('Update mode (public/private): '))
1051 description
= raw_input(light_magenta('Update description: '))
1055 slug
='-'.join(slug
.split()),
1056 owner_screen_name
=g
['original_name'],
1059 description
=description
)
1063 owner_screen_name
=g
['original_name'],
1065 description
=description
)
1066 printNicely(green(slug
+ ' list is updated.'))
1069 printNicely(red('Oops something is wrong with Twitter :('))
1076 slug
= raw_input(light_magenta('Your list that you want to delete: '))
1079 slug
='-'.join(slug
.split()),
1080 owner_screen_name
=g
['original_name'])
1081 printNicely(green(slug
+ ' list is deleted.'))
1084 printNicely(red('Oops something is wrong with Twitter :('))
1091 t
= Twitter(auth
=authen())
1092 # List all lists or base on action
1094 g
['list_action'] = g
['stuff'].split()[0]
1101 'all_mem': list_members
,
1102 'all_sub': list_subscribers
,
1105 'sub': list_subscribe
,
1106 'unsub': list_unsubscribe
,
1109 'update': list_update
,
1113 return action_ary
[g
['list_action']](t
)
1115 printNicely(red('Please try again.'))
1123 target
= g
['stuff'].split()[0]
1125 args
= parse_arguments()
1127 if g
['stuff'].split()[-1] == '-f':
1128 guide
= 'To ignore an option, just hit Enter key.'
1129 printNicely(light_magenta(guide
))
1130 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1131 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1132 args
.filter = filter(None, only
.split(','))
1133 args
.ignore
= filter(None, ignore
.split(','))
1134 elif g
['stuff'].split()[-1] == '-d':
1135 args
.filter = c
['ONLY_LIST']
1136 args
.ignore
= c
['IGNORE_LIST']
1138 printNicely(red('Sorry, wrong format.'))
1141 if target
== 'public':
1142 keyword
= g
['stuff'].split()[1]
1143 if keyword
[0] == '#':
1144 keyword
= keyword
[1:]
1146 g
['stream_stop'] = True
1147 args
.track_keywords
= keyword
1149 th
= threading
.Thread(
1157 elif target
== 'mine':
1159 g
['stream_stop'] = True
1161 th
= threading
.Thread(
1166 g
['original_name']))
1169 # Stream base on list
1170 elif target
== 'list':
1171 owner
, slug
= get_slug()
1172 # Force python 2 not redraw readline buffer
1173 g
['cmd'] = '/'.join([owner
,slug
])
1174 printNicely(light_yellow('getting list members ...'))
1176 t
= Twitter(auth
=authen())
1179 while next_cursor
!= 0:
1180 m
= t
.lists
.members(
1182 owner_screen_name
=owner
,
1184 include_entities
=False)
1185 for u
in m
['users']:
1186 members
.append('@' + u
['screen_name'])
1187 next_cursor
= m
['next_cursor']
1188 printNicely(light_yellow('... done.'))
1189 # Build thread filter array
1190 args
.filter = members
1192 g
['stream_stop'] = True
1194 th
= threading
.Thread(
1204 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1206 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1210 printNicely(red('Sorry I can\'t understand.'))
1215 Unix's command `cal`
1218 rel
= os
.popen('cal').read().split('\n')
1221 show_calendar(month
, date
, rel
)
1226 List and change theme
1230 for theme
in g
['themes']:
1231 line
= light_magenta(theme
)
1232 if c
['THEME'] == theme
:
1233 line
= ' ' * 2 + light_yellow('* ') + line
1235 line
= ' ' * 4 + line
1241 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1242 # Redefine decorated_name
1243 g
['decorated_name'] = lambda x
: color_func(
1244 c
['DECORATED_NAME'])(
1246 printNicely(green('Theme changed.'))
1248 printNicely(red('No such theme exists.'))
1253 Browse and change config
1255 all_config
= get_all_config()
1256 g
['stuff'] = g
['stuff'].strip()
1259 for k
in all_config
:
1261 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1263 guide
= 'Detailed explanation can be found at ' + \
1264 color_func(c
['TWEET']['link'])(
1265 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1267 # Print specific config
1268 elif len(g
['stuff'].split()) == 1:
1269 if g
['stuff'] in all_config
:
1272 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1275 printNicely(red('No such config key.'))
1276 # Print specific config's default value
1277 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1278 key
= g
['stuff'].split()[0]
1280 value
= get_default_config(key
)
1281 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1283 except Exception as e
:
1285 # Delete specific config key in config file
1286 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1287 key
= g
['stuff'].split()[0]
1290 printNicely(green('Config key is dropped.'))
1291 except Exception as e
:
1293 # Set specific config
1294 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1295 key
= g
['stuff'].split()[0]
1296 value
= g
['stuff'].split()[-1]
1297 if key
== 'THEME' and not validate_theme(value
):
1298 printNicely(red('Invalid theme\'s value.'))
1301 set_config(key
, value
)
1302 # Apply theme immediately
1304 c
['THEME'] = reload_theme(value
, c
['THEME'])
1305 g
['decorated_name'] = lambda x
: color_func(
1306 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1308 printNicely(green('Updated successfully.'))
1309 except Exception as e
:
1312 printNicely(light_magenta('Sorry I can\'s understand.'))
1315 def help_discover():
1320 # Discover the world
1322 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1323 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1324 'You can try ' + light_green('trend US') + ' or ' + \
1325 light_green('trend JP Tokyo') + '.\n'
1326 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1327 light_green('home 7') + ' will show 7 tweets.\n'
1329 light_green('notification') + ' will show your recent notification.\n'
1330 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1331 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1332 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1333 magenta('@mdo') + '.\n'
1334 usage
+= s
* 2 + light_green('view @mdo') + \
1335 ' will show ' + magenta('@mdo') + '\'s home.\n'
1336 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1337 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1338 'Search can be performed with or without hashtag.\n'
1349 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1350 usage
+= s
* 2 + light_green('t oops ') + \
1351 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1353 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1354 light_yellow('[id=12]') + '.\n'
1356 light_green('quote 12 ') + ' will quote the tweet with ' + \
1357 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1358 'the quote will be canceled.\n'
1360 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1361 light_yellow('[id=12]') + '.\n'
1362 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1363 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1364 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1365 light_yellow('oops') + '" to tweet with ' + \
1366 light_yellow('[id=12]') + '.\n'
1368 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1369 light_yellow('[id=12]') + '.\n'
1371 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1372 light_yellow('[id=12]') + '.\n'
1374 light_green('del 12 ') + ' will delete tweet with ' + \
1375 light_yellow('[id=12]') + '.\n'
1376 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1377 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1378 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1379 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1383 def help_messages():
1390 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1391 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1392 light_green('inbox 7') + ' will show newest 7 messages.\n'
1393 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1394 light_yellow('[thread_id=2]') + '.\n'
1395 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1396 magenta('@dtvd88') + '.\n'
1397 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1398 light_yellow('[message_id=5]') + '.\n'
1402 def help_friends_and_followers():
1404 Friends and Followers
1407 # Follower and following
1409 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1411 light_green('ls fl') + \
1412 ' will list all followers (people who are following you).\n'
1414 light_green('ls fr') + \
1415 ' will list all friends (people who you are following).\n'
1416 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1417 magenta('@dtvd88') + '.\n'
1418 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1419 magenta('@dtvd88') + '.\n'
1420 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1421 magenta('@dtvd88') + '.\n'
1422 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1423 magenta('@dtvd88') + '.\n'
1424 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1425 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1426 magenta('@dtvd88') + '.\n'
1427 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1428 magenta('@dtvd88') + '.\n'
1429 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1430 magenta('@dtvd88') + ' as a spam account.\n'
1441 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1442 usage
+= s
* 2 + light_green('list') + \
1443 ' will show all lists you are belong to.\n'
1444 usage
+= s
* 2 + light_green('list home') + \
1445 ' will show timeline of list. You will be asked for list\'s name.\n'
1446 usage
+= s
* 2 + light_green('list all_mem') + \
1447 ' will show list\'s all members.\n'
1448 usage
+= s
* 2 + light_green('list all_sub') + \
1449 ' will show list\'s all subscribers.\n'
1450 usage
+= s
* 2 + light_green('list add') + \
1451 ' will add specific person to a list owned by you.' + \
1452 ' You will be asked for list\'s name and person\'s name.\n'
1453 usage
+= s
* 2 + light_green('list rm') + \
1454 ' will remove specific person from a list owned by you.' + \
1455 ' You will be asked for list\'s name and person\'s name.\n'
1456 usage
+= s
* 2 + light_green('list sub') + \
1457 ' will subscribe you to a specific list.\n'
1458 usage
+= s
* 2 + light_green('list unsub') + \
1459 ' will unsubscribe you from a specific list.\n'
1460 usage
+= s
* 2 + light_green('list own') + \
1461 ' will show all list owned by you.\n'
1462 usage
+= s
* 2 + light_green('list new') + \
1463 ' will create a new list.\n'
1464 usage
+= s
* 2 + light_green('list update') + \
1465 ' will update a list owned by you.\n'
1466 usage
+= s
* 2 + light_green('list del') + \
1467 ' will delete a list owned by you.\n'
1478 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1479 usage
+= s
* 2 + light_green('switch public #AKB') + \
1480 ' will switch to public stream and follow "' + \
1481 light_yellow('AKB') + '" keyword.\n'
1482 usage
+= s
* 2 + light_green('switch mine') + \
1483 ' will switch to your personal stream.\n'
1484 usage
+= s
* 2 + light_green('switch mine -f ') + \
1485 ' will prompt to enter the filter.\n'
1486 usage
+= s
* 3 + light_yellow('Only nicks') + \
1487 ' filter will decide nicks will be INCLUDE ONLY.\n'
1488 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1489 ' filter will decide nicks will be EXCLUDE.\n'
1490 usage
+= s
* 2 + light_green('switch mine -d') + \
1491 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1492 usage
+= s
* 2 + light_green('switch list') + \
1493 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1502 h
, w
= os
.popen('stty size', 'r').read().split()
1505 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1506 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1507 usage
+= s
+ 'You are ' + \
1508 light_yellow('already') + ' on your personal stream.\n'
1509 usage
+= s
+ 'Any update from Twitter will show up ' + \
1510 light_yellow('immediately') + '.\n'
1511 usage
+= s
+ 'In addition, following commands are available right now:\n'
1512 # Twitter help section
1514 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1515 usage
+= s
* 2 + light_green('h discover') + \
1516 ' will show help for discover commands.\n'
1517 usage
+= s
* 2 + light_green('h tweets') + \
1518 ' will show help for tweets commands.\n'
1519 usage
+= s
* 2 + light_green('h messages') + \
1520 ' will show help for messages commands.\n'
1521 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1522 ' will show help for friends and followers commands.\n'
1523 usage
+= s
* 2 + light_green('h list') + \
1524 ' will show help for list commands.\n'
1525 usage
+= s
* 2 + light_green('h stream') + \
1526 ' will show help for stream commands.\n'
1529 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1530 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1531 'will be evaluate by Python interpreter.\n'
1532 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1533 ' for current month.\n'
1536 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1537 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1538 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1539 ' theme immediately.\n'
1540 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1542 light_green('config ASCII_ART') + ' will output current value of ' +\
1543 light_yellow('ASCII_ART') + ' config key.\n'
1545 light_green('config TREND_MAX default') + ' will output default value of ' + \
1546 light_yellow('TREND_MAX') + ' config key.\n'
1548 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1549 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1551 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1552 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1553 light_yellow('True') + '.\n'
1556 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1557 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1558 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1559 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1560 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1561 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1564 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1565 usage
+= s
+ 'Have fun and hang tight! \n'
1568 'discover': help_discover
,
1569 'tweets': help_tweets
,
1570 'messages': help_messages
,
1571 'friends_and_followers': help_friends_and_followers
,
1573 'stream': help_stream
,
1578 lambda: printNicely(red('No such command.'))
1586 Pause stream display
1589 printNicely(green('Stream is paused'))
1597 printNicely(green('Stream is running back now'))
1613 printNicely(green('See you next time :)'))
1621 Reset prefix of line
1624 if c
.get('USER_JSON_ERROR'):
1625 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1626 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1628 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1631 printNicely(str(eval(g
['cmd'])))
1681 # Handle function set
1731 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1736 Listen to user's input
1741 ['public', 'mine', 'list'], # switch
1758 ['image'], # show image
1760 ['fl', 'fr'], # list
1762 [i
for i
in g
['message_threads']], # sent
1787 [key
for key
in dict(get_all_config())], # config
1788 g
['themes'], # theme
1793 'friends_and_followers',
1803 init_interactive_shell(d
)
1810 # Only use PREFIX as a string with raw_input
1811 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1814 # Save cmd to compare with readline buffer
1815 g
['cmd'] = line
.strip()
1816 # Get short cmd to pass to handle function
1818 cmd
= line
.split()[0]
1821 # Lock the semaphore
1823 # Save cmd to global variable and call process
1824 g
['stuff'] = ' '.join(line
.split()[1:])
1825 # Process the command
1828 if cmd
in ['switch', 't', 'rt', 'rep']:
1832 # Release the semaphore lock
1838 printNicely(red('OMG something is wrong with Twitter right now.'))
1841 def stream(domain
, args
, name
='Rainbow Stream'):
1847 c
['USER_DOMAIN']: name
,
1848 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1849 c
['SITE_DOMAIN']: name
,
1852 ascii_art(art_dict
[domain
])
1853 # These arguments are optional:
1855 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1857 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1860 if args
.track_keywords
:
1861 query_args
['track'] = args
.track_keywords
1863 stream
= TwitterStream(
1868 if domain
== c
['USER_DOMAIN']:
1869 tweet_iter
= stream
.user(**query_args
)
1870 elif domain
== c
['SITE_DOMAIN']:
1871 tweet_iter
= stream
.site(**query_args
)
1873 if args
.track_keywords
:
1874 tweet_iter
= stream
.statuses
.filter(**query_args
)
1876 tweet_iter
= stream
.statuses
.sample()
1877 # Block new stream until other one exits
1878 StreamLock
.acquire()
1879 g
['stream_stop'] = False
1880 for tweet
in tweet_iter
:
1882 printNicely("-- None --")
1883 elif tweet
is Timeout
:
1884 if(g
['stream_stop']):
1885 StreamLock
.release()
1887 elif tweet
is HeartbeatTimeout
:
1888 printNicely("-- Heartbeat Timeout --")
1889 guide
= light_magenta("You can use ") + \
1890 light_green("switch") + \
1891 light_magenta(" command to return to your stream.\n")
1892 guide
+= light_magenta("Type ") + \
1893 light_green("h stream") + \
1894 light_magenta(" for more details.")
1896 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1898 StreamLock
.release()
1900 elif tweet
is Hangup
:
1901 printNicely("-- Hangup --")
1902 elif tweet
.get('text'):
1903 # Check the semaphore pause and lock (stream process only)
1911 keyword
=args
.track_keywords
,
1916 # Current readline buffer
1917 current_buffer
= readline
.get_line_buffer().strip()
1918 # There is an unexpected behaviour in MacOSX readline + Python 2:
1919 # after completely delete a word after typing it,
1920 # somehow readline buffer still contains
1921 # the 1st character of that word
1922 if current_buffer
and g
['cmd'] != current_buffer
:
1924 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
1926 elif not c
['HIDE_PROMPT']:
1927 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1929 elif tweet
.get('direct_message'):
1930 # Check the semaphore pause and lock (stream process only)
1935 print_message(tweet
['direct_message'])
1936 elif tweet
.get('event'):
1937 c
['events'].append(tweet
)
1939 except TwitterHTTPError
:
1942 magenta("We have maximum connection problem with twitter'stream API right now :("))
1950 args
= parse_arguments()
1953 except TwitterHTTPError
:
1956 magenta("We have connection problem with twitter'stream API right now :("))
1957 printNicely(magenta("Let's try again later."))
1960 # Spawn stream thread
1961 th
= threading
.Thread(
1966 g
['original_name']))
1969 # Start listen process