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