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