2 Colorful user's timeline stream
14 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
15 from twitter
.api
import *
16 from twitter
.oauth
import OAuth
, read_token_file
17 from twitter
.oauth_dance
import oauth_dance
18 from twitter
.util
import printNicely
23 from .consumer
import *
24 from .interactive
import *
25 from .c_image
import *
26 from .py3patch
import *
32 StreamLock
= threading
.Lock()
78 def parse_arguments():
82 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
86 help='Timeout for the stream (seconds).')
89 '--heartbeat-timeout',
90 help='Set heartbeat timeout.',
96 help='Set stream to non-blocking.')
100 help='Search the stream for specific text.')
104 help='Filter specific screen_name.')
108 help='Ignore specific screen_name.')
113 help='Display all image on terminal.')
114 return parser
.parse_args()
119 Authenticate with Twitter OAuth
121 # When using rainbow stream you must authorize.
122 twitter_credential
= os
.environ
.get(
126 '')) + os
.sep
+ '.rainbow_oauth'
127 if not os
.path
.exists(twitter_credential
):
128 oauth_dance("Rainbow Stream",
132 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
140 def build_mute_dict(dict_data
=False):
144 t
= Twitter(auth
=authen())
147 screen_name_list
= []
150 while next_cursor
!= 0:
151 list = t
.mutes
.users
.list(
152 screen_name
=g
['original_name'],
155 include_entities
=False,
157 screen_name_list
+= ['@' + u
['screen_name'] for u
in list['users']]
158 name_list
+= [u
['name'] for u
in list['users']]
159 next_cursor
= list['next_cursor']
160 # Return dict or list
162 return dict(zip(screen_name_list
, name_list
))
164 return screen_name_list
172 ctrl_c_handler
= lambda signum
, frame
: quit()
173 signal
.signal(signal
.SIGINT
, ctrl_c_handler
)
175 t
= Twitter(auth
=authen())
176 name
= '@' + t
.account
.verify_credentials()['screen_name']
177 if not get_config('PREFIX'):
178 set_config('PREFIX', name
)
179 g
['original_name'] = name
[1:]
180 g
['decorated_name'] = lambda x
: color_func(
181 c
['DECORATED_NAME'])('[' + x
+ ']: ')
183 files
= os
.listdir(os
.path
.dirname(__file__
) + '/colorset')
184 themes
= [f
.split('.')[0] for f
in files
if f
.split('.')[-1] == 'json']
187 g
['previous_cmd'] = ''
191 # Init tweet dict and message dict
193 c
['message_dict'] = []
195 c
['IMAGE_ON_TERM'] = args
.image_on_term
196 set_config('IMAGE_ON_TERM', str(c
['IMAGE_ON_TERM']))
198 c
['IGNORE_LIST'] += build_mute_dict()
206 target
= g
['stuff'].split()[0]
208 args
= parse_arguments()
210 if g
['stuff'].split()[-1] == '-f':
211 guide
= 'To ignore an option, just hit Enter key.'
212 printNicely(light_magenta(guide
))
213 only
= raw_input('Only nicks [Ex: @xxx,@yy]: ')
214 ignore
= raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
215 args
.filter = filter(None, only
.split(','))
216 args
.ignore
= filter(None, ignore
.split(','))
217 elif g
['stuff'].split()[-1] == '-d':
218 args
.filter = c
['ONLY_LIST']
219 args
.ignore
= c
['IGNORE_LIST']
221 printNicely(red('Sorry, wrong format.'))
224 if target
== 'public':
225 keyword
= g
['stuff'].split()[1]
226 if keyword
[0] == '#':
227 keyword
= keyword
[1:]
229 g
['stream_stop'] = True
230 args
.track_keywords
= keyword
232 th
= threading
.Thread(
240 elif target
== 'mine':
242 g
['stream_stop'] = True
244 th
= threading
.Thread(
254 printNicely(cyan('Only: ' + str(args
.filter)))
256 printNicely(red('Ignore: ' + str(args
.ignore
)))
259 printNicely(red('Sorry I can\'t understand.'))
266 t
= Twitter(auth
=authen())
267 # Get country and town
269 country
= g
['stuff'].split()[0]
273 town
= g
['stuff'].split()[1]
276 avail
= t
.trends
.available()
279 trends
= t
.trends
.place(_id
=1)[0]['trends']
282 for location
in avail
:
283 # Search for country and Town
285 if location
['countryCode'] == country \
286 and location
['placeType']['name'] == 'Town' \
287 and location
['name'] == town
:
288 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
290 # Search for country only
292 if location
['countryCode'] == country \
293 and location
['placeType']['name'] == 'Country':
294 trends
= t
.trends
.place(_id
=location
['woeid'])[0]['trends']
302 t
= Twitter(auth
=authen())
303 num
= c
['HOME_TWEET_NUM']
304 if g
['stuff'].isdigit():
305 num
= int(g
['stuff'])
306 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
315 t
= Twitter(auth
=authen())
316 user
= g
['stuff'].split()[0]
319 num
= int(g
['stuff'].split()[1])
321 num
= c
['HOME_TWEET_NUM']
322 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
326 printNicely(red('A name should begin with a \'@\''))
333 t
= Twitter(auth
=authen())
334 num
= c
['HOME_TWEET_NUM']
335 if g
['stuff'].isdigit():
336 num
= int(g
['stuff'])
337 for tweet
in reversed(t
.statuses
.mentions_timeline(count
=num
)):
346 t
= Twitter(auth
=authen())
347 t
.statuses
.update(status
=g
['stuff'])
354 t
= Twitter(auth
=authen())
356 id = int(g
['stuff'].split()[0])
358 printNicely(red('Sorry I can\'t understand.'))
360 tid
= c
['tweet_dict'][id]
361 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
368 t
= Twitter(auth
=authen())
370 id = int(g
['stuff'].split()[0])
372 printNicely(red('Sorry I can\'t understand.'))
374 tid
= c
['tweet_dict'][id]
375 tweet
= t
.statuses
.show(id=tid
)
376 screen_name
= tweet
['user']['screen_name']
378 quote
= '\"@' + screen_name
+ ': ' + text
+ '\"'
379 quote
= quote
.encode('utf8')
380 notice
= light_magenta('Compose mode ')
381 notice
+= light_yellow('(Enter nothing will cancel the quote)')
382 notice
+= light_magenta(':')
384 extra
= raw_input(quote
)
386 t
.statuses
.update(status
=quote
+ extra
)
388 printNicely(light_magenta('No text added.'))
395 t
= Twitter(auth
=authen())
398 id = int(g
['stuff'].split()[0])
400 printNicely(red('Sorry I can\'t understand.'))
402 tid
= c
['tweet_dict'][id]
403 # Get display num if exist
405 num
= int(g
['stuff'].split()[1])
407 num
= c
['RETWEETS_SHOW_NUM']
408 # Get result and display
409 rt_ary
= t
.statuses
.retweets(id=tid
, count
=num
)
411 printNicely(magenta('This tweet has no retweet.'))
413 for tweet
in reversed(rt_ary
):
422 t
= Twitter(auth
=authen())
424 id = int(g
['stuff'].split()[0])
426 printNicely(red('Sorry I can\'t understand.'))
428 tid
= c
['tweet_dict'][id]
429 t
.favorites
.create(_id
=tid
, include_entities
=False)
430 printNicely(green('Favorited.'))
431 draw(t
.statuses
.show(id=tid
))
439 t
= Twitter(auth
=authen())
441 id = int(g
['stuff'].split()[0])
443 printNicely(red('Sorry I can\'t understand.'))
445 tid
= c
['tweet_dict'][id]
446 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
447 status
= ' '.join(g
['stuff'].split()[1:])
448 status
= '@' + user
+ ' ' + unc(status
)
449 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
456 t
= Twitter(auth
=authen())
458 id = int(g
['stuff'].split()[0])
460 printNicely(red('Sorry I can\'t understand.'))
462 tid
= c
['tweet_dict'][id]
463 t
.statuses
.destroy(id=tid
)
464 printNicely(green('Okay it\'s gone.'))
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())
489 g
['stuff'] = g
['stuff'].strip()
490 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
492 printNicely('Newest tweets:')
493 for i
in reversed(xrange(c
['SEARCH_MAX_RECORD'])):
498 printNicely(magenta('I\'m afraid there is no result'))
503 Send a direct message
505 t
= Twitter(auth
=authen())
506 user
= g
['stuff'].split()[0]
507 if user
[0].startswith('@'):
509 content
= g
['stuff'].split()[1]
511 printNicely(red('Sorry I can\'t understand.'))
512 t
.direct_messages
.new(
513 screen_name
=user
[1:],
516 printNicely(green('Message sent.'))
518 printNicely(red('A name should begin with a \'@\''))
525 t
= Twitter(auth
=authen())
527 target
= g
['stuff'].split()[0]
528 if target
!= 'image':
530 id = int(g
['stuff'].split()[1])
531 tid
= c
['tweet_dict'][id]
532 tweet
= t
.statuses
.show(id=tid
)
533 media
= tweet
['entities']['media']
535 res
= requests
.get(m
['media_url'])
536 img
= Image
.open(BytesIO(res
.content
))
539 printNicely(red('Sorry I can\'t show this image.'))
546 t
= Twitter(auth
=authen())
548 if not g
['stuff'].isdigit():
550 tid
= c
['tweet_dict'][int(g
['stuff'])]
551 tweet
= t
.statuses
.show(id=tid
)
553 u
for u
in tweet
['text'].split() if u
.startswith('http://')]
555 printNicely(light_magenta('No url here @.@!'))
557 for link
in link_ary
:
558 webbrowser
.open(link
)
560 printNicely(red('Sorry I can\'t open url in this tweet.'))
565 List friends for followers
567 t
= Twitter(auth
=authen())
570 name
= g
['stuff'].split()[1]
571 if name
.startswith('@'):
574 printNicely(red('A name should begin with a \'@\''))
575 raise Exception('Invalid name')
577 name
= g
['original_name']
578 # Get list followers or friends
580 target
= g
['stuff'].split()[0]
582 printNicely(red('Omg some syntax is wrong.'))
584 d
= {'fl': 'followers', 'fr': 'friends'}
588 while next_cursor
!= 0:
589 list = getattr(t
, d
[target
]).list(
593 include_entities
=False,
595 for u
in list['users']:
596 rel
[u
['name']] = '@' + u
['screen_name']
597 next_cursor
= list['next_cursor']
599 printNicely('All: ' + str(len(rel
)) + ' ' + d
[target
] + '.')
601 user
= ' ' + cycle_color(name
)
602 user
+= color_func(c
['TWEET']['nick'])(' ' + rel
[name
] + ' ')
608 Inbox direct messages
610 t
= Twitter(auth
=authen())
611 num
= c
['MESSAGES_DISPLAY']
613 if g
['stuff'].isdigit():
616 # Max message per page is 20 so we have to loop
618 rel
= rel
+ t
.direct_messages(
621 include_entities
=False,
626 rel
= rel
+ t
.direct_messages(
629 include_entities
=False,
633 printNicely('Inbox: newest ' + str(len(rel
)) + ' messages.')
634 for m
in reversed(rel
):
643 t
= Twitter(auth
=authen())
644 num
= c
['MESSAGES_DISPLAY']
646 if g
['stuff'].isdigit():
647 num
= int(g
['stuff'])
649 # Max message per page is 20 so we have to loop
651 rel
= rel
+ t
.direct_messages
.sent(
654 include_entities
=False,
659 rel
= rel
+ t
.direct_messages
.sent(
662 include_entities
=False,
666 printNicely('Sent: newest ' + str(len(rel
)) + ' messages.')
667 for m
in reversed(rel
):
676 t
= Twitter(auth
=authen())
678 id = int(g
['stuff'].split()[0])
680 printNicely(red('Sorry I can\'t understand.'))
681 mid
= c
['message_dict'][id]
682 t
.direct_messages
.destroy(id=mid
)
683 printNicely(green('Message deleted.'))
688 Show profile of a specific user
690 t
= Twitter(auth
=authen())
691 screen_name
= g
['stuff'].split()[0]
692 if screen_name
.startswith('@'):
695 screen_name
=screen_name
[1:],
696 include_entities
=False)
699 printNicely(red('Omg no user.'))
701 printNicely(red('A name should begin with a \'@\''))
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
))
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: '))
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.'))
950 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
955 Remove specific user from a list
957 owner
, slug
= get_slug()
959 user_name
= raw_input(light_magenta('Give me name of the unlucky one: '))
960 if user_name
.startswith('@'):
961 user_name
= user_name
[1:]
963 t
.lists
.members
.destroy(
965 owner_screen_name
=owner
,
966 screen_name
=user_name
)
967 printNicely(green('Gone.'))
969 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
972 def list_subscribe(t
):
976 owner
, slug
= get_slug()
979 t
.lists
.subscribers
.create(
981 owner_screen_name
=owner
)
982 printNicely(green('Done.'))
985 light_magenta('I\'m sorry you can not subscribe to this list.'))
988 def list_unsubscribe(t
):
992 owner
, slug
= get_slug()
995 t
.lists
.subscribers
.destroy(
997 owner_screen_name
=owner
)
998 printNicely(green('Done.'))
1001 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1010 while next_cursor
!= 0:
1011 res
= t
.lists
.ownerships(
1012 screen_name
=g
['original_name'],
1015 next_cursor
= res
['next_cursor']
1019 printNicely(light_magenta('You own no lists :)'))
1026 name
= raw_input(light_magenta('New list\'s name: '))
1027 mode
= raw_input(light_magenta('New list\'s mode (public/private): '))
1028 description
= raw_input(light_magenta('New list\'s description: '))
1033 description
=description
)
1034 printNicely(green(name
+ ' list is created.'))
1036 printNicely(red('Oops something is wrong with Twitter :('))
1043 slug
= raw_input(light_magenta('Your list that you want to update: '))
1044 name
= raw_input(light_magenta('Update name (leave blank to unchange): '))
1045 mode
= raw_input(light_magenta('Update mode (public/private): '))
1046 description
= raw_input(light_magenta('Update description: '))
1050 slug
='-'.join(slug
.split()),
1051 owner_screen_name
=g
['original_name'],
1054 description
=description
)
1058 owner_screen_name
=g
['original_name'],
1060 description
=description
)
1061 printNicely(green(slug
+ ' list is updated.'))
1063 printNicely(red('Oops something is wrong with Twitter :('))
1070 slug
= raw_input(light_magenta('Your list that you want to update: '))
1073 slug
='-'.join(slug
.split()),
1074 owner_screen_name
=g
['original_name'])
1075 printNicely(green(slug
+ ' list is deleted.'))
1077 printNicely(red('Oops something is wrong with Twitter :('))
1084 t
= Twitter(auth
=authen())
1085 # List all lists or base on action
1087 g
['list_action'] = g
['stuff'].split()[0]
1094 'all_mem': list_members
,
1095 'all_sub': list_subscribers
,
1098 'sub': list_subscribe
,
1099 'unsub': list_unsubscribe
,
1102 'update': list_update
,
1106 return action_ary
[g
['list_action']](t
)
1108 printNicely(red('Please try again.'))
1113 Unix's command `cal`
1116 rel
= os
.popen('cal').read().split('\n')
1119 show_calendar(month
, date
, rel
)
1124 Browse and change config
1126 all_config
= get_all_config()
1127 g
['stuff'] = g
['stuff'].strip()
1130 for k
in all_config
:
1132 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1134 guide
= 'Detailed explanation can be found at ' + \
1135 color_func(c
['TWEET']['link'])(
1136 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1138 # Print specific config
1139 elif len(g
['stuff'].split()) == 1:
1140 if g
['stuff'] in all_config
:
1143 green(k
) + ': ' + light_yellow(str(all_config
[k
]))
1146 printNicely(red('No such config key.'))
1147 # Print specific config's default value
1148 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'default':
1149 key
= g
['stuff'].split()[0]
1151 value
= get_default_config(key
)
1152 line
= ' ' * 2 + green(key
) + ': ' + light_magenta(value
)
1154 except Exception as e
:
1156 # Delete specific config key in config file
1157 elif len(g
['stuff'].split()) == 2 and g
['stuff'].split()[-1] == 'drop':
1158 key
= g
['stuff'].split()[0]
1161 printNicely(green('Config key is dropped.'))
1162 except Exception as e
:
1164 # Set specific config
1165 elif len(g
['stuff'].split()) == 3 and g
['stuff'].split()[1] == '=':
1166 key
= g
['stuff'].split()[0]
1167 value
= g
['stuff'].split()[-1]
1168 if key
== 'THEME' and not validate_theme(value
):
1169 printNicely(red('Invalid theme\'s value.'))
1172 set_config(key
, value
)
1173 # Apply theme immediately
1175 c
['THEME'] = reload_theme(value
, c
['THEME'])
1176 g
['decorated_name'] = lambda x
: color_func(
1177 c
['DECORATED_NAME'])('[' + x
+ ']: ')
1179 printNicely(green('Updated successfully.'))
1180 except Exception as e
:
1183 printNicely(light_magenta('Sorry I can\'s understand.'))
1188 List and change theme
1192 for theme
in g
['themes']:
1193 line
= light_magenta(theme
)
1194 if c
['THEME'] == theme
:
1195 line
= ' ' * 2 + light_yellow('* ') + line
1197 line
= ' ' * 4 + line
1203 c
['THEME'] = reload_theme(g
['stuff'], c
['THEME'])
1204 # Redefine decorated_name
1205 g
['decorated_name'] = lambda x
: color_func(
1206 c
['DECORATED_NAME'])(
1208 printNicely(green('Theme changed.'))
1210 printNicely(red('No such theme exists.'))
1213 def help_discover():
1218 # Discover the world
1220 usage
+= s
+ grey(u
'\u266A' + ' Discover the world \n')
1221 usage
+= s
* 2 + light_green('trend') + ' will show global trending topics. ' + \
1222 'You can try ' + light_green('trend US') + ' or ' + \
1223 light_green('trend JP Tokyo') + '.\n'
1224 usage
+= s
* 2 + light_green('home') + ' will show your timeline. ' + \
1225 light_green('home 7') + ' will show 7 tweets.\n'
1226 usage
+= s
* 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1227 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1228 usage
+= s
* 2 + light_green('whois @mdo') + ' will show profile of ' + \
1229 magenta('@mdo') + '.\n'
1230 usage
+= s
* 2 + light_green('view @mdo') + \
1231 ' will show ' + magenta('@mdo') + '\'s home.\n'
1232 usage
+= s
* 2 + light_green('s AKB48') + ' will search for "' + \
1233 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1234 'Search can be performed with or without hashtag.\n'
1245 usage
+= s
+ grey(u
'\u266A' + ' Tweets \n')
1246 usage
+= s
* 2 + light_green('t oops ') + \
1247 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1249 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1250 light_yellow('[id=12]') + '.\n'
1252 light_green('quote 12 ') + ' will quote the tweet with ' + \
1253 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1254 'the quote will be canceled.\n'
1256 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1257 light_yellow('[id=12]') + '.\n'
1258 usage
+= s
* 2 + light_green('rep 12 oops') + ' will reply "' + \
1259 light_yellow('oops') + '" to tweet with ' + \
1260 light_yellow('[id=12]') + '.\n'
1262 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1263 light_yellow('[id=12]') + '.\n'
1265 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1266 light_yellow('[id=12]') + '.\n'
1268 light_green('del 12 ') + ' will delete tweet with ' + \
1269 light_yellow('[id=12]') + '.\n'
1270 usage
+= s
* 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1271 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1272 usage
+= s
* 2 + light_green('open 12') + ' will open url in tweet with ' + \
1273 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1277 def help_messages():
1284 usage
+= s
+ grey(u
'\u266A' + ' Direct messages \n')
1285 usage
+= s
* 2 + light_green('inbox') + ' will show inbox messages. ' + \
1286 light_green('inbox 7') + ' will show newest 7 messages.\n'
1287 usage
+= s
* 2 + light_green('sent') + ' will show sent messages. ' + \
1288 light_green('sent 7') + ' will show newest 7 messages.\n'
1289 usage
+= s
* 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1290 magenta('@dtvd88') + '.\n'
1291 usage
+= s
* 2 + light_green('trash 5') + ' will remove message with ' + \
1292 light_yellow('[message_id=5]') + '.\n'
1296 def help_friends_and_followers():
1298 Friends and Followers
1301 # Follower and following
1303 usage
+= s
+ grey(u
'\u266A' + ' Friends and followers \n')
1305 light_green('ls fl') + \
1306 ' will list all followers (people who are following you).\n'
1308 light_green('ls fr') + \
1309 ' will list all friends (people who you are following).\n'
1310 usage
+= s
* 2 + light_green('fl @dtvd88') + ' will follow ' + \
1311 magenta('@dtvd88') + '.\n'
1312 usage
+= s
* 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1313 magenta('@dtvd88') + '.\n'
1314 usage
+= s
* 2 + light_green('mute @dtvd88') + ' will mute ' + \
1315 magenta('@dtvd88') + '.\n'
1316 usage
+= s
* 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1317 magenta('@dtvd88') + '.\n'
1318 usage
+= s
* 2 + light_green('muting') + ' will list muting users.\n'
1319 usage
+= s
* 2 + light_green('block @dtvd88') + ' will block ' + \
1320 magenta('@dtvd88') + '.\n'
1321 usage
+= s
* 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1322 magenta('@dtvd88') + '.\n'
1323 usage
+= s
* 2 + light_green('report @dtvd88') + ' will report ' + \
1324 magenta('@dtvd88') + ' as a spam account.\n'
1335 usage
+= s
+ grey(u
'\u266A' + ' Twitter list\n')
1336 usage
+= s
* 2 + light_green('list') + \
1337 ' will show all lists you are belong to.\n'
1338 usage
+= s
* 2 + light_green('list home') + \
1339 ' will show timeline of list. You will be asked for list\'s name.\n'
1340 usage
+= s
* 2 + light_green('list all_mem') + \
1341 ' will show list\'s all members.\n'
1342 usage
+= s
* 2 + light_green('list all_sub') + \
1343 ' will show list\'s all subscribers.\n'
1344 usage
+= s
* 2 + light_green('list add') + \
1345 ' will add specific person to a list owned by you.' + \
1346 ' You will be asked for list\'s name and person\'s name.\n'
1347 usage
+= s
* 2 + light_green('list rm') + \
1348 ' will remove specific person from a list owned by you.' + \
1349 ' You will be asked for list\'s name and person\'s name.\n'
1350 usage
+= s
* 2 + light_green('list sub') + \
1351 ' will subscribe you to a specific list.\n'
1352 usage
+= s
* 2 + light_green('list unsub') + \
1353 ' will unsubscribe you from a specific list.\n'
1354 usage
+= s
* 2 + light_green('list own') + \
1355 ' will show all list owned by you.\n'
1356 usage
+= s
* 2 + light_green('list new') + \
1357 ' will create a new list.\n'
1358 usage
+= s
* 2 + light_green('list update') + \
1359 ' will update a list owned by you.\n'
1360 usage
+= s
* 2 + light_green('list del') + \
1361 ' will delete a list owned by you.\n'
1372 usage
+= s
+ grey(u
'\u266A' + ' Switching streams \n')
1373 usage
+= s
* 2 + light_green('switch public #AKB') + \
1374 ' will switch to public stream and follow "' + \
1375 light_yellow('AKB') + '" keyword.\n'
1376 usage
+= s
* 2 + light_green('switch mine') + \
1377 ' will switch to your personal stream.\n'
1378 usage
+= s
* 2 + light_green('switch mine -f ') + \
1379 ' will prompt to enter the filter.\n'
1380 usage
+= s
* 3 + light_yellow('Only nicks') + \
1381 ' filter will decide nicks will be INCLUDE ONLY.\n'
1382 usage
+= s
* 3 + light_yellow('Ignore nicks') + \
1383 ' filter will decide nicks will be EXCLUDE.\n'
1384 usage
+= s
* 2 + light_green('switch mine -d') + \
1385 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1394 h
, w
= os
.popen('stty size', 'r').read().split()
1397 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
1398 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1399 usage
+= s
+ 'You are ' + \
1400 light_yellow('already') + ' on your personal stream.\n'
1401 usage
+= s
+ 'Any update from Twitter will show up ' + \
1402 light_yellow('immediately') + '.\n'
1403 usage
+= s
+ 'In addtion, following commands are available right now:\n'
1404 # Twitter help section
1406 usage
+= s
+ grey(u
'\u266A' + ' Twitter help\n')
1407 usage
+= s
* 2 + light_green('h discover') + \
1408 ' will show help for discover commands.\n'
1409 usage
+= s
* 2 + light_green('h tweets') + \
1410 ' will show help for tweets commands.\n'
1411 usage
+= s
* 2 + light_green('h messages') + \
1412 ' will show help for messages commands.\n'
1413 usage
+= s
* 2 + light_green('h friends_and_followers') + \
1414 ' will show help for friends and followers commands.\n'
1415 usage
+= s
* 2 + light_green('h list') + \
1416 ' will show help for list commands.\n'
1417 usage
+= s
* 2 + light_green('h stream') + \
1418 ' will show help for stream commands.\n'
1421 usage
+= s
+ grey(u
'\u266A' + ' Smart shell\n')
1422 usage
+= s
* 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1423 'will be evaluate by Python interpreter.\n'
1424 usage
+= s
* 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1425 ' for current month.\n'
1428 usage
+= s
+ grey(u
'\u266A' + ' Config \n')
1429 usage
+= s
* 2 + light_green('theme') + ' will list available theme. ' + \
1430 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1431 ' theme immediately.\n'
1432 usage
+= s
* 2 + light_green('config') + ' will list all config.\n'
1434 light_green('config ASCII_ART') + ' will output current value of ' +\
1435 light_yellow('ASCII_ART') + ' config key.\n'
1437 light_green('config TREND_MAX default') + ' will output default value of ' + \
1438 light_yellow('TREND_MAX') + ' config key.\n'
1440 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1441 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1443 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1444 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1445 light_yellow('True') + '.\n'
1448 usage
+= s
+ grey(u
'\u266A' + ' Screening \n')
1449 usage
+= s
* 2 + light_green('h') + ' will show this help again.\n'
1450 usage
+= s
* 2 + light_green('p') + ' will pause the stream.\n'
1451 usage
+= s
* 2 + light_green('r') + ' will unpause the stream.\n'
1452 usage
+= s
* 2 + light_green('c') + ' will clear the screen.\n'
1453 usage
+= s
* 2 + light_green('q') + ' will quit.\n'
1456 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
1457 usage
+= s
+ 'Have fun and hang tight! \n'
1460 'discover': help_discover
,
1461 'tweets': help_tweets
,
1462 'messages': help_messages
,
1463 'friends_and_followers': help_friends_and_followers
,
1465 'stream': help_stream
,
1470 lambda: printNicely(red('No such command.'))
1478 Pause stream display
1481 printNicely(green('Stream is paused'))
1489 printNicely(green('Stream is running back now'))
1505 printNicely(green('See you next time :)'))
1513 Reset prefix of line
1516 if c
.get('USER_JSON_ERROR'):
1517 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1518 printNicely(red('>>> ' + c
['USER_JSON_ERROR']))
1520 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1523 printNicely(str(eval(g
['cmd'])))
1580 Listen to user's input
1585 ['public', 'mine'], # switch
1600 ['image'], # show image
1602 ['fl', 'fr'], # list
1629 [key
for key
in dict(get_all_config())], # config
1630 g
['themes'], # theme
1635 'friends_and_followers',
1645 init_interactive_shell(d
)
1651 line
= raw_input(g
['decorated_name'](c
['PREFIX']))
1654 # Save previous cmd in order to compare with readline buffer
1655 g
['previous_cmd'] = line
.strip()
1656 # Get short cmd to filter
1658 cmd
= line
.split()[0]
1661 # Save whold the entire cmd
1664 # Lock the semaphore
1666 # Save cmd to global variable and call process
1667 g
['stuff'] = ' '.join(line
.split()[1:])
1668 # Process the command
1671 if cmd
in ['switch', 't', 'rt', 'rep']:
1675 # Release the semaphore lock
1678 printNicely(red('OMG something is wrong with Twitter right now.'))
1681 def stream(domain
, args
, name
='Rainbow Stream'):
1687 c
['USER_DOMAIN']: name
,
1688 c
['PUBLIC_DOMAIN']: args
.track_keywords
,
1689 c
['SITE_DOMAIN']: name
,
1692 ascii_art(art_dict
[domain
])
1693 # These arguments are optional:
1695 timeout
=0.5, # To check g['stream_stop'] after each 0.5 s
1696 block
=not args
.no_block
,
1697 heartbeat_timeout
=args
.heartbeat_timeout
)
1700 if args
.track_keywords
:
1701 query_args
['track'] = args
.track_keywords
1703 stream
= TwitterStream(
1708 if domain
== c
['USER_DOMAIN']:
1709 tweet_iter
= stream
.user(**query_args
)
1710 elif domain
== c
['SITE_DOMAIN']:
1711 tweet_iter
= stream
.site(**query_args
)
1713 if args
.track_keywords
:
1714 tweet_iter
= stream
.statuses
.filter(**query_args
)
1716 tweet_iter
= stream
.statuses
.sample()
1717 # Block new stream until other one exits
1718 StreamLock
.acquire()
1719 g
['stream_stop'] = False
1720 for tweet
in tweet_iter
:
1722 printNicely("-- None --")
1723 elif tweet
is Timeout
:
1724 if(g
['stream_stop']):
1725 StreamLock
.release()
1727 elif tweet
is HeartbeatTimeout
:
1728 printNicely("-- Heartbeat Timeout --")
1729 elif tweet
is Hangup
:
1730 printNicely("-- Hangup --")
1731 elif tweet
.get('text'):
1734 keyword
=args
.track_keywords
,
1735 check_semaphore
=True,
1739 # Current readline buffer
1740 current_buffer
= readline
.get_line_buffer().strip()
1741 # There is an unexpected behaviour in MacOSX readline + Python 2:
1742 # after completely delete a word after typing it,
1743 # somehow readline buffer still contains
1744 # the 1st character of that word
1745 if current_buffer
and g
['previous_cmd'] != current_buffer
:
1747 g
['decorated_name'](c
['PREFIX']) + unc(current_buffer
))
1749 elif not c
['HIDE_PROMPT']:
1750 sys
.stdout
.write(g
['decorated_name'](c
['PREFIX']))
1752 elif tweet
.get('direct_message'):
1753 print_message(tweet
['direct_message'], check_semaphore
=True)
1754 except TwitterHTTPError
:
1757 magenta("We have maximum connection problem with twitter'stream API right now :("))
1765 args
= parse_arguments()
1768 except TwitterHTTPError
:
1771 magenta("We have connection problem with twitter'stream API right now :("))
1772 printNicely(magenta("Let's try again later."))
1775 # Spawn stream thread
1776 th
= threading
.Thread(
1781 g
['original_name']))
1784 # Start listen process