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