13 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
14 from twitter
.api
import *
15 from twitter
.oauth
import OAuth
, read_token_file
16 from twitter
.oauth_dance
import oauth_dance
17 from twitter
.util
import printNicely
22 from .consumer
import *
23 from .interactive
import *
24 from .c_image
import *
25 from .py3patch
import *
32 StreamLock
= threading
.Lock()
35 def parse_arguments():
39 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
43 help='Timeout for the stream (seconds).')
47 help='Search the stream for specific text.')
51 help='Filter specific screen_name.')
55 help='Ignore specific screen_name.')
60 help='Display all image on terminal.')
61 return parser
.parse_args()
66 Authenticate with Twitter OAuth
68 # When using rainbow stream you must authorize.
69 twitter_credential
= os
.environ
.get(
73 '')) + os
.sep
+ '.rainbow_oauth'
74 if not os
.path
.exists(twitter_credential
):
75 oauth_dance("Rainbow Stream",
79 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
87 def build_mute_dict(dict_data
=False):
91 t
= Twitter(auth
=authen())
97 while next_cursor
!= 0:
98 list = t
.mutes
.users
.list(
99 screen_name
=g
['original_name'],
102 include_entities
=False,
104 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
105 name_list
+= [u
['name'] for u
in list['users']]
106 next_cursor
= list['next_cursor']
107 # Return dict or list
109 return dict(zip(screen_name_list
, name_list
))
111 return screen_name_list
116 Save traceback when run in debug mode
119 g
['traceback'].append(traceback
.format_exc())
122 def upgrade_center():
124 Check latest and notify to upgrade
127 current
= pkg_resources
.get_distribution("rainbowstream").version
128 url
= 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
129 readme
= requests
.get(url
).text
130 latest
= readme
.split("version = \'")[1].split("\'")[0]
131 if current
!= latest
:
132 notice
= light_magenta('RainbowStream latest version is ')
133 notice
+= light_green(latest
)
134 notice
+= light_magenta(' while your current version is ')
135 notice
+= light_yellow(current
) + '\n'
136 notice
+= light_magenta('You should upgrade with ')
137 notice
+= light_green('pip install -U rainbowstream')
148 ctrl_c_handler
= lambda signum
, frame
: quit()
149 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
153 t
= Twitter(auth
=authen())
154 credential
= t
.account
.verify_credentials()
155 screen_name
= '@' + credential
['screen_name']
156 name
= credential
['name']
157 if not get_config('PREFIX'):
158 set_config('PREFIX', screen_name
)
159 c
['PREFIX'] = emojize(c
['PREFIX'])
160 g
['PREFIX'] = u2str(c
['PREFIX'])
161 c
['original_name'] = g
['original_name'] = screen_name
[1:]
162 g
['full_name'] = name
163 g
['decorated_name'] = lambda x
: color_func(
164 c
['DECORATED_NAME'])('[' + x
+ ']: ', rl
=True)
166 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
167 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
170 g
['message_threads'] = {}
173 # Debug option default = True
180 # Init tweet dict and message dict
182 c
['message_dict'] = []
184 c
['IMAGE_ON_TERM'] = args
.image_on_term
185 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
186 # Check type of ONLY_LIST and IGNORE_LIST
187 if not isinstance(c
['ONLY_LIST'], list):
188 printNicely(red('ONLY_LIST is not a valid list value.'))
190 if not isinstance(c
['IGNORE_LIST'], list):
191 printNicely(red('IGNORE_LIST is not a valid list value.'))
192 c
['IGNORE_LIST'] = []
194 c
['IGNORE_LIST'] += build_mute_dict()
201 t
= Twitter(auth
=authen())
202 # Get country and town
204 country
= g
['stuff'].split()[0]
208 town
= g
['stuff'].split()[1]
211 avail
= t
.trends
.available()
214 trends
= t
.trends
.place(_id
=1)[0]['trends']
217 for location
in avail
:
218 # Search for country and Town
220 if location
['countryCode'] == country \
221 and location
['placeType']['name'] == 'Town' \
222 and location
['name'] == town
:
223 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
225 # Search for country only
227 if location
['countryCode'] == country \
228 and location
['placeType']['name'] == 'Country':
229 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
237 t
= Twitter(auth
=authen())
238 num
= c
['HOME_TWEET_NUM']
239 if g
['stuff'].isdigit():
240 num
= int(g
['stuff'])
241 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
251 for e
in c
['events']:
255 printNicely(magenta('Nothing at this time.'))
262 t
= Twitter(auth
=authen())
263 num
= c
['HOME_TWEET_NUM']
264 if g
['stuff'].isdigit():
265 num
= int(g
['stuff'])
266 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
273 Show profile of a specific user
275 t
= Twitter(auth
=authen())
276 screen_name
= g
['stuff'].split()[0]
277 if screen_name
.startswith('@'):
280 screen_name
=screen_name
[1:],
281 include_entities
=False)
285 printNicely(red('No user.'))
287 printNicely(red('A name should begin with a \'@\''))
294 t
= Twitter(auth
=authen())
295 user
= g
['stuff'].split()[0]
298 num
= int(g
['stuff'].split()[1])
300 num
= c
['HOME_TWEET_NUM']
301 for tweet
in reversed(
302 t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
306 printNicely(red('A name should begin with a \'@\''))
313 t
= Twitter(auth
=authen())
315 query
= g
['stuff'].strip()
316 type = c
['SEARCH_TYPE']
317 if type not in ['mixed', 'recent', 'popular']:
319 max_record
= c
['SEARCH_MAX_RECORD']
320 count
= min(max_record
, 100)
322 rel
= t
.search
.tweets(
329 printNicely('Newest tweets:')
330 for i
in reversed(xrange(count
)):
331 draw(t
=rel
[i
], keyword
=query
)
334 printNicely(magenta('I\'m afraid there is no result'))
341 t
= Twitter(auth
=authen())
342 t
.statuses
.update(status
=g
['stuff'])
349 t
= Twitter(auth
=authen())
351 id = int(g
['stuff'].split()[0])
353 printNicely(red('Sorry I can\'t understand.'))
355 tid
= c
['tweet_dict'][id]
356 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
364 t
= Twitter(auth
=authen())
366 id = int(g
['stuff'].split()[0])
368 printNicely(red('Sorry I can\'t understand.'))
370 tid
= c
['tweet_dict'][id]
371 tweet
= t
.statuses
.show(id=tid
)
373 formater
= format_quote(tweet
)
377 prefix
= light_magenta('Compose your ', rl
=True) + \
378 light_green('#comment: ', rl
=True)
379 comment
= raw_input(prefix
)
381 quote
= comment
.join(formater
.split('#comment'))
382 t
.statuses
.update(status
=quote
)
384 printNicely(light_magenta('No text added.'))
391 t
= Twitter(auth
=authen())
394 id = int(g
['stuff'].split()[0])
396 printNicely(red('Sorry I can\'t understand.'))
398 tid
= c
['tweet_dict'][id]
399 # Get display num if exist
401 num
= int(g
['stuff'].split()[1])
403 num
= c
['RETWEETS_SHOW_NUM']
404 # Get result and display
405 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
407 printNicely(magenta('This tweet has no retweet.'))
409 for tweet
in reversed(rt_ary
):
418 t
= Twitter(auth
=authen())
420 id = int(g
['stuff'].split()[0])
422 printNicely(red('Sorry I can\'t understand.'))
424 tid
= c
['tweet_dict'][id]
425 tweet
= t
.statuses
.show(id=tid
)
426 limit
= c
['CONVERSATION_MAX']
428 thread_ref
.append(tweet
)
429 prev_tid
= tweet
['in_reply_to_status_id']
430 while prev_tid
and limit
:
432 tweet
= t
.statuses
.show(id=prev_tid
)
433 prev_tid
= tweet
['in_reply_to_status_id']
434 thread_ref
.append(tweet
)
436 for tweet
in reversed(thread_ref
):
445 t
= Twitter(auth
=authen())
447 id = int(g
['stuff'].split()[0])
449 printNicely(red('Sorry I can\'t understand.'))
451 tid
= c
['tweet_dict'][id]
452 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
453 status
= ' '.join(g
['stuff'].split()[1:])
454 status
= '@' + user
+ ' ' + str2u(status
)
455 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
462 t
= Twitter(auth
=authen())
464 id = int(g
['stuff'].split()[0])
466 printNicely(red('Sorry I can\'t understand.'))
468 tid
= c
['tweet_dict'][id]
469 t
.favorites
.create(_id
=tid
, include_entities
=False)
470 printNicely(green('Favorited.'))
471 draw(t
.statuses
.show(id=tid
))
479 t
= Twitter(auth
=authen())
481 id = int(g
['stuff'].split()[0])
483 printNicely(red('Sorry I can\'t understand.'))
485 tid
= c
['tweet_dict'][id]
486 t
.favorites
.destroy(_id
=tid
)
487 printNicely(green('Okay it\'s unfavorited.'))
488 draw(t
.statuses
.show(id=tid
))
494 Copy url of a tweet to clipboard
496 t
= Twitter(auth
=authen())
498 id = int(g
['stuff'].split()[0])
499 tid
= c
['tweet_dict'][id]
501 printNicely(red('Tweet id is not valid.'))
503 tweet
= t
.statuses
.show(id=tid
)
504 url
= 'https://twitter.com/' + \
505 tweet
['user']['screen_name'] + '/status/' + str(tid
)
507 if platform
.system().lower() == 'darwin':
508 os
.system("echo '%s' | pbcopy" % url
)
509 printNicely(green('Copied tweet\'s url to clipboard.'))
511 printNicely('Direct link: ' + yellow(url
))
518 t
= Twitter(auth
=authen())
520 id = int(g
['stuff'].split()[0])
522 printNicely(red('Sorry I can\'t understand.'))
524 tid
= c
['tweet_dict'][id]
525 t
.statuses
.destroy(id=tid
)
526 printNicely(green('Okay it\'s gone.'))
533 t
= Twitter(auth
=authen())
535 target
= g
['stuff'].split()[0]
536 if target
!= 'image':
538 id = int(g
['stuff'].split()[1])
539 tid
= c
['tweet_dict'][id]
540 tweet
= t
.statuses
.show(id=tid
)
541 media
= tweet
['entities']['media']
543 res
= requests
.get(m
['media_url'])
544 img
= Image
.open(BytesIO(res
.content
))
548 printNicely(red('Sorry I can\'t show this image.'))
555 t
= Twitter(auth
=authen())
557 if not g
['stuff'].isdigit():
559 tid
= c
['tweet_dict'][int(g
['stuff'])]
560 tweet
= t
.statuses
.show(id=tid
)
561 link_prefix
= ('http://', 'https://')
562 link_ary
= [u
for u
in tweet
['text'].split()
563 if u
.startswith(link_prefix
)]
565 printNicely(light_magenta('No url here @.@!'))
567 for link
in link_ary
:
568 webbrowser
.open(link
)
571 printNicely(red('Sorry I can\'t open url in this tweet.'))
578 t
= Twitter(auth
=authen())
579 num
= c
['MESSAGES_DISPLAY']
580 if g
['stuff'].isdigit():
586 inbox
= inbox
+ t
.direct_messages(
589 include_entities
=False,
594 inbox
= inbox
+ t
.direct_messages(
597 include_entities
=False,
601 num
= c
['MESSAGES_DISPLAY']
602 if g
['stuff'].isdigit():
607 sent
= sent
+ t
.direct_messages
.sent(
610 include_entities
=False,
615 sent
= sent
+ t
.direct_messages
.sent(
618 include_entities
=False,
623 uniq_inbox
= list(set(
624 [(m
['sender_screen_name'], m
['sender']['name']) for m
in inbox
]
626 uniq_sent
= list(set(
627 [(m
['recipient_screen_name'], m
['recipient']['name']) for m
in sent
]
629 for partner
in uniq_inbox
:
630 inbox_ary
= [m
for m
in inbox
if m
['sender_screen_name'] == partner
[0]]
632 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
633 d
[partner
] = inbox_ary
+ sent_ary
634 for partner
in uniq_sent
:
637 m
for m
in sent
if m
['recipient_screen_name'] == partner
[0]]
638 g
['message_threads'] = print_threads(d
)
643 View a thread of message
646 thread_id
= int(g
['stuff'])
648 g
['message_threads'][thread_id
],
653 printNicely(red('No such thread.'))
658 Send a direct message
660 t
= Twitter(auth
=authen())
662 user
= g
['stuff'].split()[0]
663 if user
[0].startswith('@'):
664 content
= ' '.join(g
['stuff'].split()[1:])
665 t
.direct_messages
.new(
666 screen_name
=user
[1:],
669 printNicely(green('Message sent.'))
671 printNicely(red('A name should begin with a \'@\''))
674 printNicely(red('Sorry I can\'t understand.'))
681 t
= Twitter(auth
=authen())
683 id = int(g
['stuff'].split()[0])
685 printNicely(red('Sorry I can\'t understand.'))
686 mid
= c
['message_dict'][id]
687 t
.direct_messages
.destroy(id=mid
)
688 printNicely(green('Message deleted.'))
693 List friends for followers
695 t
= Twitter(auth
=authen())
698 name
= g
['stuff'].split()[1]
699 if name
.startswith('@'):
702 printNicely(red('A name should begin with a \'@\''))
703 raise Exception('Invalid name')
705 name
= g
['original_name']
706 # Get list followers or friends
708 target
= g
['stuff'].split()[0]
710 printNicely(red('Omg some syntax is wrong.'))
712 d
= {'fl': 'followers', 'fr': 'friends'}
716 while next_cursor
!= 0:
717 list = getattr(t
, d
[target
]).list(
721 include_entities
=False,
723 for u
in list['users']:
724 rel
[u
['name']] = '@' + u
['screen_name']
725 next_cursor
= list['next_cursor']
727 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
729 user
= ' ' + cycle_color(name
)
730 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
738 t
= Twitter(auth
=authen())
739 screen_name
= g
['stuff'].split()[0]
740 if screen_name
.startswith('@'):
741 t
.friendships
.create(screen_name
=screen_name
[1:], follow
=True)
742 printNicely(green('You are following ' + screen_name
+ ' now!'))
744 printNicely(red('A name should begin with a \'@\''))
751 t
= Twitter(auth
=authen())
752 screen_name
= g
['stuff'].split()[0]
753 if screen_name
.startswith('@'):
754 t
.friendships
.destroy(
755 screen_name
=screen_name
[1:],
756 include_entities
=False)
757 printNicely(green('Unfollow ' + screen_name
+ ' success!'))
759 printNicely(red('A name should begin with a \'@\''))
766 t
= Twitter(auth
=authen())
768 screen_name
= g
['stuff'].split()[0]
770 printNicely(red('A name should be specified. '))
772 if screen_name
.startswith('@'):
774 rel
= t
.mutes
.users
.create(screen_name
=screen_name
[1:])
775 if isinstance(rel
, dict):
776 printNicely(green(screen_name
+ ' is muted.'))
777 c
['IGNORE_LIST'] += [unc(screen_name
)]
778 c
['IGNORE_LIST'] = list(set(c
['IGNORE_LIST']))
780 printNicely(red(rel
))
783 printNicely(red('Something is wrong, can not mute now :('))
785 printNicely(red('A name should begin with a \'@\''))
792 t
= Twitter(auth
=authen())
794 screen_name
= g
['stuff'].split()[0]
796 printNicely(red('A name should be specified. '))
798 if screen_name
.startswith('@'):
800 rel
= t
.mutes
.users
.destroy(screen_name
=screen_name
[1:])
801 if isinstance(rel
, dict):
802 printNicely(green(screen_name
+ ' is unmuted.'))
803 c
['IGNORE_LIST'].remove(screen_name
)
805 printNicely(red(rel
))
807 printNicely(red('Maybe you are not muting this person ?'))
809 printNicely(red('A name should begin with a \'@\''))
816 # Get dict of muting users
817 md
= build_mute_dict(dict_data
=True)
818 printNicely('All: ' + str(len(md
)) + ' people.')
820 user
= ' ' + cycle_color(md
[name
])
821 user
+= color_func(c
['TWEET']['nick'])(' ' + name
+ ' ')
823 # Update from Twitter
824 c
['IGNORE_LIST'] = [n
for n
in md
]
831 t
= Twitter(auth
=authen())
832 screen_name
= g
['stuff'].split()[0]
833 if screen_name
.startswith('@'):
835 screen_name
=screen_name
[1:],
836 include_entities
=False,
838 printNicely(green('You blocked ' + screen_name
+ '.'))
840 printNicely(red('A name should begin with a \'@\''))
847 t
= Twitter(auth
=authen())
848 screen_name
= g
['stuff'].split()[0]
849 if screen_name
.startswith('@'):
851 screen_name
=screen_name
[1:],
852 include_entities
=False,
854 printNicely(green('Unblock ' + screen_name
+ ' success!'))
856 printNicely(red('A name should begin with a \'@\''))
861 Report a user as a spam account
863 t
= Twitter(auth
=authen())
864 screen_name
= g
['stuff'].split()[0]
865 if screen_name
.startswith('@'):
867 screen_name
=screen_name
[1:])
868 printNicely(green('You reported ' + screen_name
+ '.'))
870 printNicely(red('Sorry I can\'t understand.'))
878 list_name
= raw_input(
879 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl
=True))
880 # Get list name and owner
882 owner
, slug
= list_name
.split('/')
883 if slug
.startswith('@'):
888 light_magenta('List name should follow "@owner/list_name" format.'))
889 raise Exception('Wrong list name')
896 rel
= t
.lists
.list(screen_name
=g
['original_name'])
900 printNicely(light_magenta('You belong to no lists :)'))
907 owner
, slug
= get_slug()
908 res
= t
.lists
.statuses(
910 owner_screen_name
=owner
,
912 include_entities
=False)
913 for tweet
in reversed(res
):
922 owner
, slug
= get_slug()
926 while next_cursor
!= 0:
929 owner_screen_name
=owner
,
931 include_entities
=False)
933 rel
[u
['name']] = '@' + u
['screen_name']
934 next_cursor
= m
['next_cursor']
935 printNicely('All: ' + str(len(rel
)) + ' members.')
937 user
= ' ' + cycle_color(name
)
938 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
942 def list_subscribers(t
):
946 owner
, slug
= get_slug()
950 while next_cursor
!= 0:
951 m
= t
.lists
.subscribers(
953 owner_screen_name
=owner
,
955 include_entities
=False)
957 rel
[u
['name']] = '@' + u
['screen_name']
958 next_cursor
= m
['next_cursor']
959 printNicely('All: ' + str(len(rel
)) + ' subscribers.')
961 user
= ' ' + cycle_color(name
)
962 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
968 Add specific user to a list
970 owner
, slug
= get_slug()
972 user_name
= raw_input(
974 'Give me name of the newbie: ',
976 if user_name
.startswith('@'):
977 user_name
= user_name
[1:]
979 t
.lists
.members
.create(
981 owner_screen_name
=owner
,
982 screen_name
=user_name
)
983 printNicely(green('Added.'))
986 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
991 Remove specific user from a list
993 owner
, slug
= get_slug()
995 user_name
= raw_input(
997 'Give me name of the unlucky one: ',
999 if user_name
.startswith('@'):
1000 user_name
= user_name
[1:]
1002 t
.lists
.members
.destroy(
1004 owner_screen_name
=owner
,
1005 screen_name
=user_name
)
1006 printNicely(green('Gone.'))
1009 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1012 def list_subscribe(t
):
1016 owner
, slug
= get_slug()
1019 t
.lists
.subscribers
.create(
1021 owner_screen_name
=owner
)
1022 printNicely(green('Done.'))
1026 light_magenta('I\'m sorry you can not subscribe to this list.'))
1029 def list_unsubscribe(t
):
1033 owner
, slug
= get_slug()
1036 t
.lists
.subscribers
.destroy(
1038 owner_screen_name
=owner
)
1039 printNicely(green('Done.'))
1043 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1052 while next_cursor
!= 0:
1053 res
= t
.lists
.ownerships(
1054 screen_name
=g
['original_name'],
1057 next_cursor
= res
['next_cursor']
1061 printNicely(light_magenta('You own no lists :)'))
1068 name
= raw_input(light_magenta('New list\'s name: ', rl
=True))
1071 'New list\'s mode (public/private): ',
1073 description
= raw_input(
1075 'New list\'s description: ',
1081 description
=description
)
1082 printNicely(green(name
+ ' list is created.'))
1085 printNicely(red('Oops something is wrong with Twitter :('))
1094 'Your list that you want to update: ',
1098 'Update name (leave blank to unchange): ',
1100 mode
= raw_input(light_magenta('Update mode (public/private): ', rl
=True))
1101 description
= raw_input(light_magenta('Update description: ', rl
=True))
1105 slug
='-'.join(slug
.split()),
1106 owner_screen_name
=g
['original_name'],
1109 description
=description
)
1113 owner_screen_name
=g
['original_name'],
1115 description
=description
)
1116 printNicely(green(slug
+ ' list is updated.'))
1119 printNicely(red('Oops something is wrong with Twitter :('))
1128 'Your list that you want to delete: ',
1132 slug
='-'.join(slug
.split()),
1133 owner_screen_name
=g
['original_name'])
1134 printNicely(green(slug
+ ' list is deleted.'))
1137 printNicely(red('Oops something is wrong with Twitter :('))
1144 t
= Twitter(auth
=authen())
1145 # List all lists or base on action
1147 g
['list_action'] = g
['stuff'].split()[0]
1154 'all_mem': list_members
,
1155 'all_sub': list_subscribers
,
1158 'sub': list_subscribe
,
1159 'unsub': list_unsubscribe
,
1162 'update': list_update
,
1166 return action_ary
[g
['list_action']](t
)
1168 printNicely(red('Please try again.'))
1176 target
= g
['stuff'].split()[0]
1178 args
= parse_arguments()
1180 if g
['stuff'].split()[-1] == '-f':
1181 guide
= 'To ignore an option, just hit Enter key.'
1182 printNicely(light_magenta(guide
))
1183 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
1184 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1185 args
.filter = filter(None, only
.split(','))
1186 args
.ignore
= filter(None, ignore
.split(','))
1188 printNicely(red('Sorry, wrong format.'))
1191 if target
== 'public':
1192 keyword
= g
['stuff'].split()[1]
1193 if keyword
[0] == '#':
1194 keyword
= keyword
[1:]
1196 g
['stream_stop'] = True
1197 args
.track_keywords
= keyword
1199 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1201 th
= threading
.Thread(
1209 elif target
== 'mine':
1211 g
['stream_stop'] = True
1213 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1215 th
= threading
.Thread(
1220 g
['original_name']))
1223 # Stream base on list
1224 elif target
== 'list':
1225 owner
, slug
= get_slug()
1226 # Force python 2 not redraw readline buffer
1227 g
['PREFIX'] = g
['cmd'] = '/'.join([owner
, slug
])
1228 printNicely(light_yellow('getting list members ...'))
1230 t
= Twitter(auth
=authen())
1233 while next_cursor
!= 0:
1234 m
= t
.lists
.members(
1236 owner_screen_name
=owner
,
1238 include_entities
=False)
1239 for u
in m
['users']:
1240 members
.append('@' + u
['screen_name'])
1241 next_cursor
= m
['next_cursor']
1242 printNicely(light_yellow('... done.'))
1243 # Build thread filter array
1244 args
.filter = members
1246 g
['stream_stop'] = True
1248 th
= threading
.Thread(
1258 printNicely(cyan('Include: ' + str(len(args
.filter)) + ' people.'))
1260 printNicely(red('Ignore: ' + str(len(args
.ignore
)) + ' people.'))
1264 printNicely(red('Sorry I can\'t understand.'))
1269 Unix's command `cal`
1272 rel
= os
.popen('cal').read().split('\n')
1275 show_calendar(month
, date
, rel
)
1280 List and change theme
1284 for theme
in g
['themes']:
1285 line
= light_magenta(theme
)
1286 if c
['THEME'] == theme
:
1287 line
= ' ' * 2 + light_yellow('* ') + line
1289 line
= ' ' * 4 + line
1295 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1296 # Redefine decorated_name
1297 g
['decorated_name'] = lambda x
: color_func(
1298 c
['DECORATED_NAME'])(
1300 printNicely(green('Theme changed.'))
1302 printNicely(red('No such theme exists.'))
1307 Browse and change config
1309 all_config
= get_all_config()
1310 g
['stuff'] = g
['stuff'].strip()
1313 for k
in all_config
:
1315 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1317 guide
= 'Detailed explanation can be found at ' + \
1318 color_func(c
['TWEET']['link'])(
1319 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1321 # Print specific config
1322 elif len(g
['stuff'].split()) == 1:
1323 if g
['stuff'] in all_config
:
1326 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1329 printNicely(red('No such config key.'))
1330 # Print specific config's default value
1331 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1332 key
= g
['stuff'].split()[0]
1334 value
= get_default_config(key
)
1335 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1339 printNicely(red('Just can not get the default.'))
1340 # Delete specific config key in config file
1341 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1342 key
= g
['stuff'].split()[0]
1345 printNicely(green('Config key is dropped.'))
1348 printNicely(red('Just can not drop the key.'))
1349 # Set specific config
1350 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1351 key
= g
['stuff'].split()[0]
1352 value
= g
['stuff'].split()[-1]
1353 if key
== 'THEME' and not validate_theme(value
):
1354 printNicely(red('Invalid theme\'s value.'))
1357 set_config(key
, value
)
1358 # Keys that needs to be apply immediately
1360 c
['THEME'] = reload_theme(value
, c
['THEME'])
1361 g
['decorated_name'] = lambda x
: color_func(
1362 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1363 elif key
== 'PREFIX':
1364 g
['PREFIX'] = u2str(emojize(c
['PREFIX']))
1366 printNicely(green('Updated successfully.'))
1369 printNicely(red('Just can not set the key.'))
1371 printNicely(light_magenta('Sorry I can\'s understand.'))
1374 def help_discover():
1379 # Discover the world
1381 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1382 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1383 'You can try ' + light_green('trend US') + ' or ' + \
1384 light_green('trend JP Tokyo') + '.\n'
1385 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1386 light_green('home 7') + ' will show 7 tweets.\n'
1388 light_green('notification') + ' will show your recent notification.\n'
1389 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1390 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1391 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1392 magenta('@mdo') + '.\n'
1393 usage
+= s
* 2 + light_green('view @mdo') + \
1394 ' will show ' + magenta('@mdo') + '\'s home.\n'
1395 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1396 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1397 'Search can be performed with or without hashtag.\n'
1408 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1409 usage
+= s
* 2 + light_green('t oops ') + \
1410 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1412 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1413 light_yellow('[id=12]') + '.\n'
1415 light_green('quote 12 ') + ' will quote the tweet with ' + \
1416 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1417 'the quote will be canceled.\n'
1419 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1420 light_yellow('[id=12]') + '.\n'
1421 usage
+= s
* 2 + light_green('conversation 12') + ' will show the chain of ' + \
1422 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1423 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1424 light_yellow('oops') + '" to tweet with ' + \
1425 light_yellow('[id=12]') + '.\n'
1427 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1428 light_yellow('[id=12]') + '.\n'
1430 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1431 light_yellow('[id=12]') + '.\n'
1433 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1434 light_yellow('[id=12]') + '.\n'
1436 light_green('del 12 ') + ' will delete tweet with ' + \
1437 light_yellow('[id=12]') + '.\n'
1438 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1439 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1440 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1441 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1445 def help_messages():
1452 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1453 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1454 light_green('inbox 7') + ' will show newest 7 messages.\n'
1455 usage
+= s
* 2 + light_green('thread 2') + ' will show full thread with ' + \
1456 light_yellow('[thread_id=2]') + '.\n'
1457 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1458 magenta('@dtvd88') + '.\n'
1459 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1460 light_yellow('[message_id=5]') + '.\n'
1464 def help_friends_and_followers():
1466 Friends and Followers
1469 # Follower and following
1471 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1473 light_green('ls fl') + \
1474 ' will list all followers (people who are following you).\n'
1476 light_green('ls fr') + \
1477 ' will list all friends (people who you are following).\n'
1478 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1479 magenta('@dtvd88') + '.\n'
1480 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1481 magenta('@dtvd88') + '.\n'
1482 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1483 magenta('@dtvd88') + '.\n'
1484 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1485 magenta('@dtvd88') + '.\n'
1486 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1487 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1488 magenta('@dtvd88') + '.\n'
1489 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1490 magenta('@dtvd88') + '.\n'
1491 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1492 magenta('@dtvd88') + ' as a spam account.\n'
1503 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1504 usage
+= s
* 2 + light_green('list') + \
1505 ' will show all lists you are belong to.\n'
1506 usage
+= s
* 2 + light_green('list home') + \
1507 ' will show timeline of list. You will be asked for list\'s name.\n'
1508 usage
+= s
* 2 + light_green('list all_mem') + \
1509 ' will show list\'s all members.\n'
1510 usage
+= s
* 2 + light_green('list all_sub') + \
1511 ' will show list\'s all subscribers.\n'
1512 usage
+= s
* 2 + light_green('list add') + \
1513 ' will add specific person to a list owned by you.' + \
1514 ' You will be asked for list\'s name and person\'s name.\n'
1515 usage
+= s
* 2 + light_green('list rm') + \
1516 ' will remove specific person from a list owned by you.' + \
1517 ' You will be asked for list\'s name and person\'s name.\n'
1518 usage
+= s
* 2 + light_green('list sub') + \
1519 ' will subscribe you to a specific list.\n'
1520 usage
+= s
* 2 + light_green('list unsub') + \
1521 ' will unsubscribe you from a specific list.\n'
1522 usage
+= s
* 2 + light_green('list own') + \
1523 ' will show all list owned by you.\n'
1524 usage
+= s
* 2 + light_green('list new') + \
1525 ' will create a new list.\n'
1526 usage
+= s
* 2 + light_green('list update') + \
1527 ' will update a list owned by you.\n'
1528 usage
+= s
* 2 + light_green('list del') + \
1529 ' will delete a list owned by you.\n'
1540 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1541 usage
+= s
* 2 + light_green('switch public #AKB') + \
1542 ' will switch to public stream and follow "' + \
1543 light_yellow('AKB') + '" keyword.\n'
1544 usage
+= s
* 2 + light_green('switch mine') + \
1545 ' will switch to your personal stream.\n'
1546 usage
+= s
* 2 + light_green('switch mine -f ') + \
1547 ' will prompt to enter the filter.\n'
1548 usage
+= s
* 3 + light_yellow('Only nicks') + \
1549 ' filter will decide nicks will be INCLUDE ONLY.\n'
1550 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1551 ' filter will decide nicks will be EXCLUDE.\n'
1552 usage
+= s
* 2 + light_green('switch list') + \
1553 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1562 h
, w
= os
.popen('stty size', 'r').read().split()
1565 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1566 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1567 usage
+= s
+ 'You are ' + \
1568 light_yellow('already') + ' on your personal stream.\n'
1569 usage
+= s
+ 'Any update from Twitter will show up ' + \
1570 light_yellow('immediately') + '.\n'
1571 usage
+= s
+ 'In addition, following commands are available right now:\n'
1572 # Twitter help section
1574 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1575 usage
+= s
* 2 + light_green('h discover') + \
1576 ' will show help for discover commands.\n'
1577 usage
+= s
* 2 + light_green('h tweets') + \
1578 ' will show help for tweets commands.\n'
1579 usage
+= s
* 2 + light_green('h messages') + \
1580 ' will show help for messages commands.\n'
1581 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1582 ' will show help for friends and followers commands.\n'
1583 usage
+= s
* 2 + light_green('h list') + \
1584 ' will show help for list commands.\n'
1585 usage
+= s
* 2 + light_green('h stream') + \
1586 ' will show help for stream commands.\n'
1589 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1590 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1591 'will be evaluate by Python interpreter.\n'
1592 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1593 ' for current month.\n'
1596 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1597 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1598 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1599 ' theme immediately.\n'
1600 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1602 light_green('config ASCII_ART') + ' will output current value of ' +\
1603 light_yellow('ASCII_ART') + ' config key.\n'
1605 light_green('config TREND_MAX default') + ' will output default value of ' + \
1606 light_yellow('TREND_MAX') + ' config key.\n'
1608 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1609 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1611 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1612 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1613 light_yellow('True') + '.\n'
1616 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1617 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1618 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1619 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1620 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1621 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1624 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1625 usage
+= s
+ 'Have fun and hang tight! \n'
1628 'discover': help_discover
,
1629 'tweets': help_tweets
,
1630 'messages': help_messages
,
1631 'friends_and_followers': help_friends_and_followers
,
1633 'stream': help_stream
,
1638 lambda: printNicely(red('No such command.'))
1646 Pause stream display
1649 printNicely(green('Stream is paused'))
1657 printNicely(green('Stream is running back now'))
1673 printNicely(green('See you next time :)'))
1681 Reset prefix of line
1684 if c
.get('USER_JSON_ERROR'):
1685 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1686 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1688 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1691 printNicely(str(eval(g
['cmd'])))
1742 # Handle function set
1793 return dict(zip(cmdset
, funcset
)).get(cmd
, reset
)
1798 Listen to user's input
1803 ['public', 'mine', 'list'], # switch
1821 ['image'], # show image
1823 ['fl', 'fr'], # list
1825 [i
for i
in g
['message_threads']], # sent
1850 [key
for key
in dict(get_all_config())], # config
1851 g
['themes'], # theme
1856 'friends_and_followers',
1866 init_interactive_shell(d
)
1873 # Only use PREFIX as a string with raw_input
1874 line
= raw_input(g
['decorated_name'](g
['PREFIX']))
1877 # Save cmd to compare with readline buffer
1878 g
['cmd'] = line
.strip()
1879 # Get short cmd to pass to handle function
1881 cmd
= line
.split()[0]
1884 # Lock the semaphore
1886 # Save cmd to global variable and call process
1887 g
['stuff'] = ' '.join(line
.split()[1:])
1888 # Process the command
1891 if cmd
in ['switch', 't', 'rt', 'rep']:
1895 # Release the semaphore lock
1901 printNicely(red('OMG something is wrong with Twitter right now.'))
1904 def reconn_notice():
1906 Notice when Hangup or Timeout
1908 guide
= light_magenta("You can use ") + \
1909 light_green("switch") + \
1910 light_magenta(" command to return to your stream.\n")
1911 guide
+= light_magenta("Type ") + \
1912 light_green("h stream") + \
1913 light_magenta(" for more details.")
1915 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1919 def stream(domain
, args
, name
='Rainbow Stream'):
1925 c
['USER_DOMAIN']: name
,
1926 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1927 c
['SITE_DOMAIN']: name
,
1930 ascii_art(art_dict
[domain
])
1931 # These arguments are optional:
1933 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1935 heartbeat_timeout
=c
['HEARTBEAT_TIMEOUT'] * 60)
1938 if args
.track_keywords
:
1939 query_args
['track'] = args
.track_keywords
1941 stream
= TwitterStream(
1946 if domain
== c
['USER_DOMAIN']:
1947 tweet_iter
= stream
.user(**query_args
)
1948 elif domain
== c
['SITE_DOMAIN']:
1949 tweet_iter
= stream
.site(**query_args
)
1951 if args
.track_keywords
:
1952 tweet_iter
= stream
.statuses
.filter(**query_args
)
1954 tweet_iter
= stream
.statuses
.sample()
1955 # Block new stream until other one exits
1956 StreamLock
.acquire()
1957 g
['stream_stop'] = False
1958 for tweet
in tweet_iter
:
1960 printNicely("-- None --")
1961 elif tweet
is Timeout
:
1962 # Because the stream check for each 0.3s
1963 # so we shouldn't output anything here
1964 if(g
['stream_stop']):
1965 StreamLock
.release()
1967 elif tweet
is HeartbeatTimeout
:
1968 printNicely("-- Heartbeat Timeout --")
1970 StreamLock
.release()
1972 elif tweet
is Hangup
:
1973 printNicely("-- Hangup --")
1975 StreamLock
.release()
1977 elif tweet
.get('text'):
1978 # Check the semaphore pause and lock (stream process only)
1986 keyword
=args
.track_keywords
,
1991 # Current readline buffer
1992 current_buffer
= readline
.get_line_buffer().strip()
1993 # There is an unexpected behaviour in MacOSX readline + Python 2:
1994 # after completely delete a word after typing it,
1995 # somehow readline buffer still contains
1996 # the 1st character of that word
1997 if current_buffer
and g
['cmd'] != current_buffer
:
1999 g
['decorated_name'](c
['PREFIX']) + str2u(current_buffer
))
2001 elif not c
['HIDE_PROMPT']:
2002 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
2004 elif tweet
.get('direct_message'):
2005 # Check the semaphore pause and lock (stream process only)
2010 print_message(tweet
['direct_message'])
2011 elif tweet
.get('event'):
2012 c
['events'].append(tweet
)
2014 except TwitterHTTPError
:
2017 magenta("We have maximum connection problem with twitter'stream API right now :("))
2025 args
= parse_arguments()
2028 except TwitterHTTPError
:
2031 magenta("We have connection problem with twitter'stream API right now :("))
2032 printNicely(magenta("Let's try again later."))
2035 # Spawn stream thread
2036 th
= threading
.Thread(
2041 g
['original_name']))
2044 # Start listen process