support quote format
[rainbowstream.git] / rainbowstream / rainbow.py
... / ...
CommitLineData
1"""
2Colorful user's timeline stream
3"""
4import os
5import os.path
6import sys
7import signal
8import argparse
9import time
10import threading
11import requests
12import webbrowser
13
14from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
15from twitter.api import *
16from twitter.oauth import OAuth, read_token_file
17from twitter.oauth_dance import oauth_dance
18from twitter.util import printNicely
19
20from .draw import *
21from .colors import *
22from .config import *
23from .consumer import *
24from .interactive import *
25from .c_image import *
26from .py3patch import *
27
28# Global values
29g = {}
30
31# Lock for streams
32StreamLock = threading.Lock()
33
34
35def parse_arguments():
36 """
37 Parse the arguments
38 """
39 parser = argparse.ArgumentParser(description=__doc__ or "")
40 parser.add_argument(
41 '-to',
42 '--timeout',
43 help='Timeout for the stream (seconds).')
44 parser.add_argument(
45 '-tt',
46 '--track-keywords',
47 help='Search the stream for specific text.')
48 parser.add_argument(
49 '-fil',
50 '--filter',
51 help='Filter specific screen_name.')
52 parser.add_argument(
53 '-ig',
54 '--ignore',
55 help='Ignore specific screen_name.')
56 parser.add_argument(
57 '-iot',
58 '--image-on-term',
59 action='store_true',
60 help='Display all image on terminal.')
61 return parser.parse_args()
62
63
64def authen():
65 """
66 Authenticate with Twitter OAuth
67 """
68 # When using rainbow stream you must authorize.
69 twitter_credential = os.environ.get(
70 'HOME',
71 os.environ.get(
72 'USERPROFILE',
73 '')) + os.sep + '.rainbow_oauth'
74 if not os.path.exists(twitter_credential):
75 oauth_dance("Rainbow Stream",
76 CONSUMER_KEY,
77 CONSUMER_SECRET,
78 twitter_credential)
79 oauth_token, oauth_token_secret = read_token_file(twitter_credential)
80 return OAuth(
81 oauth_token,
82 oauth_token_secret,
83 CONSUMER_KEY,
84 CONSUMER_SECRET)
85
86
87def build_mute_dict(dict_data=False):
88 """
89 Build muting list
90 """
91 t = Twitter(auth=authen())
92 # Init cursor
93 next_cursor = -1
94 screen_name_list = []
95 name_list = []
96 # Cursor loop
97 while next_cursor != 0:
98 list = t.mutes.users.list(
99 screen_name=g['original_name'],
100 cursor=next_cursor,
101 skip_status=True,
102 include_entities=False,
103 )
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
108 if dict_data:
109 return dict(zip(screen_name_list, name_list))
110 else:
111 return screen_name_list
112
113
114def init(args):
115 """
116 Init function
117 """
118 # Handle Ctrl C
119 ctrl_c_handler = lambda signum, frame: quit()
120 signal.signal(signal.SIGINT, ctrl_c_handler)
121 # Get name
122 t = Twitter(auth=authen())
123 name = '@' + t.account.verify_credentials()['screen_name']
124 if not get_config('PREFIX'):
125 set_config('PREFIX', name)
126 g['original_name'] = name[1:]
127 g['decorated_name'] = lambda x: color_func(
128 c['DECORATED_NAME'])('[' + x + ']: ')
129 # Theme init
130 files = os.listdir(os.path.dirname(__file__) + '/colorset')
131 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
132 g['themes'] = themes
133 # Startup cmd
134 g['cmd'] = ''
135 # Semaphore init
136 c['lock'] = False
137 c['pause'] = False
138 # Init tweet dict and message dict
139 c['tweet_dict'] = []
140 c['message_dict'] = []
141 # Image on term
142 c['IMAGE_ON_TERM'] = args.image_on_term
143 set_config('IMAGE_ON_TERM', str(c['IMAGE_ON_TERM']))
144 # Mute dict
145 c['IGNORE_LIST'] += build_mute_dict()
146
147
148def switch():
149 """
150 Switch stream
151 """
152 try:
153 target = g['stuff'].split()[0]
154 # Filter and ignore
155 args = parse_arguments()
156 try:
157 if g['stuff'].split()[-1] == '-f':
158 guide = 'To ignore an option, just hit Enter key.'
159 printNicely(light_magenta(guide))
160 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
161 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
162 args.filter = filter(None, only.split(','))
163 args.ignore = filter(None, ignore.split(','))
164 elif g['stuff'].split()[-1] == '-d':
165 args.filter = c['ONLY_LIST']
166 args.ignore = c['IGNORE_LIST']
167 except:
168 printNicely(red('Sorry, wrong format.'))
169 return
170 # Public stream
171 if target == 'public':
172 keyword = g['stuff'].split()[1]
173 if keyword[0] == '#':
174 keyword = keyword[1:]
175 # Kill old thread
176 g['stream_stop'] = True
177 args.track_keywords = keyword
178 # Start new thread
179 th = threading.Thread(
180 target=stream,
181 args=(
182 c['PUBLIC_DOMAIN'],
183 args))
184 th.daemon = True
185 th.start()
186 # Personal stream
187 elif target == 'mine':
188 # Kill old thread
189 g['stream_stop'] = True
190 # Start new thread
191 th = threading.Thread(
192 target=stream,
193 args=(
194 c['USER_DOMAIN'],
195 args,
196 g['original_name']))
197 th.daemon = True
198 th.start()
199 printNicely('')
200 if args.filter:
201 printNicely(cyan('Only: ' + str(args.filter)))
202 if args.ignore:
203 printNicely(red('Ignore: ' + str(args.ignore)))
204 printNicely('')
205 except:
206 printNicely(red('Sorry I can\'t understand.'))
207
208
209def trend():
210 """
211 Trend
212 """
213 t = Twitter(auth=authen())
214 # Get country and town
215 try:
216 country = g['stuff'].split()[0]
217 except:
218 country = ''
219 try:
220 town = g['stuff'].split()[1]
221 except:
222 town = ''
223 avail = t.trends.available()
224 # World wide
225 if not country:
226 trends = t.trends.place(_id=1)[0]['trends']
227 print_trends(trends)
228 else:
229 for location in avail:
230 # Search for country and Town
231 if town:
232 if location['countryCode'] == country \
233 and location['placeType']['name'] == 'Town' \
234 and location['name'] == town:
235 trends = t.trends.place(_id=location['woeid'])[0]['trends']
236 print_trends(trends)
237 # Search for country only
238 else:
239 if location['countryCode'] == country \
240 and location['placeType']['name'] == 'Country':
241 trends = t.trends.place(_id=location['woeid'])[0]['trends']
242 print_trends(trends)
243
244
245def home():
246 """
247 Home
248 """
249 t = Twitter(auth=authen())
250 num = c['HOME_TWEET_NUM']
251 if g['stuff'].isdigit():
252 num = int(g['stuff'])
253 for tweet in reversed(t.statuses.home_timeline(count=num)):
254 draw(t=tweet)
255 printNicely('')
256
257
258def view():
259 """
260 Friend view
261 """
262 t = Twitter(auth=authen())
263 user = g['stuff'].split()[0]
264 if user[0] == '@':
265 try:
266 num = int(g['stuff'].split()[1])
267 except:
268 num = c['HOME_TWEET_NUM']
269 for tweet in reversed(t.statuses.user_timeline(count=num, screen_name=user[1:])):
270 draw(t=tweet)
271 printNicely('')
272 else:
273 printNicely(red('A name should begin with a \'@\''))
274
275
276def mentions():
277 """
278 Mentions timeline
279 """
280 t = Twitter(auth=authen())
281 num = c['HOME_TWEET_NUM']
282 if g['stuff'].isdigit():
283 num = int(g['stuff'])
284 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
285 draw(t=tweet)
286 printNicely('')
287
288
289def tweet():
290 """
291 Tweet
292 """
293 t = Twitter(auth=authen())
294 t.statuses.update(status=g['stuff'])
295
296
297def retweet():
298 """
299 ReTweet
300 """
301 t = Twitter(auth=authen())
302 try:
303 id = int(g['stuff'].split()[0])
304 except:
305 printNicely(red('Sorry I can\'t understand.'))
306 return
307 tid = c['tweet_dict'][id]
308 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
309
310
311def quote():
312 """
313 Quote a tweet
314 """
315 # Retrieve info
316 t = Twitter(auth=authen())
317 try:
318 id = int(g['stuff'].split()[0])
319 except:
320 printNicely(red('Sorry I can\'t understand.'))
321 return
322 tid = c['tweet_dict'][id]
323 tweet = t.statuses.show(id=tid)
324 screen_name = '@' + tweet['user']['screen_name']
325 text = tweet['text']
326 # Validate quote format
327 if '#owner' not in c['QUOTE_FORMAT']:
328 printNicely(light_magenta('Quote should contains #owner'))
329 return
330 if '#comment' not in c['QUOTE_FORMAT']:
331 printNicely(light_magenta('Quote format should have #comment'))
332 return
333 # Notice
334 notice = light_magenta('Current quote format is: ')
335 notice += light_green(c['QUOTE_FORMAT'])
336 printNicely(notice)
337 # Build formater
338 formater = ''
339 try:
340 formater = c['QUOTE_FORMAT']
341 formater = screen_name.join(formater.split('#owner'))
342 formater = text.join(formater.split('#tweet'))
343 formater = u2str(formater)
344 except:
345 pass
346 # Get comment
347 prefix = light_magenta('Compose your ') + light_green('#comment: ')
348 comment = raw_input(prefix)
349 if comment:
350 quote = comment.join(formater.split('#comment'))
351 t.statuses.update(status = quote)
352 else:
353 printNicely(light_magenta('No text added.'))
354
355
356def allretweet():
357 """
358 List all retweet
359 """
360 t = Twitter(auth=authen())
361 # Get rainbow id
362 try:
363 id = int(g['stuff'].split()[0])
364 except:
365 printNicely(red('Sorry I can\'t understand.'))
366 return
367 tid = c['tweet_dict'][id]
368 # Get display num if exist
369 try:
370 num = int(g['stuff'].split()[1])
371 except:
372 num = c['RETWEETS_SHOW_NUM']
373 # Get result and display
374 rt_ary = t.statuses.retweets(id=tid, count=num)
375 if not rt_ary:
376 printNicely(magenta('This tweet has no retweet.'))
377 return
378 for tweet in reversed(rt_ary):
379 draw(t=tweet)
380 printNicely('')
381
382
383def favorite():
384 """
385 Favorite
386 """
387 t = Twitter(auth=authen())
388 try:
389 id = int(g['stuff'].split()[0])
390 except:
391 printNicely(red('Sorry I can\'t understand.'))
392 return
393 tid = c['tweet_dict'][id]
394 t.favorites.create(_id=tid, include_entities=False)
395 printNicely(green('Favorited.'))
396 draw(t.statuses.show(id=tid))
397 printNicely('')
398
399
400def reply():
401 """
402 Reply
403 """
404 t = Twitter(auth=authen())
405 try:
406 id = int(g['stuff'].split()[0])
407 except:
408 printNicely(red('Sorry I can\'t understand.'))
409 return
410 tid = c['tweet_dict'][id]
411 user = t.statuses.show(id=tid)['user']['screen_name']
412 status = ' '.join(g['stuff'].split()[1:])
413 status = '@' + user + ' ' + str2u(status)
414 t.statuses.update(status=status, in_reply_to_status_id=tid)
415
416
417def delete():
418 """
419 Delete
420 """
421 t = Twitter(auth=authen())
422 try:
423 id = int(g['stuff'].split()[0])
424 except:
425 printNicely(red('Sorry I can\'t understand.'))
426 return
427 tid = c['tweet_dict'][id]
428 t.statuses.destroy(id=tid)
429 printNicely(green('Okay it\'s gone.'))
430
431
432def unfavorite():
433 """
434 Unfavorite
435 """
436 t = Twitter(auth=authen())
437 try:
438 id = int(g['stuff'].split()[0])
439 except:
440 printNicely(red('Sorry I can\'t understand.'))
441 return
442 tid = c['tweet_dict'][id]
443 t.favorites.destroy(_id=tid)
444 printNicely(green('Okay it\'s unfavorited.'))
445 draw(t.statuses.show(id=tid))
446 printNicely('')
447
448
449def search():
450 """
451 Search
452 """
453 t = Twitter(auth=authen())
454 g['stuff'] = g['stuff'].strip()
455 rel = t.search.tweets(q=g['stuff'])['statuses']
456 if rel:
457 printNicely('Newest tweets:')
458 for i in reversed(xrange(c['SEARCH_MAX_RECORD'])):
459 draw(t=rel[i],
460 keyword=g['stuff'])
461 printNicely('')
462 else:
463 printNicely(magenta('I\'m afraid there is no result'))
464
465
466def message():
467 """
468 Send a direct message
469 """
470 t = Twitter(auth=authen())
471 user = g['stuff'].split()[0]
472 if user[0].startswith('@'):
473 try:
474 content = g['stuff'].split()[1]
475 except:
476 printNicely(red('Sorry I can\'t understand.'))
477 t.direct_messages.new(
478 screen_name=user[1:],
479 text=content
480 )
481 printNicely(green('Message sent.'))
482 else:
483 printNicely(red('A name should begin with a \'@\''))
484
485
486def show():
487 """
488 Show image
489 """
490 t = Twitter(auth=authen())
491 try:
492 target = g['stuff'].split()[0]
493 if target != 'image':
494 return
495 id = int(g['stuff'].split()[1])
496 tid = c['tweet_dict'][id]
497 tweet = t.statuses.show(id=tid)
498 media = tweet['entities']['media']
499 for m in media:
500 res = requests.get(m['media_url'])
501 img = Image.open(BytesIO(res.content))
502 img.show()
503 except:
504 printNicely(red('Sorry I can\'t show this image.'))
505
506
507def urlopen():
508 """
509 Open url
510 """
511 t = Twitter(auth=authen())
512 try:
513 if not g['stuff'].isdigit():
514 return
515 tid = c['tweet_dict'][int(g['stuff'])]
516 tweet = t.statuses.show(id=tid)
517 link_ary = [
518 u for u in tweet['text'].split() if u.startswith('http://')]
519 if not link_ary:
520 printNicely(light_magenta('No url here @.@!'))
521 return
522 for link in link_ary:
523 webbrowser.open(link)
524 except:
525 printNicely(red('Sorry I can\'t open url in this tweet.'))
526
527
528def ls():
529 """
530 List friends for followers
531 """
532 t = Twitter(auth=authen())
533 # Get name
534 try:
535 name = g['stuff'].split()[1]
536 if name.startswith('@'):
537 name = name[1:]
538 else:
539 printNicely(red('A name should begin with a \'@\''))
540 raise Exception('Invalid name')
541 except:
542 name = g['original_name']
543 # Get list followers or friends
544 try:
545 target = g['stuff'].split()[0]
546 except:
547 printNicely(red('Omg some syntax is wrong.'))
548 # Init cursor
549 d = {'fl': 'followers', 'fr': 'friends'}
550 next_cursor = -1
551 rel = {}
552 # Cursor loop
553 while next_cursor != 0:
554 list = getattr(t, d[target]).list(
555 screen_name=name,
556 cursor=next_cursor,
557 skip_status=True,
558 include_entities=False,
559 )
560 for u in list['users']:
561 rel[u['name']] = '@' + u['screen_name']
562 next_cursor = list['next_cursor']
563 # Print out result
564 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
565 for name in rel:
566 user = ' ' + cycle_color(name)
567 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
568 printNicely(user)
569
570
571def inbox():
572 """
573 Inbox direct messages
574 """
575 t = Twitter(auth=authen())
576 num = c['MESSAGES_DISPLAY']
577 rel = []
578 if g['stuff'].isdigit():
579 num = g['stuff']
580 cur_page = 1
581 # Max message per page is 20 so we have to loop
582 while num > 20:
583 rel = rel + t.direct_messages(
584 count=20,
585 page=cur_page,
586 include_entities=False,
587 skip_status=False
588 )
589 num -= 20
590 cur_page += 1
591 rel = rel + t.direct_messages(
592 count=num,
593 page=cur_page,
594 include_entities=False,
595 skip_status=False
596 )
597 # Display
598 printNicely('Inbox: newest ' + str(len(rel)) + ' messages.')
599 for m in reversed(rel):
600 print_message(m)
601 printNicely('')
602
603
604def sent():
605 """
606 Sent direct messages
607 """
608 t = Twitter(auth=authen())
609 num = c['MESSAGES_DISPLAY']
610 rel = []
611 if g['stuff'].isdigit():
612 num = int(g['stuff'])
613 cur_page = 1
614 # Max message per page is 20 so we have to loop
615 while num > 20:
616 rel = rel + t.direct_messages.sent(
617 count=20,
618 page=cur_page,
619 include_entities=False,
620 skip_status=False
621 )
622 num -= 20
623 cur_page += 1
624 rel = rel + t.direct_messages.sent(
625 count=num,
626 page=cur_page,
627 include_entities=False,
628 skip_status=False
629 )
630 # Display
631 printNicely('Sent: newest ' + str(len(rel)) + ' messages.')
632 for m in reversed(rel):
633 print_message(m)
634 printNicely('')
635
636
637def trash():
638 """
639 Remove message
640 """
641 t = Twitter(auth=authen())
642 try:
643 id = int(g['stuff'].split()[0])
644 except:
645 printNicely(red('Sorry I can\'t understand.'))
646 mid = c['message_dict'][id]
647 t.direct_messages.destroy(id=mid)
648 printNicely(green('Message deleted.'))
649
650
651def whois():
652 """
653 Show profile of a specific user
654 """
655 t = Twitter(auth=authen())
656 screen_name = g['stuff'].split()[0]
657 if screen_name.startswith('@'):
658 try:
659 user = t.users.show(
660 screen_name=screen_name[1:],
661 include_entities=False)
662 show_profile(user)
663 except:
664 printNicely(red('Omg no user.'))
665 else:
666 printNicely(red('A name should begin with a \'@\''))
667
668
669def follow():
670 """
671 Follow a user
672 """
673 t = Twitter(auth=authen())
674 screen_name = g['stuff'].split()[0]
675 if screen_name.startswith('@'):
676 t.friendships.create(screen_name=screen_name[1:], follow=True)
677 printNicely(green('You are following ' + screen_name + ' now!'))
678 else:
679 printNicely(red('A name should begin with a \'@\''))
680
681
682def unfollow():
683 """
684 Unfollow a user
685 """
686 t = Twitter(auth=authen())
687 screen_name = g['stuff'].split()[0]
688 if screen_name.startswith('@'):
689 t.friendships.destroy(
690 screen_name=screen_name[1:],
691 include_entities=False)
692 printNicely(green('Unfollow ' + screen_name + ' success!'))
693 else:
694 printNicely(red('A name should begin with a \'@\''))
695
696
697def mute():
698 """
699 Mute a user
700 """
701 t = Twitter(auth=authen())
702 try:
703 screen_name = g['stuff'].split()[0]
704 except:
705 printNicely(red('A name should be specified. '))
706 return
707 if screen_name.startswith('@'):
708 try:
709 rel = t.mutes.users.create(screen_name=screen_name[1:])
710 if isinstance(rel, dict):
711 printNicely(green(screen_name + ' is muted.'))
712 c['IGNORE_LIST'] += [unc(screen_name)]
713 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
714 else:
715 printNicely(red(rel))
716 except:
717 printNicely(red('Something is wrong, can not mute now :('))
718 else:
719 printNicely(red('A name should begin with a \'@\''))
720
721
722def unmute():
723 """
724 Unmute a user
725 """
726 t = Twitter(auth=authen())
727 try:
728 screen_name = g['stuff'].split()[0]
729 except:
730 printNicely(red('A name should be specified. '))
731 return
732 if screen_name.startswith('@'):
733 try:
734 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
735 if isinstance(rel, dict):
736 printNicely(green(screen_name + ' is unmuted.'))
737 c['IGNORE_LIST'].remove(screen_name)
738 else:
739 printNicely(red(rel))
740 except:
741 printNicely(red('Maybe you are not muting this person ?'))
742 else:
743 printNicely(red('A name should begin with a \'@\''))
744
745
746def muting():
747 """
748 List muting user
749 """
750 # Get dict of muting users
751 md = build_mute_dict(dict_data=True)
752 printNicely('All: ' + str(len(md)) + ' people.')
753 for name in md:
754 user = ' ' + cycle_color(md[name])
755 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
756 printNicely(user)
757 # Update from Twitter
758 c['IGNORE_LIST'] = [n for n in md]
759
760
761def block():
762 """
763 Block a user
764 """
765 t = Twitter(auth=authen())
766 screen_name = g['stuff'].split()[0]
767 if screen_name.startswith('@'):
768 t.blocks.create(
769 screen_name=screen_name[1:],
770 include_entities=False,
771 skip_status=True)
772 printNicely(green('You blocked ' + screen_name + '.'))
773 else:
774 printNicely(red('A name should begin with a \'@\''))
775
776
777def unblock():
778 """
779 Unblock a user
780 """
781 t = Twitter(auth=authen())
782 screen_name = g['stuff'].split()[0]
783 if screen_name.startswith('@'):
784 t.blocks.destroy(
785 screen_name=screen_name[1:],
786 include_entities=False,
787 skip_status=True)
788 printNicely(green('Unblock ' + screen_name + ' success!'))
789 else:
790 printNicely(red('A name should begin with a \'@\''))
791
792
793def report():
794 """
795 Report a user as a spam account
796 """
797 t = Twitter(auth=authen())
798 screen_name = g['stuff'].split()[0]
799 if screen_name.startswith('@'):
800 t.users.report_spam(
801 screen_name=screen_name[1:])
802 printNicely(green('You reported ' + screen_name + '.'))
803 else:
804 printNicely(red('Sorry I can\'t understand.'))
805
806
807def get_slug():
808 """
809 Get Slug Decorator
810 """
811 # Get list name
812 list_name = raw_input(light_magenta('Give me the list\'s name: '))
813 # Get list name and owner
814 try:
815 owner, slug = list_name.split('/')
816 if slug.startswith('@'):
817 slug = slug[1:]
818 return owner, slug
819 except:
820 printNicely(
821 light_magenta('List name should follow "@owner/list_name" format.'))
822 raise Exception('Wrong list name')
823
824
825def show_lists(t):
826 """
827 List list
828 """
829 rel = t.lists.list(screen_name=g['original_name'])
830 if rel:
831 print_list(rel)
832 else:
833 printNicely(light_magenta('You belong to no lists :)'))
834
835
836def list_home(t):
837 """
838 List home
839 """
840 owner, slug = get_slug()
841 res = t.lists.statuses(
842 slug=slug,
843 owner_screen_name=owner,
844 count=c['LIST_MAX'],
845 include_entities=False)
846 for tweet in res:
847 draw(t=tweet)
848 printNicely('')
849
850
851def list_members(t):
852 """
853 List members
854 """
855 owner, slug = get_slug()
856 # Get members
857 rel = {}
858 next_cursor = -1
859 while next_cursor != 0:
860 m = t.lists.members(
861 slug=slug,
862 owner_screen_name=owner,
863 cursor=next_cursor,
864 include_entities=False)
865 for u in m['users']:
866 rel[u['name']] = '@' + u['screen_name']
867 next_cursor = m['next_cursor']
868 printNicely('All: ' + str(len(rel)) + ' members.')
869 for name in rel:
870 user = ' ' + cycle_color(name)
871 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
872 printNicely(user)
873
874
875def list_subscribers(t):
876 """
877 List subscribers
878 """
879 owner, slug = get_slug()
880 # Get subscribers
881 rel = {}
882 next_cursor = -1
883 while next_cursor != 0:
884 m = t.lists.subscribers(
885 slug=slug,
886 owner_screen_name=owner,
887 cursor=next_cursor,
888 include_entities=False)
889 for u in m['users']:
890 rel[u['name']] = '@' + u['screen_name']
891 next_cursor = m['next_cursor']
892 printNicely('All: ' + str(len(rel)) + ' subscribers.')
893 for name in rel:
894 user = ' ' + cycle_color(name)
895 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
896 printNicely(user)
897
898
899def list_add(t):
900 """
901 Add specific user to a list
902 """
903 owner, slug = get_slug()
904 # Add
905 user_name = raw_input(light_magenta('Give me name of the newbie: '))
906 if user_name.startswith('@'):
907 user_name = user_name[1:]
908 try:
909 t.lists.members.create(
910 slug=slug,
911 owner_screen_name=owner,
912 screen_name=user_name)
913 printNicely(green('Added.'))
914 except:
915 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
916
917
918def list_remove(t):
919 """
920 Remove specific user from a list
921 """
922 owner, slug = get_slug()
923 # Remove
924 user_name = raw_input(light_magenta('Give me name of the unlucky one: '))
925 if user_name.startswith('@'):
926 user_name = user_name[1:]
927 try:
928 t.lists.members.destroy(
929 slug=slug,
930 owner_screen_name=owner,
931 screen_name=user_name)
932 printNicely(green('Gone.'))
933 except:
934 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
935
936
937def list_subscribe(t):
938 """
939 Subscribe to a list
940 """
941 owner, slug = get_slug()
942 # Subscribe
943 try:
944 t.lists.subscribers.create(
945 slug=slug,
946 owner_screen_name=owner)
947 printNicely(green('Done.'))
948 except:
949 printNicely(
950 light_magenta('I\'m sorry you can not subscribe to this list.'))
951
952
953def list_unsubscribe(t):
954 """
955 Unsubscribe a list
956 """
957 owner, slug = get_slug()
958 # Subscribe
959 try:
960 t.lists.subscribers.destroy(
961 slug=slug,
962 owner_screen_name=owner)
963 printNicely(green('Done.'))
964 except:
965 printNicely(
966 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
967
968
969def list_own(t):
970 """
971 List own
972 """
973 rel = []
974 next_cursor = -1
975 while next_cursor != 0:
976 res = t.lists.ownerships(
977 screen_name=g['original_name'],
978 cursor=next_cursor)
979 rel += res['lists']
980 next_cursor = res['next_cursor']
981 if rel:
982 print_list(rel)
983 else:
984 printNicely(light_magenta('You own no lists :)'))
985
986
987def list_new(t):
988 """
989 Create a new list
990 """
991 name = raw_input(light_magenta('New list\'s name: '))
992 mode = raw_input(light_magenta('New list\'s mode (public/private): '))
993 description = raw_input(light_magenta('New list\'s description: '))
994 try:
995 t.lists.create(
996 name=name,
997 mode=mode,
998 description=description)
999 printNicely(green(name + ' list is created.'))
1000 except:
1001 printNicely(red('Oops something is wrong with Twitter :('))
1002
1003
1004def list_update(t):
1005 """
1006 Update a list
1007 """
1008 slug = raw_input(light_magenta('Your list that you want to update: '))
1009 name = raw_input(light_magenta('Update name (leave blank to unchange): '))
1010 mode = raw_input(light_magenta('Update mode (public/private): '))
1011 description = raw_input(light_magenta('Update description: '))
1012 try:
1013 if name:
1014 t.lists.update(
1015 slug='-'.join(slug.split()),
1016 owner_screen_name=g['original_name'],
1017 name=name,
1018 mode=mode,
1019 description=description)
1020 else:
1021 t.lists.update(
1022 slug=slug,
1023 owner_screen_name=g['original_name'],
1024 mode=mode,
1025 description=description)
1026 printNicely(green(slug + ' list is updated.'))
1027 except:
1028 printNicely(red('Oops something is wrong with Twitter :('))
1029
1030
1031def list_delete(t):
1032 """
1033 Delete a list
1034 """
1035 slug = raw_input(light_magenta('Your list that you want to update: '))
1036 try:
1037 t.lists.destroy(
1038 slug='-'.join(slug.split()),
1039 owner_screen_name=g['original_name'])
1040 printNicely(green(slug + ' list is deleted.'))
1041 except:
1042 printNicely(red('Oops something is wrong with Twitter :('))
1043
1044
1045def twitterlist():
1046 """
1047 Twitter's list
1048 """
1049 t = Twitter(auth=authen())
1050 # List all lists or base on action
1051 try:
1052 g['list_action'] = g['stuff'].split()[0]
1053 except:
1054 show_lists(t)
1055 return
1056 # Sub-function
1057 action_ary = {
1058 'home': list_home,
1059 'all_mem': list_members,
1060 'all_sub': list_subscribers,
1061 'add': list_add,
1062 'rm': list_remove,
1063 'sub': list_subscribe,
1064 'unsub': list_unsubscribe,
1065 'own': list_own,
1066 'new': list_new,
1067 'update': list_update,
1068 'del': list_delete,
1069 }
1070 try:
1071 return action_ary[g['list_action']](t)
1072 except:
1073 printNicely(red('Please try again.'))
1074
1075
1076def cal():
1077 """
1078 Unix's command `cal`
1079 """
1080 # Format
1081 rel = os.popen('cal').read().split('\n')
1082 month = rel.pop(0)
1083 date = rel.pop(0)
1084 show_calendar(month, date, rel)
1085
1086
1087def config():
1088 """
1089 Browse and change config
1090 """
1091 all_config = get_all_config()
1092 g['stuff'] = g['stuff'].strip()
1093 # List all config
1094 if not g['stuff']:
1095 for k in all_config:
1096 line = ' ' * 2 + \
1097 green(k) + ': ' + light_yellow(str(all_config[k]))
1098 printNicely(line)
1099 guide = 'Detailed explanation can be found at ' + \
1100 color_func(c['TWEET']['link'])(
1101 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1102 printNicely(guide)
1103 # Print specific config
1104 elif len(g['stuff'].split()) == 1:
1105 if g['stuff'] in all_config:
1106 k = g['stuff']
1107 line = ' ' * 2 + \
1108 green(k) + ': ' + light_yellow(str(all_config[k]))
1109 printNicely(line)
1110 else:
1111 printNicely(red('No such config key.'))
1112 # Print specific config's default value
1113 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1114 key = g['stuff'].split()[0]
1115 try:
1116 value = get_default_config(key)
1117 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
1118 printNicely(line)
1119 except Exception as e:
1120 printNicely(red(e))
1121 # Delete specific config key in config file
1122 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1123 key = g['stuff'].split()[0]
1124 try:
1125 delete_config(key)
1126 printNicely(green('Config key is dropped.'))
1127 except Exception as e:
1128 printNicely(red(e))
1129 # Set specific config
1130 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
1131 key = g['stuff'].split()[0]
1132 value = g['stuff'].split()[-1]
1133 if key == 'THEME' and not validate_theme(value):
1134 printNicely(red('Invalid theme\'s value.'))
1135 return
1136 try:
1137 set_config(key, value)
1138 # Apply theme immediately
1139 if key == 'THEME':
1140 c['THEME'] = reload_theme(value, c['THEME'])
1141 g['decorated_name'] = lambda x: color_func(
1142 c['DECORATED_NAME'])('[' + x + ']: ')
1143 reload_config()
1144 printNicely(green('Updated successfully.'))
1145 except Exception as e:
1146 printNicely(red(e))
1147 else:
1148 printNicely(light_magenta('Sorry I can\'s understand.'))
1149
1150
1151def theme():
1152 """
1153 List and change theme
1154 """
1155 if not g['stuff']:
1156 # List themes
1157 for theme in g['themes']:
1158 line = light_magenta(theme)
1159 if c['THEME'] == theme:
1160 line = ' ' * 2 + light_yellow('* ') + line
1161 else:
1162 line = ' ' * 4 + line
1163 printNicely(line)
1164 else:
1165 # Change theme
1166 try:
1167 # Load new theme
1168 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1169 # Redefine decorated_name
1170 g['decorated_name'] = lambda x: color_func(
1171 c['DECORATED_NAME'])(
1172 '[' + x + ']: ')
1173 printNicely(green('Theme changed.'))
1174 except:
1175 printNicely(red('No such theme exists.'))
1176
1177
1178def help_discover():
1179 """
1180 Discover the world
1181 """
1182 s = ' ' * 2
1183 # Discover the world
1184 usage = '\n'
1185 usage += s + grey(u'\u266A' + ' Discover the world \n')
1186 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1187 'You can try ' + light_green('trend US') + ' or ' + \
1188 light_green('trend JP Tokyo') + '.\n'
1189 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1190 light_green('home 7') + ' will show 7 tweets.\n'
1191 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1192 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1193 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
1194 magenta('@mdo') + '.\n'
1195 usage += s * 2 + light_green('view @mdo') + \
1196 ' will show ' + magenta('@mdo') + '\'s home.\n'
1197 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1198 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1199 'Search can be performed with or without hashtag.\n'
1200 printNicely(usage)
1201
1202
1203def help_tweets():
1204 """
1205 Tweets
1206 """
1207 s = ' ' * 2
1208 # Tweet
1209 usage = '\n'
1210 usage += s + grey(u'\u266A' + ' Tweets \n')
1211 usage += s * 2 + light_green('t oops ') + \
1212 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1213 usage += s * 2 + \
1214 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1215 light_yellow('[id=12]') + '.\n'
1216 usage += s * 2 + \
1217 light_green('quote 12 ') + ' will quote the tweet with ' + \
1218 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1219 'the quote will be canceled.\n'
1220 usage += s * 2 + \
1221 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1222 light_yellow('[id=12]') + '.\n'
1223 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1224 light_yellow('oops') + '" to tweet with ' + \
1225 light_yellow('[id=12]') + '.\n'
1226 usage += s * 2 + \
1227 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1228 light_yellow('[id=12]') + '.\n'
1229 usage += s * 2 + \
1230 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1231 light_yellow('[id=12]') + '.\n'
1232 usage += s * 2 + \
1233 light_green('del 12 ') + ' will delete tweet with ' + \
1234 light_yellow('[id=12]') + '.\n'
1235 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1236 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1237 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1238 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1239 printNicely(usage)
1240
1241
1242def help_messages():
1243 """
1244 Messages
1245 """
1246 s = ' ' * 2
1247 # Direct message
1248 usage = '\n'
1249 usage += s + grey(u'\u266A' + ' Direct messages \n')
1250 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1251 light_green('inbox 7') + ' will show newest 7 messages.\n'
1252 usage += s * 2 + light_green('sent') + ' will show sent messages. ' + \
1253 light_green('sent 7') + ' will show newest 7 messages.\n'
1254 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1255 magenta('@dtvd88') + '.\n'
1256 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1257 light_yellow('[message_id=5]') + '.\n'
1258 printNicely(usage)
1259
1260
1261def help_friends_and_followers():
1262 """
1263 Friends and Followers
1264 """
1265 s = ' ' * 2
1266 # Follower and following
1267 usage = '\n'
1268 usage += s + grey(u'\u266A' + ' Friends and followers \n')
1269 usage += s * 2 + \
1270 light_green('ls fl') + \
1271 ' will list all followers (people who are following you).\n'
1272 usage += s * 2 + \
1273 light_green('ls fr') + \
1274 ' will list all friends (people who you are following).\n'
1275 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
1276 magenta('@dtvd88') + '.\n'
1277 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1278 magenta('@dtvd88') + '.\n'
1279 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
1280 magenta('@dtvd88') + '.\n'
1281 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1282 magenta('@dtvd88') + '.\n'
1283 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1284 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
1285 magenta('@dtvd88') + '.\n'
1286 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1287 magenta('@dtvd88') + '.\n'
1288 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
1289 magenta('@dtvd88') + ' as a spam account.\n'
1290 printNicely(usage)
1291
1292
1293def help_list():
1294 """
1295 Lists
1296 """
1297 s = ' ' * 2
1298 # Twitter list
1299 usage = '\n'
1300 usage += s + grey(u'\u266A' + ' Twitter list\n')
1301 usage += s * 2 + light_green('list') + \
1302 ' will show all lists you are belong to.\n'
1303 usage += s * 2 + light_green('list home') + \
1304 ' will show timeline of list. You will be asked for list\'s name.\n'
1305 usage += s * 2 + light_green('list all_mem') + \
1306 ' will show list\'s all members.\n'
1307 usage += s * 2 + light_green('list all_sub') + \
1308 ' will show list\'s all subscribers.\n'
1309 usage += s * 2 + light_green('list add') + \
1310 ' will add specific person to a list owned by you.' + \
1311 ' You will be asked for list\'s name and person\'s name.\n'
1312 usage += s * 2 + light_green('list rm') + \
1313 ' will remove specific person from a list owned by you.' + \
1314 ' You will be asked for list\'s name and person\'s name.\n'
1315 usage += s * 2 + light_green('list sub') + \
1316 ' will subscribe you to a specific list.\n'
1317 usage += s * 2 + light_green('list unsub') + \
1318 ' will unsubscribe you from a specific list.\n'
1319 usage += s * 2 + light_green('list own') + \
1320 ' will show all list owned by you.\n'
1321 usage += s * 2 + light_green('list new') + \
1322 ' will create a new list.\n'
1323 usage += s * 2 + light_green('list update') + \
1324 ' will update a list owned by you.\n'
1325 usage += s * 2 + light_green('list del') + \
1326 ' will delete a list owned by you.\n'
1327 printNicely(usage)
1328
1329
1330def help_stream():
1331 """
1332 Stream switch
1333 """
1334 s = ' ' * 2
1335 # Switch
1336 usage = '\n'
1337 usage += s + grey(u'\u266A' + ' Switching streams \n')
1338 usage += s * 2 + light_green('switch public #AKB') + \
1339 ' will switch to public stream and follow "' + \
1340 light_yellow('AKB') + '" keyword.\n'
1341 usage += s * 2 + light_green('switch mine') + \
1342 ' will switch to your personal stream.\n'
1343 usage += s * 2 + light_green('switch mine -f ') + \
1344 ' will prompt to enter the filter.\n'
1345 usage += s * 3 + light_yellow('Only nicks') + \
1346 ' filter will decide nicks will be INCLUDE ONLY.\n'
1347 usage += s * 3 + light_yellow('Ignore nicks') + \
1348 ' filter will decide nicks will be EXCLUDE.\n'
1349 usage += s * 2 + light_green('switch mine -d') + \
1350 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1351 printNicely(usage)
1352
1353
1354def help():
1355 """
1356 Help
1357 """
1358 s = ' ' * 2
1359 h, w = os.popen('stty size', 'r').read().split()
1360 # Start
1361 usage = '\n'
1362 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1363 usage += s + '-' * (int(w) - 4) + '\n'
1364 usage += s + 'You are ' + \
1365 light_yellow('already') + ' on your personal stream.\n'
1366 usage += s + 'Any update from Twitter will show up ' + \
1367 light_yellow('immediately') + '.\n'
1368 usage += s + 'In addtion, following commands are available right now:\n'
1369 # Twitter help section
1370 usage += '\n'
1371 usage += s + grey(u'\u266A' + ' Twitter help\n')
1372 usage += s * 2 + light_green('h discover') + \
1373 ' will show help for discover commands.\n'
1374 usage += s * 2 + light_green('h tweets') + \
1375 ' will show help for tweets commands.\n'
1376 usage += s * 2 + light_green('h messages') + \
1377 ' will show help for messages commands.\n'
1378 usage += s * 2 + light_green('h friends_and_followers') + \
1379 ' will show help for friends and followers commands.\n'
1380 usage += s * 2 + light_green('h list') + \
1381 ' will show help for list commands.\n'
1382 usage += s * 2 + light_green('h stream') + \
1383 ' will show help for stream commands.\n'
1384 # Smart shell
1385 usage += '\n'
1386 usage += s + grey(u'\u266A' + ' Smart shell\n')
1387 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1388 'will be evaluate by Python interpreter.\n'
1389 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1390 ' for current month.\n'
1391 # Config
1392 usage += '\n'
1393 usage += s + grey(u'\u266A' + ' Config \n')
1394 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
1395 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1396 ' theme immediately.\n'
1397 usage += s * 2 + light_green('config') + ' will list all config.\n'
1398 usage += s * 3 + \
1399 light_green('config ASCII_ART') + ' will output current value of ' +\
1400 light_yellow('ASCII_ART') + ' config key.\n'
1401 usage += s * 3 + \
1402 light_green('config TREND_MAX default') + ' will output default value of ' + \
1403 light_yellow('TREND_MAX') + ' config key.\n'
1404 usage += s * 3 + \
1405 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1406 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1407 usage += s * 3 + \
1408 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1409 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1410 light_yellow('True') + '.\n'
1411 # Screening
1412 usage += '\n'
1413 usage += s + grey(u'\u266A' + ' Screening \n')
1414 usage += s * 2 + light_green('h') + ' will show this help again.\n'
1415 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1416 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
1417 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1418 usage += s * 2 + light_green('q') + ' will quit.\n'
1419 # End
1420 usage += '\n'
1421 usage += s + '-' * (int(w) - 4) + '\n'
1422 usage += s + 'Have fun and hang tight! \n'
1423 # Show help
1424 d = {
1425 'discover': help_discover,
1426 'tweets': help_tweets,
1427 'messages': help_messages,
1428 'friends_and_followers': help_friends_and_followers,
1429 'list': help_list,
1430 'stream': help_stream,
1431 }
1432 if g['stuff']:
1433 d.get(
1434 g['stuff'].strip(),
1435 lambda: printNicely(red('No such command.'))
1436 )()
1437 else:
1438 printNicely(usage)
1439
1440
1441def pause():
1442 """
1443 Pause stream display
1444 """
1445 c['pause'] = True
1446 printNicely(green('Stream is paused'))
1447
1448
1449def replay():
1450 """
1451 Replay stream
1452 """
1453 c['pause'] = False
1454 printNicely(green('Stream is running back now'))
1455
1456
1457def clear():
1458 """
1459 Clear screen
1460 """
1461 os.system('clear')
1462
1463
1464def quit():
1465 """
1466 Exit all
1467 """
1468 try:
1469 save_history()
1470 printNicely(green('See you next time :)'))
1471 except:
1472 pass
1473 sys.exit()
1474
1475
1476def reset():
1477 """
1478 Reset prefix of line
1479 """
1480 if g['reset']:
1481 if c.get('USER_JSON_ERROR'):
1482 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1483 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1484 printNicely('')
1485 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1486 g['reset'] = False
1487 try:
1488 printNicely(str(eval(g['cmd'])))
1489 except Exception:
1490 pass
1491
1492
1493# Command set
1494cmdset = [
1495 'switch',
1496 'trend',
1497 'home',
1498 'view',
1499 'mentions',
1500 't',
1501 'rt',
1502 'quote',
1503 'allrt',
1504 'fav',
1505 'rep',
1506 'del',
1507 'ufav',
1508 's',
1509 'mes',
1510 'show',
1511 'open',
1512 'ls',
1513 'inbox',
1514 'sent',
1515 'trash',
1516 'whois',
1517 'fl',
1518 'ufl',
1519 'mute',
1520 'unmute',
1521 'muting',
1522 'block',
1523 'unblock',
1524 'report',
1525 'list',
1526 'cal',
1527 'config',
1528 'theme',
1529 'h',
1530 'p',
1531 'r',
1532 'c',
1533 'q'
1534]
1535
1536# Handle function set
1537funcset = [
1538 switch,
1539 trend,
1540 home,
1541 view,
1542 mentions,
1543 tweet,
1544 retweet,
1545 quote,
1546 allretweet,
1547 favorite,
1548 reply,
1549 delete,
1550 unfavorite,
1551 search,
1552 message,
1553 show,
1554 urlopen,
1555 ls,
1556 inbox,
1557 sent,
1558 trash,
1559 whois,
1560 follow,
1561 unfollow,
1562 mute,
1563 unmute,
1564 muting,
1565 block,
1566 unblock,
1567 report,
1568 twitterlist,
1569 cal,
1570 config,
1571 theme,
1572 help,
1573 pause,
1574 replay,
1575 clear,
1576 quit
1577]
1578
1579
1580def process(cmd):
1581 """
1582 Process switch
1583 """
1584 return dict(zip(cmdset, funcset)).get(cmd, reset)
1585
1586
1587def listen():
1588 """
1589 Listen to user's input
1590 """
1591 d = dict(zip(
1592 cmdset,
1593 [
1594 ['public', 'mine'], # switch
1595 [], # trend
1596 [], # home
1597 ['@'], # view
1598 [], # mentions
1599 [], # tweet
1600 [], # retweet
1601 [], # quote
1602 [], # allretweet
1603 [], # favorite
1604 [], # reply
1605 [], # delete
1606 [], # unfavorite
1607 ['#'], # search
1608 ['@'], # message
1609 ['image'], # show image
1610 [''], # open url
1611 ['fl', 'fr'], # list
1612 [], # inbox
1613 [], # sent
1614 [], # trash
1615 ['@'], # whois
1616 ['@'], # follow
1617 ['@'], # unfollow
1618 ['@'], # mute
1619 ['@'], # unmute
1620 ['@'], # muting
1621 ['@'], # block
1622 ['@'], # unblock
1623 ['@'], # report
1624 [
1625 'home',
1626 'all_mem',
1627 'all_sub',
1628 'add',
1629 'rm',
1630 'sub',
1631 'unsub',
1632 'own',
1633 'new',
1634 'update',
1635 'del'
1636 ], # list
1637 [], # cal
1638 [key for key in dict(get_all_config())], # config
1639 g['themes'], # theme
1640 [
1641 'discover',
1642 'tweets',
1643 'messages',
1644 'friends_and_followers',
1645 'list',
1646 'stream'
1647 ], # help
1648 [], # pause
1649 [], # reconnect
1650 [], # clear
1651 [], # quit
1652 ]
1653 ))
1654 init_interactive_shell(d)
1655 read_history()
1656 reset()
1657 while True:
1658 # raw_input
1659 if g['prefix']:
1660 line = raw_input(g['decorated_name'](c['PREFIX']))
1661 else:
1662 line = raw_input()
1663 # Save cmd to compare with readline buffer
1664 g['cmd'] = line.strip()
1665 # Get short cmd to pass to handle function
1666 try:
1667 cmd = line.split()[0]
1668 except:
1669 cmd = ''
1670 try:
1671 # Lock the semaphore
1672 c['lock'] = True
1673 # Save cmd to global variable and call process
1674 g['stuff'] = ' '.join(line.split()[1:])
1675 # Process the command
1676 process(cmd)()
1677 # Not re-display
1678 if cmd in ['switch', 't', 'rt', 'rep']:
1679 g['prefix'] = False
1680 else:
1681 g['prefix'] = True
1682 # Release the semaphore lock
1683 c['lock'] = False
1684 except Exception:
1685 printNicely(red('OMG something is wrong with Twitter right now.'))
1686
1687
1688def stream(domain, args, name='Rainbow Stream'):
1689 """
1690 Track the stream
1691 """
1692 # The Logo
1693 art_dict = {
1694 c['USER_DOMAIN']: name,
1695 c['PUBLIC_DOMAIN']: args.track_keywords,
1696 c['SITE_DOMAIN']: name,
1697 }
1698 if c['ASCII_ART']:
1699 ascii_art(art_dict[domain])
1700 # These arguments are optional:
1701 stream_args = dict(
1702 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
1703 block=True,
1704 heartbeat_timeout=c['HEARTBEAT_TIMEOUT'] * 60)
1705 # Track keyword
1706 query_args = dict()
1707 if args.track_keywords:
1708 query_args['track'] = args.track_keywords
1709 # Get stream
1710 stream = TwitterStream(
1711 auth=authen(),
1712 domain=domain,
1713 **stream_args)
1714 try:
1715 if domain == c['USER_DOMAIN']:
1716 tweet_iter = stream.user(**query_args)
1717 elif domain == c['SITE_DOMAIN']:
1718 tweet_iter = stream.site(**query_args)
1719 else:
1720 if args.track_keywords:
1721 tweet_iter = stream.statuses.filter(**query_args)
1722 else:
1723 tweet_iter = stream.statuses.sample()
1724 # Block new stream until other one exits
1725 StreamLock.acquire()
1726 g['stream_stop'] = False
1727 for tweet in tweet_iter:
1728 if tweet is None:
1729 printNicely("-- None --")
1730 elif tweet is Timeout:
1731 if(g['stream_stop']):
1732 StreamLock.release()
1733 break
1734 elif tweet is HeartbeatTimeout:
1735 printNicely("-- Heartbeat Timeout --")
1736 guide = light_magenta("You can use ") + \
1737 light_green("switch") + \
1738 light_magenta(" command to return to your stream.\n")
1739 guide += light_magenta("Type ") + \
1740 light_green("h stream") + \
1741 light_magenta(" for more details.")
1742 printNicely(guide)
1743 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1744 sys.stdout.flush()
1745 elif tweet is Hangup:
1746 printNicely("-- Hangup --")
1747 elif tweet.get('text'):
1748 draw(
1749 t=tweet,
1750 keyword=args.track_keywords,
1751 check_semaphore=True,
1752 fil=args.filter,
1753 ig=args.ignore,
1754 )
1755 # Current readline buffer
1756 current_buffer = readline.get_line_buffer().strip()
1757 # There is an unexpected behaviour in MacOSX readline + Python 2:
1758 # after completely delete a word after typing it,
1759 # somehow readline buffer still contains
1760 # the 1st character of that word
1761 if current_buffer and g['cmd'] != current_buffer:
1762 sys.stdout.write(
1763 g['decorated_name'](c['PREFIX']) + str2u(current_buffer))
1764 sys.stdout.flush()
1765 elif not c['HIDE_PROMPT']:
1766 sys.stdout.write(g['decorated_name'](c['PREFIX']))
1767 sys.stdout.flush()
1768 elif tweet.get('direct_message'):
1769 print_message(tweet['direct_message'], check_semaphore=True)
1770 except TwitterHTTPError:
1771 printNicely('')
1772 printNicely(
1773 magenta("We have maximum connection problem with twitter'stream API right now :("))
1774
1775
1776def fly():
1777 """
1778 Main function
1779 """
1780 # Initial
1781 args = parse_arguments()
1782 try:
1783 init(args)
1784 except TwitterHTTPError:
1785 printNicely('')
1786 printNicely(
1787 magenta("We have connection problem with twitter'stream API right now :("))
1788 printNicely(magenta("Let's try again later."))
1789 save_history()
1790 sys.exit()
1791 # Spawn stream thread
1792 th = threading.Thread(
1793 target=stream,
1794 args=(
1795 c['USER_DOMAIN'],
1796 args,
1797 g['original_name']))
1798 th.daemon = True
1799 th.start()
1800 # Start listen process
1801 time.sleep(0.5)
1802 g['reset'] = True
1803 g['prefix'] = True
1804 listen()