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