fix small bug
[rainbowstream.git] / rainbowstream / rainbow.py
... / ...
CommitLineData
1"""
2Colorful user's timeline stream
3"""
4import os
5import os.path
6import sys
7import signal
8import argparse
9import time
10import threading
11import requests
12import webbrowser
13
14from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup
15from twitter.api import *
16from twitter.oauth import OAuth, read_token_file
17from twitter.oauth_dance import oauth_dance
18from twitter.util import printNicely
19
20from .draw import *
21from .colors import *
22from .config import *
23from .consumer import *
24from .interactive import *
25from .c_image import *
26from .py3patch import *
27
28# Global values
29g = {}
30
31# Lock for streams
32StreamLock = threading.Lock()
33
34# Commands
35cmdset = [
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
78def 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
117def 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
140def 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
170def 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
222def 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
258def 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
271def 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
289def 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
302def tweet():
303 """
304 Tweet
305 """
306 t = Twitter(auth=authen())
307 t.statuses.update(status=g['stuff'])
308
309
310def 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
324def 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
351def 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
378def 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
395def 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
412def 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
427def 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
444def 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
461def 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
481def 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
502def 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'][int(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
523def 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
566def 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
599def 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
632def 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
646def 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
664def 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
677def 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
692def 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
712def 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
732def 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
759def 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
775def 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
791def 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
805def 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
823def 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
834def 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
849def 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
873def 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
897def 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
916def 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
935def 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
951def 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
967def 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
985def 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
1002def 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
1029def 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
1043def 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
1074def 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
1085def 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
1152def 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:
1176 printNicely(red('No such theme exists.'))
1177
1178
1179def help_discover():
1180 """
1181 Discover the world
1182 """
1183 s = ' ' * 2
1184 # Discover the world
1185 usage = '\n'
1186 usage += s + grey(u'\u266A' + ' Discover the world \n')
1187 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1188 'You can try ' + light_green('trend US') + ' or ' + \
1189 light_green('trend JP Tokyo') + '.\n'
1190 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1191 light_green('home 7') + ' will show 7 tweets.\n'
1192 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1193 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1194 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
1195 magenta('@mdo') + '.\n'
1196 usage += s * 2 + light_green('view @mdo') + \
1197 ' will show ' + magenta('@mdo') + '\'s home.\n'
1198 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1199 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1200 'Search can be performed with or without hashtag.\n'
1201 printNicely(usage)
1202
1203
1204def help_tweets():
1205 """
1206 Tweets
1207 """
1208 s = ' ' * 2
1209 # Tweet
1210 usage = '\n'
1211 usage += s + grey(u'\u266A' + ' Tweets \n')
1212 usage += s * 2 + light_green('t oops ') + \
1213 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1214 usage += s * 2 + \
1215 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1216 light_yellow('[id=12]') + '.\n'
1217 usage += s * 2 + \
1218 light_green('quote 12 ') + ' will quote the tweet with ' + \
1219 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1220 'the quote will be canceled.\n'
1221 usage += s * 2 + \
1222 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1223 light_yellow('[id=12]') + '.\n'
1224 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1225 light_yellow('oops') + '" to tweet with ' + \
1226 light_yellow('[id=12]') + '.\n'
1227 usage += s * 2 + \
1228 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1229 light_yellow('[id=12]') + '.\n'
1230 usage += s * 2 + \
1231 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1232 light_yellow('[id=12]') + '.\n'
1233 usage += s * 2 + \
1234 light_green('del 12 ') + ' will delete tweet with ' + \
1235 light_yellow('[id=12]') + '.\n'
1236 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1237 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1238 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1239 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1240 printNicely(usage)
1241
1242
1243def help_messages():
1244 """
1245 Messages
1246 """
1247 s = ' ' * 2
1248 # Direct message
1249 usage = '\n'
1250 usage += s + grey(u'\u266A' + ' Direct messages \n')
1251 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1252 light_green('inbox 7') + ' will show newest 7 messages.\n'
1253 usage += s * 2 + light_green('sent') + ' will show sent messages. ' + \
1254 light_green('sent 7') + ' will show newest 7 messages.\n'
1255 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1256 magenta('@dtvd88') + '.\n'
1257 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1258 light_yellow('[message_id=5]') + '.\n'
1259 printNicely(usage)
1260
1261
1262def help_friends_and_followers():
1263 """
1264 Friends and Followers
1265 """
1266 s = ' ' * 2
1267 # Follower and following
1268 usage = '\n'
1269 usage += s + grey(u'\u266A' + ' Friends and followers \n')
1270 usage += s * 2 + \
1271 light_green('ls fl') + \
1272 ' will list all followers (people who are following you).\n'
1273 usage += s * 2 + \
1274 light_green('ls fr') + \
1275 ' will list all friends (people who you are following).\n'
1276 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
1277 magenta('@dtvd88') + '.\n'
1278 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1279 magenta('@dtvd88') + '.\n'
1280 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
1281 magenta('@dtvd88') + '.\n'
1282 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1283 magenta('@dtvd88') + '.\n'
1284 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1285 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
1286 magenta('@dtvd88') + '.\n'
1287 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1288 magenta('@dtvd88') + '.\n'
1289 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
1290 magenta('@dtvd88') + ' as a spam account.\n'
1291 printNicely(usage)
1292
1293
1294def help_list():
1295 """
1296 Lists
1297 """
1298 s = ' ' * 2
1299 # Twitter list
1300 usage = '\n'
1301 usage += s + grey(u'\u266A' + ' Twitter list\n')
1302 usage += s * 2 + light_green('list') + \
1303 ' will show all lists you are belong to.\n'
1304 usage += s * 2 + light_green('list home') + \
1305 ' will show timeline of list. You will be asked for list\'s name.\n'
1306 usage += s * 2 + light_green('list all_mem') + \
1307 ' will show list\'s all members.\n'
1308 usage += s * 2 + light_green('list all_sub') + \
1309 ' will show list\'s all subscribers.\n'
1310 usage += s * 2 + light_green('list add') + \
1311 ' will add specific person to a list owned by you.' + \
1312 ' You will be asked for list\'s name and person\'s name.\n'
1313 usage += s * 2 + light_green('list rm') + \
1314 ' will remove specific person from 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 sub') + \
1317 ' will subscribe you to a specific list.\n'
1318 usage += s * 2 + light_green('list unsub') + \
1319 ' will unsubscribe you from a specific list.\n'
1320 usage += s * 2 + light_green('list own') + \
1321 ' will show all list owned by you.\n'
1322 usage += s * 2 + light_green('list new') + \
1323 ' will create a new list.\n'
1324 usage += s * 2 + light_green('list update') + \
1325 ' will update a list owned by you.\n'
1326 usage += s * 2 + light_green('list del') + \
1327 ' will delete a list owned by you.\n'
1328 printNicely(usage)
1329
1330
1331def help_stream():
1332 """
1333 Stream switch
1334 """
1335 s = ' ' * 2
1336 # Switch
1337 usage = '\n'
1338 usage += s + grey(u'\u266A' + ' Switching streams \n')
1339 usage += s * 2 + light_green('switch public #AKB') + \
1340 ' will switch to public stream and follow "' + \
1341 light_yellow('AKB') + '" keyword.\n'
1342 usage += s * 2 + light_green('switch mine') + \
1343 ' will switch to your personal stream.\n'
1344 usage += s * 2 + light_green('switch mine -f ') + \
1345 ' will prompt to enter the filter.\n'
1346 usage += s * 3 + light_yellow('Only nicks') + \
1347 ' filter will decide nicks will be INCLUDE ONLY.\n'
1348 usage += s * 3 + light_yellow('Ignore nicks') + \
1349 ' filter will decide nicks will be EXCLUDE.\n'
1350 usage += s * 2 + light_green('switch mine -d') + \
1351 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
1352 printNicely(usage)
1353
1354
1355def help():
1356 """
1357 Help
1358 """
1359 s = ' ' * 2
1360 h, w = os.popen('stty size', 'r').read().split()
1361 # Start
1362 usage = '\n'
1363 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1364 usage += s + '-' * (int(w) - 4) + '\n'
1365 usage += s + 'You are ' + \
1366 light_yellow('already') + ' on your personal stream.\n'
1367 usage += s + 'Any update from Twitter will show up ' + \
1368 light_yellow('immediately') + '.\n'
1369 usage += s + 'In addtion, following commands are available right now:\n'
1370 # Twitter help section
1371 usage += '\n'
1372 usage += s + grey(u'\u266A' + ' Twitter help\n')
1373 usage += s * 2 + light_green('h discover') + \
1374 ' will show help for discover commands.\n'
1375 usage += s * 2 + light_green('h tweets') + \
1376 ' will show help for tweets commands.\n'
1377 usage += s * 2 + light_green('h messages') + \
1378 ' will show help for messages commands.\n'
1379 usage += s * 2 + light_green('h friends_and_followers') + \
1380 ' will show help for friends and followers commands.\n'
1381 usage += s * 2 + light_green('h list') + \
1382 ' will show help for list commands.\n'
1383 usage += s * 2 + light_green('h stream') + \
1384 ' will show help for stream commands.\n'
1385 # Smart shell
1386 usage += '\n'
1387 usage += s + grey(u'\u266A' + ' Smart shell\n')
1388 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1389 'will be evaluate by Python interpreter.\n'
1390 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1391 ' for current month.\n'
1392 # Config
1393 usage += '\n'
1394 usage += s + grey(u'\u266A' + ' Config \n')
1395 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
1396 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1397 ' theme immediately.\n'
1398 usage += s * 2 + light_green('config') + ' will list all config.\n'
1399 usage += s * 3 + \
1400 light_green('config ASCII_ART') + ' will output current value of ' +\
1401 light_yellow('ASCII_ART') + ' config key.\n'
1402 usage += s * 3 + \
1403 light_green('config TREND_MAX default') + ' will output default value of ' + \
1404 light_yellow('TREND_MAX') + ' config key.\n'
1405 usage += s * 3 + \
1406 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1407 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1408 usage += s * 3 + \
1409 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1410 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1411 light_yellow('True') + '.\n'
1412 # Screening
1413 usage += '\n'
1414 usage += s + grey(u'\u266A' + ' Screening \n')
1415 usage += s * 2 + light_green('h') + ' will show this help again.\n'
1416 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1417 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
1418 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1419 usage += s * 2 + light_green('q') + ' will quit.\n'
1420 # End
1421 usage += '\n'
1422 usage += s + '-' * (int(w) - 4) + '\n'
1423 usage += s + 'Have fun and hang tight! \n'
1424 # Show help
1425 d = {
1426 'discover': help_discover,
1427 'tweets': help_tweets,
1428 'messages': help_messages,
1429 'friends_and_followers': help_friends_and_followers,
1430 'list': help_list,
1431 'stream': help_stream,
1432 }
1433 if g['stuff']:
1434 d[g['stuff'].strip()]()
1435 else:
1436 printNicely(usage)
1437
1438
1439def pause():
1440 """
1441 Pause stream display
1442 """
1443 c['pause'] = True
1444 printNicely(green('Stream is paused'))
1445
1446
1447def replay():
1448 """
1449 Replay stream
1450 """
1451 c['pause'] = False
1452 printNicely(green('Stream is running back now'))
1453
1454
1455def clear():
1456 """
1457 Clear screen
1458 """
1459 os.system('clear')
1460
1461
1462def quit():
1463 """
1464 Exit all
1465 """
1466 try:
1467 save_history()
1468 printNicely(green('See you next time :)'))
1469 except:
1470 pass
1471 sys.exit()
1472
1473
1474def reset():
1475 """
1476 Reset prefix of line
1477 """
1478 if g['reset']:
1479 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1480 g['reset'] = False
1481 try:
1482 printNicely(str(eval(g['cmd'])))
1483 except Exception:
1484 pass
1485
1486
1487def process(cmd):
1488 """
1489 Process switch
1490 """
1491 return dict(zip(
1492 cmdset,
1493 [
1494 switch,
1495 trend,
1496 home,
1497 view,
1498 mentions,
1499 tweet,
1500 retweet,
1501 quote,
1502 allretweet,
1503 favorite,
1504 reply,
1505 delete,
1506 unfavorite,
1507 search,
1508 message,
1509 show,
1510 urlopen,
1511 ls,
1512 inbox,
1513 sent,
1514 trash,
1515 whois,
1516 follow,
1517 unfollow,
1518 mute,
1519 unmute,
1520 muting,
1521 block,
1522 unblock,
1523 report,
1524 list,
1525 cal,
1526 config,
1527 theme,
1528 help,
1529 pause,
1530 replay,
1531 clear,
1532 quit
1533 ]
1534 )).get(cmd, reset)
1535
1536
1537def listen():
1538 """
1539 Listen to user's input
1540 """
1541 d = dict(zip(
1542 cmdset,
1543 [
1544 ['public', 'mine'], # switch
1545 [], # trend
1546 [], # home
1547 ['@'], # view
1548 [], # mentions
1549 [], # tweet
1550 [], # retweet
1551 [], # quote
1552 [], # allretweet
1553 [], # favorite
1554 [], # reply
1555 [], # delete
1556 [], # unfavorite
1557 ['#'], # search
1558 ['@'], # message
1559 ['image'], # show image
1560 [''], # open url
1561 ['fl', 'fr'], # list
1562 [], # inbox
1563 [], # sent
1564 [], # trash
1565 ['@'], # whois
1566 ['@'], # follow
1567 ['@'], # unfollow
1568 ['@'], # mute
1569 ['@'], # unmute
1570 ['@'], # muting
1571 ['@'], # block
1572 ['@'], # unblock
1573 ['@'], # report
1574 [
1575 'home',
1576 'all_mem',
1577 'all_sub',
1578 'add',
1579 'rm',
1580 'sub',
1581 'unsub',
1582 'own',
1583 'new',
1584 'update',
1585 'del'
1586 ], # list
1587 [], # cal
1588 [key for key in dict(get_all_config())], # config
1589 g['themes'], # theme
1590 [
1591 'discover',
1592 'tweets',
1593 'messages',
1594 'friends_and_followers',
1595 'list',
1596 'stream'
1597 ], # help
1598 [], # pause
1599 [], # reconnect
1600 [], # clear
1601 [], # quit
1602 ]
1603 ))
1604 init_interactive_shell(d)
1605 read_history()
1606 reset()
1607 while True:
1608 # raw_input
1609 if g['prefix']:
1610 line = raw_input(g['decorated_name'](c['PREFIX']))
1611 else:
1612 line = raw_input()
1613 try:
1614 cmd = line.split()[0]
1615 except:
1616 cmd = ''
1617 g['cmd'] = cmd
1618 try:
1619 # Lock the semaphore
1620 c['lock'] = True
1621 # Save cmd to global variable and call process
1622 g['stuff'] = ' '.join(line.split()[1:])
1623 # Process the command
1624 process(cmd)()
1625 # Not re-display
1626 if cmd in ['switch', 't', 'rt', 'rep']:
1627 g['prefix'] = False
1628 else:
1629 g['prefix'] = True
1630 # Release the semaphore lock
1631 c['lock'] = False
1632 except Exception:
1633 printNicely(red('OMG something is wrong with Twitter right now.'))
1634
1635
1636def stream(domain, args, name='Rainbow Stream'):
1637 """
1638 Track the stream
1639 """
1640 # The Logo
1641 art_dict = {
1642 c['USER_DOMAIN']: name,
1643 c['PUBLIC_DOMAIN']: args.track_keywords,
1644 c['SITE_DOMAIN']: name,
1645 }
1646 if c['ASCII_ART']:
1647 ascii_art(art_dict[domain])
1648 # These arguments are optional:
1649 stream_args = dict(
1650 timeout=args.timeout,
1651 block=False,
1652 heartbeat_timeout=args.heartbeat_timeout)
1653 # Track keyword
1654 query_args = dict()
1655 if args.track_keywords:
1656 query_args['track'] = args.track_keywords
1657 # Get stream
1658 stream = TwitterStream(
1659 auth=authen(),
1660 domain=domain,
1661 **stream_args)
1662 try:
1663 if domain == c['USER_DOMAIN']:
1664 tweet_iter = stream.user(**query_args)
1665 elif domain == c['SITE_DOMAIN']:
1666 tweet_iter = stream.site(**query_args)
1667 else:
1668 if args.track_keywords:
1669 tweet_iter = stream.statuses.filter(**query_args)
1670 else:
1671 tweet_iter = stream.statuses.sample()
1672 # Block new stream until other one exits
1673 StreamLock.acquire()
1674 g['stream_stop'] = False
1675 for tweet in tweet_iter:
1676 if(g['stream_stop']):
1677 StreamLock.release()
1678 break
1679 if tweet is None:
1680 pass
1681 elif tweet is Timeout:
1682 printNicely("-- Timeout --")
1683 elif tweet is HeartbeatTimeout:
1684 printNicely("-- Heartbeat Timeout --")
1685 elif tweet is Hangup:
1686 printNicely("-- Hangup --")
1687 elif tweet.get('text'):
1688 draw(
1689 t=tweet,
1690 keyword=args.track_keywords,
1691 check_semaphore=True,
1692 fil=args.filter,
1693 ig=args.ignore,
1694 )
1695 elif tweet.get('direct_message'):
1696 print_message(tweet['direct_message'], check_semaphore=True)
1697 except TwitterHTTPError:
1698 printNicely('')
1699 printNicely(
1700 magenta("We have maximum connection problem with twitter'stream API right now :("))
1701
1702
1703def fly():
1704 """
1705 Main function
1706 """
1707 # Initial
1708 args = parse_arguments()
1709 try:
1710 init(args)
1711 except TwitterHTTPError:
1712 printNicely('')
1713 printNicely(
1714 magenta("We have maximum connection problem with twitter'stream API right now :("))
1715 printNicely(magenta("Let's try again later."))
1716 save_history()
1717 sys.exit()
1718 # Spawn stream thread
1719 th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
1720 th.daemon = True
1721 th.start()
1722 # Start listen process
1723 time.sleep(0.5)
1724 g['reset'] = True
1725 g['prefix'] = True
1726 listen()