minor fix
[rainbowstream.git] / rainbowstream / rainbow.py
1 import os
2 import os.path
3 import sys
4 import signal
5 import argparse
6 import time
7 import threading
8 import requests
9 import webbrowser
10 import traceback
11 import pkg_resources
12 import socks
13 import socket
14
15 from io import BytesIO
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 .c_image import *
28 from .py3patch import *
29 from .emoji import *
30 from .util import *
31
32 # Global values
33 g = {}
34
35 # Lock for streams
36 StreamLock = threading.Lock()
37
38
39 def parse_arguments():
40 """
41 Parse the arguments
42 """
43 parser = argparse.ArgumentParser(description=__doc__ or "")
44 parser.add_argument(
45 '-s',
46 '--stream',
47 default="mine",
48 help='Default stream after program start. (Default: mine)')
49 parser.add_argument(
50 '-to',
51 '--timeout',
52 help='Timeout for the stream (seconds).')
53 parser.add_argument(
54 '-tt',
55 '--track-keywords',
56 help='Search the stream for specific text.')
57 parser.add_argument(
58 '-fil',
59 '--filter',
60 help='Filter specific screen_name.')
61 parser.add_argument(
62 '-ig',
63 '--ignore',
64 help='Ignore specific screen_name.')
65 parser.add_argument(
66 '-iot',
67 '--image-on-term',
68 action='store_true',
69 help='Display all image on terminal.')
70 parser.add_argument(
71 '-ph',
72 '--proxy-host',
73 help='Use HTTP/SOCKS proxy for network connections.')
74 parser.add_argument(
75 '-pp',
76 '--proxy-port',
77 default=8080,
78 help='HTTP/SOCKS proxy port (Default: 8080).')
79 parser.add_argument(
80 '-pt',
81 '--proxy-type',
82 default='SOCKS5',
83 help='Proxy type (HTTP, SOCKS4, SOCKS5; Default: SOCKS5).')
84 return parser.parse_args()
85
86
87 def proxy_connect(args):
88 """
89 Connect to specified proxy
90 """
91 if args.proxy_host:
92 # Setup proxy by monkeypatching the standard lib
93 if args.proxy_type.lower() == "socks5" or not args.proxy_type:
94 socks.set_default_proxy(
95 socks.SOCKS5, args.proxy_host,
96 int(args.proxy_port))
97 elif args.proxy_type.lower() == "http":
98 socks.set_default_proxy(
99 socks.HTTP, args.proxy_host,
100 int(args.proxy_port))
101 elif args.proxy_type.lower() == "socks4":
102 socks.set_default_proxy(
103 socks.SOCKS4, args.proxy_host,
104 int(args.proxy_port))
105 else:
106 printNicely(
107 magenta('Sorry, wrong proxy type specified! Aborting...'))
108 sys.exit()
109 socket.socket = socks.socksocket
110
111
112 def authen():
113 """
114 Authenticate with Twitter OAuth
115 """
116 # When using rainbow stream you must authorize.
117 twitter_credential = os.environ.get(
118 'HOME',
119 os.environ.get(
120 'USERPROFILE',
121 '')) + os.sep + '.rainbow_oauth'
122 if not os.path.exists(twitter_credential):
123 oauth_dance('Rainbow Stream',
124 CONSUMER_KEY,
125 CONSUMER_SECRET,
126 twitter_credential)
127 oauth_token, oauth_token_secret = read_token_file(twitter_credential)
128 return OAuth(
129 oauth_token,
130 oauth_token_secret,
131 CONSUMER_KEY,
132 CONSUMER_SECRET)
133
134
135 def build_mute_dict(dict_data=False):
136 """
137 Build muting list
138 """
139 t = Twitter(auth=authen())
140 # Init cursor
141 next_cursor = -1
142 screen_name_list = []
143 name_list = []
144 # Cursor loop
145 while next_cursor != 0:
146 list = t.mutes.users.list(
147 screen_name=g['original_name'],
148 cursor=next_cursor,
149 skip_status=True,
150 include_entities=False,
151 )
152 screen_name_list += ['@' + u['screen_name'] for u in list['users']]
153 name_list += [u['name'] for u in list['users']]
154 next_cursor = list['next_cursor']
155 # Return dict or list
156 if dict_data:
157 return dict(zip(screen_name_list, name_list))
158 else:
159 return screen_name_list
160
161
162 def debug_option():
163 """
164 Save traceback when run in debug mode
165 """
166 if g['debug']:
167 g['traceback'].append(traceback.format_exc())
168
169
170 def upgrade_center():
171 """
172 Check latest and notify to upgrade
173 """
174 try:
175 current = pkg_resources.get_distribution('rainbowstream').version
176 url = 'https://raw.githubusercontent.com/DTVD/rainbowstream/master/setup.py'
177 readme = requests.get(url).text
178 latest = readme.split('version = \'')[1].split('\'')[0]
179 if current != latest:
180 notice = light_magenta('RainbowStream latest version is ')
181 notice += light_green(latest)
182 notice += light_magenta(' while your current version is ')
183 notice += light_yellow(current) + '\n'
184 notice += light_magenta('You should upgrade with ')
185 notice += light_green('pip install -U rainbowstream')
186 printNicely(notice)
187 else:
188 notice = light_yellow('You are running latest version (')
189 notice += light_green(current)
190 notice += light_yellow(')')
191 printNicely(notice)
192 except:
193 pass
194
195
196 def init(args):
197 """
198 Init function
199 """
200 # Handle Ctrl C
201 ctrl_c_handler = lambda signum, frame: quit()
202 signal.signal(signal.SIGINT, ctrl_c_handler)
203 # Upgrade notify
204 upgrade_center()
205 # Get name
206 t = Twitter(auth=authen())
207 credential = t.account.verify_credentials()
208 screen_name = '@' + credential['screen_name']
209 name = credential['name']
210 c['original_name'] = g['original_name'] = screen_name[1:]
211 g['listname'] = g['keyword'] = ''
212 g['PREFIX'] = u2str(emojize(format_prefix()))
213 g['full_name'] = name
214 g['decorated_name'] = lambda x: color_func(
215 c['DECORATED_NAME'])('[' + x + ']: ', rl=True)
216 # Theme init
217 files = os.listdir(os.path.dirname(__file__) + '/colorset')
218 themes = [f.split('.')[0] for f in files if f.split('.')[-1] == 'json']
219 g['themes'] = themes
220 g['pause'] = False
221 g['message_threads'] = {}
222 # Startup cmd
223 g['cmd'] = ''
224 # Debug option default = True
225 g['debug'] = True
226 g['traceback'] = []
227 # Events
228 c['events'] = []
229 # Semaphore init
230 c['lock'] = False
231 # Init tweet dict and message dict
232 c['tweet_dict'] = []
233 c['message_dict'] = []
234 # Image on term
235 c['IMAGE_ON_TERM'] = args.image_on_term
236 set_config('IMAGE_ON_TERM', str(c['IMAGE_ON_TERM']))
237 # Check type of ONLY_LIST and IGNORE_LIST
238 if not isinstance(c['ONLY_LIST'], list):
239 printNicely(red('ONLY_LIST is not a valid list value.'))
240 c['ONLY_LIST'] = []
241 if not isinstance(c['IGNORE_LIST'], list):
242 printNicely(red('IGNORE_LIST is not a valid list value.'))
243 c['IGNORE_LIST'] = []
244 # Mute dict
245 c['IGNORE_LIST'] += build_mute_dict()
246
247
248 def trend():
249 """
250 Trend
251 """
252 t = Twitter(auth=authen())
253 # Get country and town
254 try:
255 country = g['stuff'].split()[0]
256 except:
257 country = ''
258 try:
259 town = g['stuff'].split()[1]
260 except:
261 town = ''
262 avail = t.trends.available()
263 # World wide
264 if not country:
265 trends = t.trends.place(_id=1)[0]['trends']
266 print_trends(trends)
267 else:
268 for location in avail:
269 # Search for country and Town
270 if town:
271 if location['countryCode'] == country \
272 and location['placeType']['name'] == 'Town' \
273 and location['name'] == town:
274 trends = t.trends.place(_id=location['woeid'])[0]['trends']
275 print_trends(trends)
276 # Search for country only
277 else:
278 if location['countryCode'] == country \
279 and location['placeType']['name'] == 'Country':
280 trends = t.trends.place(_id=location['woeid'])[0]['trends']
281 print_trends(trends)
282
283
284 def home():
285 """
286 Home
287 """
288 t = Twitter(auth=authen())
289 num = c['HOME_TWEET_NUM']
290 if g['stuff'].isdigit():
291 num = int(g['stuff'])
292 for tweet in reversed(t.statuses.home_timeline(count=num)):
293 draw(t=tweet)
294 printNicely('')
295
296
297 def notification():
298 """
299 Show notifications
300 """
301 if c['events']:
302 for e in c['events']:
303 print_event(e)
304 printNicely('')
305 else:
306 printNicely(magenta('Nothing at this time.'))
307
308
309 def mentions():
310 """
311 Mentions timeline
312 """
313 t = Twitter(auth=authen())
314 num = c['HOME_TWEET_NUM']
315 if g['stuff'].isdigit():
316 num = int(g['stuff'])
317 for tweet in reversed(t.statuses.mentions_timeline(count=num)):
318 draw(t=tweet)
319 printNicely('')
320
321
322 def whois():
323 """
324 Show profile of a specific user
325 """
326 t = Twitter(auth=authen())
327 try:
328 screen_name = g['stuff'].split()[0]
329 except:
330 printNicely(red('Sorry I can\'t understand.'))
331 return
332 if screen_name.startswith('@'):
333 try:
334 user = t.users.show(
335 screen_name=screen_name[1:],
336 include_entities=False)
337 show_profile(user)
338 except:
339 debug_option()
340 printNicely(red('No user.'))
341 else:
342 printNicely(red('A name should begin with a \'@\''))
343
344
345 def view():
346 """
347 Friend view
348 """
349 t = Twitter(auth=authen())
350 try:
351 user = g['stuff'].split()[0]
352 except:
353 printNicely(red('Sorry I can\'t understand.'))
354 return
355 if user[0] == '@':
356 try:
357 num = int(g['stuff'].split()[1])
358 except:
359 num = c['HOME_TWEET_NUM']
360 for tweet in reversed(
361 t.statuses.user_timeline(count=num, screen_name=user[1:])):
362 draw(t=tweet)
363 printNicely('')
364 else:
365 printNicely(red('A name should begin with a \'@\''))
366
367
368 def search():
369 """
370 Search
371 """
372 t = Twitter(auth=authen())
373 # Setup query
374 query = g['stuff'].strip()
375 if not query:
376 printNicely(red('Sorry I can\'t understand.'))
377 return
378 type = c['SEARCH_TYPE']
379 if type not in ['mixed', 'recent', 'popular']:
380 type = 'mixed'
381 max_record = c['SEARCH_MAX_RECORD']
382 count = min(max_record, 100)
383 # Perform search
384 rel = t.search.tweets(
385 q=query,
386 type=type,
387 count=count
388 )['statuses']
389 # Return results
390 if rel:
391 printNicely('Newest tweets:')
392 for i in reversed(xrange(count)):
393 draw(t=rel[i], keyword=query)
394 printNicely('')
395 else:
396 printNicely(magenta('I\'m afraid there is no result'))
397
398
399 def tweet():
400 """
401 Tweet
402 """
403 t = Twitter(auth=authen())
404 t.statuses.update(status=g['stuff'])
405
406
407 def retweet():
408 """
409 ReTweet
410 """
411 t = Twitter(auth=authen())
412 try:
413 id = int(g['stuff'].split()[0])
414 except:
415 printNicely(red('Sorry I can\'t understand.'))
416 return
417 tid = c['tweet_dict'][id]
418 t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
419
420
421 def quote():
422 """
423 Quote a tweet
424 """
425 # Get tweet
426 t = Twitter(auth=authen())
427 try:
428 id = int(g['stuff'].split()[0])
429 except:
430 printNicely(red('Sorry I can\'t understand.'))
431 return
432 tid = c['tweet_dict'][id]
433 tweet = t.statuses.show(id=tid)
434 # Get formater
435 formater = format_quote(tweet)
436 if not formater:
437 return
438 # Get comment
439 prefix = light_magenta('Compose your ', rl=True) + \
440 light_green('#comment: ', rl=True)
441 comment = raw_input(prefix)
442 if comment:
443 quote = comment.join(formater.split('#comment'))
444 t.statuses.update(status=quote)
445 else:
446 printNicely(light_magenta('No text added.'))
447
448
449 def allretweet():
450 """
451 List all retweet
452 """
453 t = Twitter(auth=authen())
454 # Get rainbow id
455 try:
456 id = int(g['stuff'].split()[0])
457 except:
458 printNicely(red('Sorry I can\'t understand.'))
459 return
460 tid = c['tweet_dict'][id]
461 # Get display num if exist
462 try:
463 num = int(g['stuff'].split()[1])
464 except:
465 num = c['RETWEETS_SHOW_NUM']
466 # Get result and display
467 rt_ary = t.statuses.retweets(id=tid, count=num)
468 if not rt_ary:
469 printNicely(magenta('This tweet has no retweet.'))
470 return
471 for tweet in reversed(rt_ary):
472 draw(t=tweet)
473 printNicely('')
474
475
476 def conversation():
477 """
478 Conversation view
479 """
480 t = Twitter(auth=authen())
481 try:
482 id = int(g['stuff'].split()[0])
483 except:
484 printNicely(red('Sorry I can\'t understand.'))
485 return
486 tid = c['tweet_dict'][id]
487 tweet = t.statuses.show(id=tid)
488 limit = c['CONVERSATION_MAX']
489 thread_ref = []
490 thread_ref.append(tweet)
491 prev_tid = tweet['in_reply_to_status_id']
492 while prev_tid and limit:
493 limit -= 1
494 tweet = t.statuses.show(id=prev_tid)
495 prev_tid = tweet['in_reply_to_status_id']
496 thread_ref.append(tweet)
497
498 for tweet in reversed(thread_ref):
499 draw(t=tweet)
500 printNicely('')
501
502
503 def reply():
504 """
505 Reply
506 """
507 t = Twitter(auth=authen())
508 try:
509 id = int(g['stuff'].split()[0])
510 except:
511 printNicely(red('Sorry I can\'t understand.'))
512 return
513 tid = c['tweet_dict'][id]
514 user = t.statuses.show(id=tid)['user']['screen_name']
515 status = ' '.join(g['stuff'].split()[1:])
516 status = '@' + user + ' ' + str2u(status)
517 t.statuses.update(status=status, in_reply_to_status_id=tid)
518
519
520 def reply_all():
521 """
522 Reply to all
523 """
524 t = Twitter(auth=authen())
525 try:
526 id = int(g['stuff'].split()[0])
527 except:
528 printNicely(red('Sorry I can\'t understand.'))
529 return
530 tid = c['tweet_dict'][id]
531 original_tweet = t.statuses.show(id=tid)
532 text = original_tweet['text']
533 owner = '@' + original_tweet['user']['screen_name']
534 nick_ary = ['@' + re.sub('[\W_]', '', w)
535 for w in text.split() if w.startswith('@')] + [owner]
536 status = ' '.join(g['stuff'].split()[1:])
537 status = ' '.join(nick_ary) + ' ' + str2u(status)
538 t.statuses.update(status=status, in_reply_to_status_id=tid)
539
540
541 def favorite():
542 """
543 Favorite
544 """
545 t = Twitter(auth=authen())
546 try:
547 id = int(g['stuff'].split()[0])
548 except:
549 printNicely(red('Sorry I can\'t understand.'))
550 return
551 tid = c['tweet_dict'][id]
552 t.favorites.create(_id=tid, include_entities=False)
553 printNicely(green('Favorited.'))
554 draw(t.statuses.show(id=tid))
555 printNicely('')
556
557
558 def unfavorite():
559 """
560 Unfavorite
561 """
562 t = Twitter(auth=authen())
563 try:
564 id = int(g['stuff'].split()[0])
565 except:
566 printNicely(red('Sorry I can\'t understand.'))
567 return
568 tid = c['tweet_dict'][id]
569 t.favorites.destroy(_id=tid)
570 printNicely(green('Okay it\'s unfavorited.'))
571 draw(t.statuses.show(id=tid))
572 printNicely('')
573
574
575 def share():
576 """
577 Copy url of a tweet to clipboard
578 """
579 t = Twitter(auth=authen())
580 try:
581 id = int(g['stuff'].split()[0])
582 tid = c['tweet_dict'][id]
583 except:
584 printNicely(red('Tweet id is not valid.'))
585 return
586 tweet = t.statuses.show(id=tid)
587 url = 'https://twitter.com/' + \
588 tweet['user']['screen_name'] + '/status/' + str(tid)
589 import platform
590 if platform.system().lower() == 'darwin':
591 os.system("echo '%s' | pbcopy" % url)
592 printNicely(green('Copied tweet\'s url to clipboard.'))
593 else:
594 printNicely('Direct link: ' + yellow(url))
595
596
597 def delete():
598 """
599 Delete
600 """
601 t = Twitter(auth=authen())
602 try:
603 id = int(g['stuff'].split()[0])
604 except:
605 printNicely(red('Sorry I can\'t understand.'))
606 return
607 tid = c['tweet_dict'][id]
608 t.statuses.destroy(id=tid)
609 printNicely(green('Okay it\'s gone.'))
610
611
612 def show():
613 """
614 Show image
615 """
616 t = Twitter(auth=authen())
617 try:
618 target = g['stuff'].split()[0]
619 if target != 'image':
620 return
621 id = int(g['stuff'].split()[1])
622 tid = c['tweet_dict'][id]
623 tweet = t.statuses.show(id=tid)
624 media = tweet['entities']['media']
625 for m in media:
626 res = requests.get(m['media_url'])
627 img = Image.open(BytesIO(res.content))
628 img.show()
629 except:
630 debug_option()
631 printNicely(red('Sorry I can\'t show this image.'))
632
633
634 def urlopen():
635 """
636 Open url
637 """
638 t = Twitter(auth=authen())
639 try:
640 if not g['stuff'].isdigit():
641 return
642 tid = c['tweet_dict'][int(g['stuff'])]
643 tweet = t.statuses.show(id=tid)
644 link_prefix = ('http://', 'https://')
645 link_ary = [u for u in tweet['text'].split()
646 if u.startswith(link_prefix)]
647 if not link_ary:
648 printNicely(light_magenta('No url here @.@!'))
649 return
650 for link in link_ary:
651 webbrowser.open(link)
652 except:
653 debug_option()
654 printNicely(red('Sorry I can\'t open url in this tweet.'))
655
656
657 def inbox():
658 """
659 Inbox threads
660 """
661 t = Twitter(auth=authen())
662 num = c['MESSAGES_DISPLAY']
663 if g['stuff'].isdigit():
664 num = g['stuff']
665 # Get inbox messages
666 cur_page = 1
667 inbox = []
668 while num > 20:
669 inbox = inbox + t.direct_messages(
670 count=20,
671 page=cur_page,
672 include_entities=False,
673 skip_status=False
674 )
675 num -= 20
676 cur_page += 1
677 inbox = inbox + t.direct_messages(
678 count=num,
679 page=cur_page,
680 include_entities=False,
681 skip_status=False
682 )
683 # Get sent messages
684 num = c['MESSAGES_DISPLAY']
685 if g['stuff'].isdigit():
686 num = g['stuff']
687 cur_page = 1
688 sent = []
689 while num > 20:
690 sent = sent + t.direct_messages.sent(
691 count=20,
692 page=cur_page,
693 include_entities=False,
694 skip_status=False
695 )
696 num -= 20
697 cur_page += 1
698 sent = sent + t.direct_messages.sent(
699 count=num,
700 page=cur_page,
701 include_entities=False,
702 skip_status=False
703 )
704
705 d = {}
706 uniq_inbox = list(set(
707 [(m['sender_screen_name'], m['sender']['name']) for m in inbox]
708 ))
709 uniq_sent = list(set(
710 [(m['recipient_screen_name'], m['recipient']['name']) for m in sent]
711 ))
712 for partner in uniq_inbox:
713 inbox_ary = [m for m in inbox if m['sender_screen_name'] == partner[0]]
714 sent_ary = [
715 m for m in sent if m['recipient_screen_name'] == partner[0]]
716 d[partner] = inbox_ary + sent_ary
717 for partner in uniq_sent:
718 if partner not in d:
719 d[partner] = [
720 m for m in sent if m['recipient_screen_name'] == partner[0]]
721 g['message_threads'] = print_threads(d)
722
723
724 def thread():
725 """
726 View a thread of message
727 """
728 try:
729 thread_id = int(g['stuff'])
730 print_thread(
731 g['message_threads'][thread_id],
732 g['original_name'],
733 g['full_name'])
734 except Exception:
735 debug_option()
736 printNicely(red('No such thread.'))
737
738
739 def message():
740 """
741 Send a direct message
742 """
743 t = Twitter(auth=authen())
744 try:
745 user = g['stuff'].split()[0]
746 if user[0].startswith('@'):
747 content = ' '.join(g['stuff'].split()[1:])
748 t.direct_messages.new(
749 screen_name=user[1:],
750 text=content
751 )
752 printNicely(green('Message sent.'))
753 else:
754 printNicely(red('A name should begin with a \'@\''))
755 except:
756 debug_option()
757 printNicely(red('Sorry I can\'t understand.'))
758
759
760 def trash():
761 """
762 Remove message
763 """
764 t = Twitter(auth=authen())
765 try:
766 id = int(g['stuff'].split()[0])
767 except:
768 printNicely(red('Sorry I can\'t understand.'))
769 mid = c['message_dict'][id]
770 t.direct_messages.destroy(id=mid)
771 printNicely(green('Message deleted.'))
772
773
774 def ls():
775 """
776 List friends for followers
777 """
778 t = Twitter(auth=authen())
779 # Get name
780 try:
781 name = g['stuff'].split()[1]
782 if name.startswith('@'):
783 name = name[1:]
784 else:
785 printNicely(red('A name should begin with a \'@\''))
786 raise Exception('Invalid name')
787 except:
788 name = g['original_name']
789 # Get list followers or friends
790 try:
791 target = g['stuff'].split()[0]
792 except:
793 printNicely(red('Omg some syntax is wrong.'))
794 return
795 # Init cursor
796 d = {'fl': 'followers', 'fr': 'friends'}
797 next_cursor = -1
798 rel = {}
799 # Cursor loop
800 while next_cursor != 0:
801 list = getattr(t, d[target]).list(
802 screen_name=name,
803 cursor=next_cursor,
804 skip_status=True,
805 include_entities=False,
806 )
807 for u in list['users']:
808 rel[u['name']] = '@' + u['screen_name']
809 next_cursor = list['next_cursor']
810 # Print out result
811 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
812 for name in rel:
813 user = ' ' + cycle_color(name)
814 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
815 printNicely(user)
816
817
818 def follow():
819 """
820 Follow a user
821 """
822 t = Twitter(auth=authen())
823 screen_name = g['stuff'].split()[0]
824 if screen_name.startswith('@'):
825 t.friendships.create(screen_name=screen_name[1:], follow=True)
826 printNicely(green('You are following ' + screen_name + ' now!'))
827 else:
828 printNicely(red('A name should begin with a \'@\''))
829
830
831 def unfollow():
832 """
833 Unfollow a user
834 """
835 t = Twitter(auth=authen())
836 screen_name = g['stuff'].split()[0]
837 if screen_name.startswith('@'):
838 t.friendships.destroy(
839 screen_name=screen_name[1:],
840 include_entities=False)
841 printNicely(green('Unfollow ' + screen_name + ' success!'))
842 else:
843 printNicely(red('A name should begin with a \'@\''))
844
845
846 def mute():
847 """
848 Mute a user
849 """
850 t = Twitter(auth=authen())
851 try:
852 screen_name = g['stuff'].split()[0]
853 except:
854 printNicely(red('A name should be specified. '))
855 return
856 if screen_name.startswith('@'):
857 try:
858 rel = t.mutes.users.create(screen_name=screen_name[1:])
859 if isinstance(rel, dict):
860 printNicely(green(screen_name + ' is muted.'))
861 c['IGNORE_LIST'] += [unc(screen_name)]
862 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
863 else:
864 printNicely(red(rel))
865 except:
866 debug_option()
867 printNicely(red('Something is wrong, can not mute now :('))
868 else:
869 printNicely(red('A name should begin with a \'@\''))
870
871
872 def unmute():
873 """
874 Unmute a user
875 """
876 t = Twitter(auth=authen())
877 try:
878 screen_name = g['stuff'].split()[0]
879 except:
880 printNicely(red('A name should be specified. '))
881 return
882 if screen_name.startswith('@'):
883 try:
884 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
885 if isinstance(rel, dict):
886 printNicely(green(screen_name + ' is unmuted.'))
887 c['IGNORE_LIST'].remove(screen_name)
888 else:
889 printNicely(red(rel))
890 except:
891 printNicely(red('Maybe you are not muting this person ?'))
892 else:
893 printNicely(red('A name should begin with a \'@\''))
894
895
896 def muting():
897 """
898 List muting user
899 """
900 # Get dict of muting users
901 md = build_mute_dict(dict_data=True)
902 printNicely('All: ' + str(len(md)) + ' people.')
903 for name in md:
904 user = ' ' + cycle_color(md[name])
905 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
906 printNicely(user)
907 # Update from Twitter
908 c['IGNORE_LIST'] = [n for n in md]
909
910
911 def block():
912 """
913 Block a user
914 """
915 t = Twitter(auth=authen())
916 screen_name = g['stuff'].split()[0]
917 if screen_name.startswith('@'):
918 t.blocks.create(
919 screen_name=screen_name[1:],
920 include_entities=False,
921 skip_status=True)
922 printNicely(green('You blocked ' + screen_name + '.'))
923 else:
924 printNicely(red('A name should begin with a \'@\''))
925
926
927 def unblock():
928 """
929 Unblock a user
930 """
931 t = Twitter(auth=authen())
932 screen_name = g['stuff'].split()[0]
933 if screen_name.startswith('@'):
934 t.blocks.destroy(
935 screen_name=screen_name[1:],
936 include_entities=False,
937 skip_status=True)
938 printNicely(green('Unblock ' + screen_name + ' success!'))
939 else:
940 printNicely(red('A name should begin with a \'@\''))
941
942
943 def report():
944 """
945 Report a user as a spam account
946 """
947 t = Twitter(auth=authen())
948 screen_name = g['stuff'].split()[0]
949 if screen_name.startswith('@'):
950 t.users.report_spam(
951 screen_name=screen_name[1:])
952 printNicely(green('You reported ' + screen_name + '.'))
953 else:
954 printNicely(red('Sorry I can\'t understand.'))
955
956
957 def get_slug():
958 """
959 Get slug
960 """
961 # Get list name
962 list_name = raw_input(
963 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl=True))
964 # Get list name and owner
965 try:
966 owner, slug = list_name.split('/')
967 if slug.startswith('@'):
968 slug = slug[1:]
969 return owner, slug
970 except:
971 printNicely(
972 light_magenta('List name should follow "@owner/list_name" format.'))
973 raise Exception('Wrong list name')
974
975
976 def check_slug(list_name):
977 """
978 Check slug
979 """
980 # Get list name and owner
981 try:
982 owner, slug = list_name.split('/')
983 if slug.startswith('@'):
984 slug = slug[1:]
985 return owner, slug
986 except:
987 printNicely(
988 light_magenta('List name should follow "@owner/list_name" format.'))
989 raise Exception('Wrong list name')
990
991
992 def show_lists(t):
993 """
994 List list
995 """
996 rel = t.lists.list(screen_name=g['original_name'])
997 if rel:
998 print_list(rel)
999 else:
1000 printNicely(light_magenta('You belong to no lists :)'))
1001
1002
1003 def list_home(t):
1004 """
1005 List home
1006 """
1007 owner, slug = get_slug()
1008 res = t.lists.statuses(
1009 slug=slug,
1010 owner_screen_name=owner,
1011 count=c['LIST_MAX'],
1012 include_entities=False)
1013 for tweet in reversed(res):
1014 draw(t=tweet)
1015 printNicely('')
1016
1017
1018 def list_members(t):
1019 """
1020 List members
1021 """
1022 owner, slug = get_slug()
1023 # Get members
1024 rel = {}
1025 next_cursor = -1
1026 while next_cursor != 0:
1027 m = t.lists.members(
1028 slug=slug,
1029 owner_screen_name=owner,
1030 cursor=next_cursor,
1031 include_entities=False)
1032 for u in m['users']:
1033 rel[u['name']] = '@' + u['screen_name']
1034 next_cursor = m['next_cursor']
1035 printNicely('All: ' + str(len(rel)) + ' members.')
1036 for name in rel:
1037 user = ' ' + cycle_color(name)
1038 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
1039 printNicely(user)
1040
1041
1042 def list_subscribers(t):
1043 """
1044 List subscribers
1045 """
1046 owner, slug = get_slug()
1047 # Get subscribers
1048 rel = {}
1049 next_cursor = -1
1050 while next_cursor != 0:
1051 m = t.lists.subscribers(
1052 slug=slug,
1053 owner_screen_name=owner,
1054 cursor=next_cursor,
1055 include_entities=False)
1056 for u in m['users']:
1057 rel[u['name']] = '@' + u['screen_name']
1058 next_cursor = m['next_cursor']
1059 printNicely('All: ' + str(len(rel)) + ' subscribers.')
1060 for name in rel:
1061 user = ' ' + cycle_color(name)
1062 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
1063 printNicely(user)
1064
1065
1066 def list_add(t):
1067 """
1068 Add specific user to a list
1069 """
1070 owner, slug = get_slug()
1071 # Add
1072 user_name = raw_input(
1073 light_magenta(
1074 'Give me name of the newbie: ',
1075 rl=True))
1076 if user_name.startswith('@'):
1077 user_name = user_name[1:]
1078 try:
1079 t.lists.members.create(
1080 slug=slug,
1081 owner_screen_name=owner,
1082 screen_name=user_name)
1083 printNicely(green('Added.'))
1084 except:
1085 debug_option()
1086 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1087
1088
1089 def list_remove(t):
1090 """
1091 Remove specific user from a list
1092 """
1093 owner, slug = get_slug()
1094 # Remove
1095 user_name = raw_input(
1096 light_magenta(
1097 'Give me name of the unlucky one: ',
1098 rl=True))
1099 if user_name.startswith('@'):
1100 user_name = user_name[1:]
1101 try:
1102 t.lists.members.destroy(
1103 slug=slug,
1104 owner_screen_name=owner,
1105 screen_name=user_name)
1106 printNicely(green('Gone.'))
1107 except:
1108 debug_option()
1109 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1110
1111
1112 def list_subscribe(t):
1113 """
1114 Subscribe to a list
1115 """
1116 owner, slug = get_slug()
1117 # Subscribe
1118 try:
1119 t.lists.subscribers.create(
1120 slug=slug,
1121 owner_screen_name=owner)
1122 printNicely(green('Done.'))
1123 except:
1124 debug_option()
1125 printNicely(
1126 light_magenta('I\'m sorry you can not subscribe to this list.'))
1127
1128
1129 def list_unsubscribe(t):
1130 """
1131 Unsubscribe a list
1132 """
1133 owner, slug = get_slug()
1134 # Subscribe
1135 try:
1136 t.lists.subscribers.destroy(
1137 slug=slug,
1138 owner_screen_name=owner)
1139 printNicely(green('Done.'))
1140 except:
1141 debug_option()
1142 printNicely(
1143 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1144
1145
1146 def list_own(t):
1147 """
1148 List own
1149 """
1150 rel = []
1151 next_cursor = -1
1152 while next_cursor != 0:
1153 res = t.lists.ownerships(
1154 screen_name=g['original_name'],
1155 cursor=next_cursor)
1156 rel += res['lists']
1157 next_cursor = res['next_cursor']
1158 if rel:
1159 print_list(rel)
1160 else:
1161 printNicely(light_magenta('You own no lists :)'))
1162
1163
1164 def list_new(t):
1165 """
1166 Create a new list
1167 """
1168 name = raw_input(light_magenta('New list\'s name: ', rl=True))
1169 mode = raw_input(
1170 light_magenta(
1171 'New list\'s mode (public/private): ',
1172 rl=True))
1173 description = raw_input(
1174 light_magenta(
1175 'New list\'s description: ',
1176 rl=True))
1177 try:
1178 t.lists.create(
1179 name=name,
1180 mode=mode,
1181 description=description)
1182 printNicely(green(name + ' list is created.'))
1183 except:
1184 debug_option()
1185 printNicely(red('Oops something is wrong with Twitter :('))
1186
1187
1188 def list_update(t):
1189 """
1190 Update a list
1191 """
1192 slug = raw_input(
1193 light_magenta(
1194 'Your list that you want to update: ',
1195 rl=True))
1196 name = raw_input(
1197 light_magenta(
1198 'Update name (leave blank to unchange): ',
1199 rl=True))
1200 mode = raw_input(light_magenta('Update mode (public/private): ', rl=True))
1201 description = raw_input(light_magenta('Update description: ', rl=True))
1202 try:
1203 if name:
1204 t.lists.update(
1205 slug='-'.join(slug.split()),
1206 owner_screen_name=g['original_name'],
1207 name=name,
1208 mode=mode,
1209 description=description)
1210 else:
1211 t.lists.update(
1212 slug=slug,
1213 owner_screen_name=g['original_name'],
1214 mode=mode,
1215 description=description)
1216 printNicely(green(slug + ' list is updated.'))
1217 except:
1218 debug_option()
1219 printNicely(red('Oops something is wrong with Twitter :('))
1220
1221
1222 def list_delete(t):
1223 """
1224 Delete a list
1225 """
1226 slug = raw_input(
1227 light_magenta(
1228 'Your list that you want to delete: ',
1229 rl=True))
1230 try:
1231 t.lists.destroy(
1232 slug='-'.join(slug.split()),
1233 owner_screen_name=g['original_name'])
1234 printNicely(green(slug + ' list is deleted.'))
1235 except:
1236 debug_option()
1237 printNicely(red('Oops something is wrong with Twitter :('))
1238
1239
1240 def twitterlist():
1241 """
1242 Twitter's list
1243 """
1244 t = Twitter(auth=authen())
1245 # List all lists or base on action
1246 try:
1247 g['list_action'] = g['stuff'].split()[0]
1248 except:
1249 show_lists(t)
1250 return
1251 # Sub-function
1252 action_ary = {
1253 'home': list_home,
1254 'all_mem': list_members,
1255 'all_sub': list_subscribers,
1256 'add': list_add,
1257 'rm': list_remove,
1258 'sub': list_subscribe,
1259 'unsub': list_unsubscribe,
1260 'own': list_own,
1261 'new': list_new,
1262 'update': list_update,
1263 'del': list_delete,
1264 }
1265 try:
1266 return action_ary[g['list_action']](t)
1267 except:
1268 printNicely(red('Please try again.'))
1269
1270
1271 def switch():
1272 """
1273 Switch stream
1274 """
1275 try:
1276 target = g['stuff'].split()[0]
1277 # Filter and ignore
1278 args = parse_arguments()
1279 try:
1280 if g['stuff'].split()[-1] == '-f':
1281 guide = 'To ignore an option, just hit Enter key.'
1282 printNicely(light_magenta(guide))
1283 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
1284 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1285 args.filter = filter(None, only.split(','))
1286 args.ignore = filter(None, ignore.split(','))
1287 except:
1288 printNicely(red('Sorry, wrong format.'))
1289 return
1290 # Kill old thread
1291 g['stream_stop'] = True
1292 try:
1293 stuff = g['stuff'].split()[1]
1294 except:
1295 stuff = None
1296 # Spawn new thread
1297 spawn_dict = {
1298 'public': spawn_public_stream,
1299 'list': spawn_list_stream,
1300 'mine': spawn_personal_stream,
1301 }
1302 spawn_dict.get(target)(args, stuff)
1303 except:
1304 debug_option()
1305 printNicely(red('Sorry I can\'t understand.'))
1306
1307
1308 def cal():
1309 """
1310 Unix's command `cal`
1311 """
1312 # Format
1313 rel = os.popen('cal').read().split('\n')
1314 month = rel.pop(0)
1315 date = rel.pop(0)
1316 show_calendar(month, date, rel)
1317
1318
1319 def theme():
1320 """
1321 List and change theme
1322 """
1323 if not g['stuff']:
1324 # List themes
1325 for theme in g['themes']:
1326 line = light_magenta(theme)
1327 if c['THEME'] == theme:
1328 line = ' ' * 2 + light_yellow('* ') + line
1329 else:
1330 line = ' ' * 4 + line
1331 printNicely(line)
1332 else:
1333 # Change theme
1334 try:
1335 # Load new theme
1336 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1337 # Redefine decorated_name
1338 g['decorated_name'] = lambda x: color_func(
1339 c['DECORATED_NAME'])(
1340 '[' + x + ']: ')
1341 printNicely(green('Theme changed.'))
1342 except:
1343 printNicely(red('No such theme exists.'))
1344
1345
1346 def config():
1347 """
1348 Browse and change config
1349 """
1350 all_config = get_all_config()
1351 g['stuff'] = g['stuff'].strip()
1352 # List all config
1353 if not g['stuff']:
1354 for k in all_config:
1355 line = ' ' * 2 + \
1356 green(k) + ': ' + light_yellow(str(all_config[k]))
1357 printNicely(line)
1358 guide = 'Detailed explanation can be found at ' + \
1359 color_func(c['TWEET']['link'])(
1360 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
1361 printNicely(guide)
1362 # Print specific config
1363 elif len(g['stuff'].split()) == 1:
1364 if g['stuff'] in all_config:
1365 k = g['stuff']
1366 line = ' ' * 2 + \
1367 green(k) + ': ' + light_yellow(str(all_config[k]))
1368 printNicely(line)
1369 else:
1370 printNicely(red('No such config key.'))
1371 # Print specific config's default value
1372 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1373 key = g['stuff'].split()[0]
1374 try:
1375 value = get_default_config(key)
1376 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
1377 printNicely(line)
1378 except:
1379 debug_option()
1380 printNicely(red('Just can not get the default.'))
1381 # Delete specific config key in config file
1382 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1383 key = g['stuff'].split()[0]
1384 try:
1385 delete_config(key)
1386 printNicely(green('Config key is dropped.'))
1387 except:
1388 debug_option()
1389 printNicely(red('Just can not drop the key.'))
1390 # Set specific config
1391 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
1392 key = g['stuff'].split()[0]
1393 value = g['stuff'].split()[-1]
1394 if key == 'THEME' and not validate_theme(value):
1395 printNicely(red('Invalid theme\'s value.'))
1396 return
1397 try:
1398 set_config(key, value)
1399 # Keys that needs to be apply immediately
1400 if key == 'THEME':
1401 c['THEME'] = reload_theme(value, c['THEME'])
1402 g['decorated_name'] = lambda x: color_func(
1403 c['DECORATED_NAME'])('[' + x + ']: ')
1404 elif key == 'PREFIX':
1405 g['PREFIX'] = u2str(emojize(format_prefix(
1406 listname=g['listname'],
1407 keyword=g['keyword']
1408 )))
1409 reload_config()
1410 printNicely(green('Updated successfully.'))
1411 except:
1412 debug_option()
1413 printNicely(red('Just can not set the key.'))
1414 else:
1415 printNicely(light_magenta('Sorry I can\'s understand.'))
1416
1417
1418 def help_discover():
1419 """
1420 Discover the world
1421 """
1422 s = ' ' * 2
1423 # Discover the world
1424 usage = '\n'
1425 usage += s + grey(u'\u266A' + ' Discover the world \n')
1426 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1427 'You can try ' + light_green('trend US') + ' or ' + \
1428 light_green('trend JP Tokyo') + '.\n'
1429 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1430 light_green('home 7') + ' will show 7 tweets.\n'
1431 usage += s * 2 + \
1432 light_green('notification') + ' will show your recent notification.\n'
1433 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1434 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1435 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
1436 magenta('@mdo') + '.\n'
1437 usage += s * 2 + light_green('view @mdo') + \
1438 ' will show ' + magenta('@mdo') + '\'s home.\n'
1439 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1440 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1441 'Search can be performed with or without hashtag.\n'
1442 printNicely(usage)
1443
1444
1445 def help_tweets():
1446 """
1447 Tweets
1448 """
1449 s = ' ' * 2
1450 # Tweet
1451 usage = '\n'
1452 usage += s + grey(u'\u266A' + ' Tweets \n')
1453 usage += s * 2 + light_green('t oops ') + \
1454 'will tweet "' + light_yellow('oops') + '" immediately.\n'
1455 usage += s * 2 + \
1456 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1457 light_yellow('[id=12]') + '.\n'
1458 usage += s * 2 + \
1459 light_green('quote 12 ') + ' will quote the tweet with ' + \
1460 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1461 'the quote will be canceled.\n'
1462 usage += s * 2 + \
1463 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1464 light_yellow('[id=12]') + '.\n'
1465 usage += s * 2 + light_green('conversation 12') + ' will show the chain of ' + \
1466 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
1467 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1468 light_yellow('oops') + '" to the owner of the tweet with ' + \
1469 light_yellow('[id=12]') + '.\n'
1470 usage += s * 2 + light_green('repall 12 oops') + ' will reply "' + \
1471 light_yellow('oops') + '" to all people in the tweet with ' + \
1472 light_yellow('[id=12]') + '.\n'
1473 usage += s * 2 + \
1474 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1475 light_yellow('[id=12]') + '.\n'
1476 usage += s * 2 + \
1477 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1478 light_yellow('[id=12]') + '.\n'
1479 usage += s * 2 + \
1480 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1481 light_yellow('[id=12]') + '.\n'
1482 usage += s * 2 + \
1483 light_green('del 12 ') + ' will delete tweet with ' + \
1484 light_yellow('[id=12]') + '.\n'
1485 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1486 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
1487 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1488 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
1489 printNicely(usage)
1490
1491
1492 def help_messages():
1493 """
1494 Messages
1495 """
1496 s = ' ' * 2
1497 # Direct message
1498 usage = '\n'
1499 usage += s + grey(u'\u266A' + ' Direct messages \n')
1500 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1501 light_green('inbox 7') + ' will show newest 7 messages.\n'
1502 usage += s * 2 + light_green('thread 2') + ' will show full thread with ' + \
1503 light_yellow('[thread_id=2]') + '.\n'
1504 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
1505 magenta('@dtvd88') + '.\n'
1506 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1507 light_yellow('[message_id=5]') + '.\n'
1508 printNicely(usage)
1509
1510
1511 def help_friends_and_followers():
1512 """
1513 Friends and Followers
1514 """
1515 s = ' ' * 2
1516 # Follower and following
1517 usage = '\n'
1518 usage += s + grey(u'\u266A' + ' Friends and followers \n')
1519 usage += s * 2 + \
1520 light_green('ls fl') + \
1521 ' will list all followers (people who are following you).\n'
1522 usage += s * 2 + \
1523 light_green('ls fr') + \
1524 ' will list all friends (people who you are following).\n'
1525 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
1526 magenta('@dtvd88') + '.\n'
1527 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
1528 magenta('@dtvd88') + '.\n'
1529 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
1530 magenta('@dtvd88') + '.\n'
1531 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
1532 magenta('@dtvd88') + '.\n'
1533 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1534 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
1535 magenta('@dtvd88') + '.\n'
1536 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
1537 magenta('@dtvd88') + '.\n'
1538 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
1539 magenta('@dtvd88') + ' as a spam account.\n'
1540 printNicely(usage)
1541
1542
1543 def help_list():
1544 """
1545 Lists
1546 """
1547 s = ' ' * 2
1548 # Twitter list
1549 usage = '\n'
1550 usage += s + grey(u'\u266A' + ' Twitter list\n')
1551 usage += s * 2 + light_green('list') + \
1552 ' will show all lists you are belong to.\n'
1553 usage += s * 2 + light_green('list home') + \
1554 ' will show timeline of list. You will be asked for list\'s name.\n'
1555 usage += s * 2 + light_green('list all_mem') + \
1556 ' will show list\'s all members.\n'
1557 usage += s * 2 + light_green('list all_sub') + \
1558 ' will show list\'s all subscribers.\n'
1559 usage += s * 2 + light_green('list add') + \
1560 ' will add specific person to a list owned by you.' + \
1561 ' You will be asked for list\'s name and person\'s name.\n'
1562 usage += s * 2 + light_green('list rm') + \
1563 ' will remove specific person from a list owned by you.' + \
1564 ' You will be asked for list\'s name and person\'s name.\n'
1565 usage += s * 2 + light_green('list sub') + \
1566 ' will subscribe you to a specific list.\n'
1567 usage += s * 2 + light_green('list unsub') + \
1568 ' will unsubscribe you from a specific list.\n'
1569 usage += s * 2 + light_green('list own') + \
1570 ' will show all list owned by you.\n'
1571 usage += s * 2 + light_green('list new') + \
1572 ' will create a new list.\n'
1573 usage += s * 2 + light_green('list update') + \
1574 ' will update a list owned by you.\n'
1575 usage += s * 2 + light_green('list del') + \
1576 ' will delete a list owned by you.\n'
1577 printNicely(usage)
1578
1579
1580 def help_stream():
1581 """
1582 Stream switch
1583 """
1584 s = ' ' * 2
1585 # Switch
1586 usage = '\n'
1587 usage += s + grey(u'\u266A' + ' Switching streams \n')
1588 usage += s * 2 + light_green('switch public #AKB') + \
1589 ' will switch to public stream and follow "' + \
1590 light_yellow('AKB') + '" keyword.\n'
1591 usage += s * 2 + light_green('switch mine') + \
1592 ' will switch to your personal stream.\n'
1593 usage += s * 2 + light_green('switch mine -f ') + \
1594 ' will prompt to enter the filter.\n'
1595 usage += s * 3 + light_yellow('Only nicks') + \
1596 ' filter will decide nicks will be INCLUDE ONLY.\n'
1597 usage += s * 3 + light_yellow('Ignore nicks') + \
1598 ' filter will decide nicks will be EXCLUDE.\n'
1599 usage += s * 2 + light_green('switch list') + \
1600 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
1601 printNicely(usage)
1602
1603
1604 def help():
1605 """
1606 Help
1607 """
1608 s = ' ' * 2
1609 h, w = os.popen('stty size', 'r').read().split()
1610 # Start
1611 usage = '\n'
1612 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1613 usage += s + '-' * (int(w) - 4) + '\n'
1614 usage += s + 'You are ' + \
1615 light_yellow('already') + ' on your personal stream.\n'
1616 usage += s + 'Any update from Twitter will show up ' + \
1617 light_yellow('immediately') + '.\n'
1618 usage += s + 'In addition, following commands are available right now:\n'
1619 # Twitter help section
1620 usage += '\n'
1621 usage += s + grey(u'\u266A' + ' Twitter help\n')
1622 usage += s * 2 + light_green('h discover') + \
1623 ' will show help for discover commands.\n'
1624 usage += s * 2 + light_green('h tweets') + \
1625 ' will show help for tweets commands.\n'
1626 usage += s * 2 + light_green('h messages') + \
1627 ' will show help for messages commands.\n'
1628 usage += s * 2 + light_green('h friends_and_followers') + \
1629 ' will show help for friends and followers commands.\n'
1630 usage += s * 2 + light_green('h list') + \
1631 ' will show help for list commands.\n'
1632 usage += s * 2 + light_green('h stream') + \
1633 ' will show help for stream commands.\n'
1634 # Smart shell
1635 usage += '\n'
1636 usage += s + grey(u'\u266A' + ' Smart shell\n')
1637 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1638 'will be evaluate by Python interpreter.\n'
1639 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1640 ' for current month.\n'
1641 # Config
1642 usage += '\n'
1643 usage += s + grey(u'\u266A' + ' Config \n')
1644 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
1645 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
1646 ' theme immediately.\n'
1647 usage += s * 2 + light_green('config') + ' will list all config.\n'
1648 usage += s * 3 + \
1649 light_green('config ASCII_ART') + ' will output current value of ' +\
1650 light_yellow('ASCII_ART') + ' config key.\n'
1651 usage += s * 3 + \
1652 light_green('config TREND_MAX default') + ' will output default value of ' + \
1653 light_yellow('TREND_MAX') + ' config key.\n'
1654 usage += s * 3 + \
1655 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1656 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
1657 usage += s * 3 + \
1658 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1659 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1660 light_yellow('True') + '.\n'
1661 # Screening
1662 usage += '\n'
1663 usage += s + grey(u'\u266A' + ' Screening \n')
1664 usage += s * 2 + light_green('h') + ' will show this help again.\n'
1665 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1666 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
1667 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1668 usage += s * 2 + light_green('v') + ' will show version info.\n'
1669 usage += s * 2 + light_green('q') + ' will quit.\n'
1670 # End
1671 usage += '\n'
1672 usage += s + '-' * (int(w) - 4) + '\n'
1673 usage += s + 'Have fun and hang tight! \n'
1674 # Show help
1675 d = {
1676 'discover': help_discover,
1677 'tweets': help_tweets,
1678 'messages': help_messages,
1679 'friends_and_followers': help_friends_and_followers,
1680 'list': help_list,
1681 'stream': help_stream,
1682 }
1683 if g['stuff']:
1684 d.get(
1685 g['stuff'].strip(),
1686 lambda: printNicely(red('No such command.'))
1687 )()
1688 else:
1689 printNicely(usage)
1690
1691
1692 def pause():
1693 """
1694 Pause stream display
1695 """
1696 g['pause'] = True
1697 printNicely(green('Stream is paused'))
1698
1699
1700 def replay():
1701 """
1702 Replay stream
1703 """
1704 g['pause'] = False
1705 printNicely(green('Stream is running back now'))
1706
1707
1708 def clear():
1709 """
1710 Clear screen
1711 """
1712 os.system('clear')
1713
1714
1715 def quit():
1716 """
1717 Exit all
1718 """
1719 try:
1720 save_history()
1721 printNicely(green('See you next time :)'))
1722 except:
1723 pass
1724 sys.exit()
1725
1726
1727 def reset():
1728 """
1729 Reset prefix of line
1730 """
1731 if g['reset']:
1732 if c.get('USER_JSON_ERROR'):
1733 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1734 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1735 printNicely('')
1736 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
1737 g['reset'] = False
1738 try:
1739 printNicely(str(eval(g['cmd'])))
1740 except Exception:
1741 pass
1742
1743
1744 # Command set
1745 cmdset = [
1746 'switch',
1747 'trend',
1748 'home',
1749 'notification',
1750 'view',
1751 'mentions',
1752 't',
1753 'rt',
1754 'quote',
1755 'allrt',
1756 'conversation',
1757 'fav',
1758 'rep',
1759 'repall',
1760 'del',
1761 'ufav',
1762 'share',
1763 's',
1764 'mes',
1765 'show',
1766 'open',
1767 'ls',
1768 'inbox',
1769 'thread',
1770 'trash',
1771 'whois',
1772 'fl',
1773 'ufl',
1774 'mute',
1775 'unmute',
1776 'muting',
1777 'block',
1778 'unblock',
1779 'report',
1780 'list',
1781 'cal',
1782 'config',
1783 'theme',
1784 'h',
1785 'p',
1786 'r',
1787 'c',
1788 'v',
1789 'q',
1790 ]
1791
1792 # Handle function set
1793 funcset = [
1794 switch,
1795 trend,
1796 home,
1797 notification,
1798 view,
1799 mentions,
1800 tweet,
1801 retweet,
1802 quote,
1803 allretweet,
1804 conversation,
1805 favorite,
1806 reply,
1807 reply_all,
1808 delete,
1809 unfavorite,
1810 share,
1811 search,
1812 message,
1813 show,
1814 urlopen,
1815 ls,
1816 inbox,
1817 thread,
1818 trash,
1819 whois,
1820 follow,
1821 unfollow,
1822 mute,
1823 unmute,
1824 muting,
1825 block,
1826 unblock,
1827 report,
1828 twitterlist,
1829 cal,
1830 config,
1831 theme,
1832 help,
1833 pause,
1834 replay,
1835 clear,
1836 upgrade_center,
1837 quit,
1838 ]
1839
1840
1841 def process(cmd):
1842 """
1843 Process switch
1844 """
1845 return dict(zip(cmdset, funcset)).get(cmd, reset)
1846
1847
1848 def listen():
1849 """
1850 Listen to user's input
1851 """
1852 d = dict(zip(
1853 cmdset,
1854 [
1855 ['public', 'mine', 'list'], # switch
1856 [], # trend
1857 [], # home
1858 [], # notification
1859 ['@'], # view
1860 [], # mentions
1861 [], # tweet
1862 [], # retweet
1863 [], # quote
1864 [], # allretweet
1865 [], # conversation
1866 [], # favorite
1867 [], # reply
1868 [], # reply_all
1869 [], # delete
1870 [], # unfavorite
1871 [], # url
1872 ['#'], # search
1873 ['@'], # message
1874 ['image'], # show image
1875 [''], # open url
1876 ['fl', 'fr'], # list
1877 [], # inbox
1878 [i for i in g['message_threads']], # sent
1879 [], # trash
1880 ['@'], # whois
1881 ['@'], # follow
1882 ['@'], # unfollow
1883 ['@'], # mute
1884 ['@'], # unmute
1885 ['@'], # muting
1886 ['@'], # block
1887 ['@'], # unblock
1888 ['@'], # report
1889 [
1890 'home',
1891 'all_mem',
1892 'all_sub',
1893 'add',
1894 'rm',
1895 'sub',
1896 'unsub',
1897 'own',
1898 'new',
1899 'update',
1900 'del'
1901 ], # list
1902 [], # cal
1903 [key for key in dict(get_all_config())], # config
1904 g['themes'], # theme
1905 [
1906 'discover',
1907 'tweets',
1908 'messages',
1909 'friends_and_followers',
1910 'list',
1911 'stream'
1912 ], # help
1913 [], # pause
1914 [], # reconnect
1915 [], # clear
1916 [], # version
1917 [], # quit
1918 ]
1919 ))
1920 init_interactive_shell(d)
1921 read_history()
1922 reset()
1923 while True:
1924 try:
1925 # raw_input
1926 if g['prefix']:
1927 # Only use PREFIX as a string with raw_input
1928 line = raw_input(g['decorated_name'](g['PREFIX']))
1929 else:
1930 line = raw_input()
1931 # Save cmd to compare with readline buffer
1932 g['cmd'] = line.strip()
1933 # Get short cmd to pass to handle function
1934 try:
1935 cmd = line.split()[0]
1936 except:
1937 cmd = ''
1938 # Lock the semaphore
1939 c['lock'] = True
1940 # Save cmd to global variable and call process
1941 g['stuff'] = ' '.join(line.split()[1:])
1942 # Process the command
1943 process(cmd)()
1944 # Not re-display
1945 if cmd in ['switch', 't', 'rt', 'rep']:
1946 g['prefix'] = False
1947 else:
1948 g['prefix'] = True
1949 # Release the semaphore lock
1950 c['lock'] = False
1951 except EOFError:
1952 printNicely('')
1953 except Exception:
1954 debug_option()
1955 printNicely(red('OMG something is wrong with Twitter right now.'))
1956
1957
1958 def reconn_notice():
1959 """
1960 Notice when Hangup or Timeout
1961 """
1962 guide = light_magenta('You can use ') + \
1963 light_green('switch') + \
1964 light_magenta(' command to return to your stream.\n')
1965 guide += light_magenta('Type ') + \
1966 light_green('h stream') + \
1967 light_magenta(' for more details.')
1968 printNicely(guide)
1969 sys.stdout.write(g['decorated_name'](g['PREFIX']))
1970 sys.stdout.flush()
1971
1972
1973 def stream(domain, args, name='Rainbow Stream'):
1974 """
1975 Track the stream
1976 """
1977 # The Logo
1978 art_dict = {
1979 c['USER_DOMAIN']: name,
1980 c['PUBLIC_DOMAIN']: args.track_keywords or 'Global',
1981 c['SITE_DOMAIN']: name,
1982 }
1983 if c['ASCII_ART']:
1984 ascii_art(art_dict.get(domain, name))
1985 # These arguments are optional:
1986 stream_args = dict(
1987 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
1988 block=True,
1989 heartbeat_timeout=c['HEARTBEAT_TIMEOUT'] * 60)
1990 # Track keyword
1991 query_args = dict()
1992 if args.track_keywords:
1993 query_args['track'] = args.track_keywords
1994 # Get stream
1995 stream = TwitterStream(
1996 auth=authen(),
1997 domain=domain,
1998 **stream_args)
1999 try:
2000 if domain == c['USER_DOMAIN']:
2001 tweet_iter = stream.user(**query_args)
2002 elif domain == c['SITE_DOMAIN']:
2003 tweet_iter = stream.site(**query_args)
2004 else:
2005 if args.track_keywords:
2006 tweet_iter = stream.statuses.filter(**query_args)
2007 else:
2008 tweet_iter = stream.statuses.sample()
2009 # Block new stream until other one exits
2010 StreamLock.acquire()
2011 g['stream_stop'] = False
2012 last_tweet_time = time.time()
2013 for tweet in tweet_iter:
2014 if tweet is None:
2015 printNicely('-- None --')
2016 elif tweet is Timeout:
2017 # Because the stream check for each 0.3s
2018 # so we shouldn't output anything here
2019 if(g['stream_stop']):
2020 StreamLock.release()
2021 break
2022 elif tweet is HeartbeatTimeout:
2023 printNicely('-- Heartbeat Timeout --')
2024 reconn_notice()
2025 StreamLock.release()
2026 break
2027 elif tweet is Hangup:
2028 printNicely('-- Hangup --')
2029 reconn_notice()
2030 StreamLock.release()
2031 break
2032 elif tweet.get('text'):
2033 # Slow down the stream by STREAM_DELAY config key
2034 if time.time() - last_tweet_time < c['STREAM_DELAY']:
2035 continue
2036 last_tweet_time = time.time()
2037 # Check the semaphore pause and lock (stream process only)
2038 if g['pause']:
2039 continue
2040 while c['lock']:
2041 time.sleep(0.5)
2042 # Draw the tweet
2043 draw(
2044 t=tweet,
2045 keyword=args.track_keywords,
2046 humanize=False,
2047 fil=args.filter,
2048 ig=args.ignore,
2049 )
2050 # Current readline buffer
2051 current_buffer = readline.get_line_buffer().strip()
2052 # There is an unexpected behaviour in MacOSX readline + Python 2:
2053 # after completely delete a word after typing it,
2054 # somehow readline buffer still contains
2055 # the 1st character of that word
2056 if current_buffer and g['cmd'] != current_buffer:
2057 sys.stdout.write(
2058 g['decorated_name'](g['PREFIX']) + current_buffer)
2059 sys.stdout.flush()
2060 elif not c['HIDE_PROMPT']:
2061 sys.stdout.write(g['decorated_name'](g['PREFIX']))
2062 sys.stdout.flush()
2063 elif tweet.get('direct_message'):
2064 # Check the semaphore pause and lock (stream process only)
2065 if g['pause']:
2066 continue
2067 while c['lock']:
2068 time.sleep(0.5)
2069 print_message(tweet['direct_message'])
2070 elif tweet.get('event'):
2071 c['events'].append(tweet)
2072 print_event(tweet)
2073 except TwitterHTTPError as e:
2074 printNicely('')
2075 printNicely(
2076 magenta('We have connection problem with twitter stream API right now :('))
2077 detail_twitter_error(e)
2078 sys.stdout.write(g['decorated_name'](g['PREFIX']))
2079 sys.stdout.flush()
2080 except (URLError, ConnectionResetError):
2081 printNicely(
2082 magenta('There seems to be a connection problem.'))
2083 save_history()
2084 sys.exit()
2085
2086
2087 def spawn_public_stream(args, keyword=None):
2088 """
2089 Spawn a new public stream
2090 """
2091 # Only set keyword if specified
2092 if keyword:
2093 if keyword[0] == '#':
2094 keyword = keyword[1:]
2095 args.track_keywords = keyword
2096 g['keyword'] = keyword
2097 else:
2098 g['keyword'] = 'Global'
2099 g['PREFIX'] = u2str(emojize(format_prefix(keyword=g['keyword'])))
2100 g['listname'] = ''
2101 # Start new thread
2102 th = threading.Thread(
2103 target=stream,
2104 args=(
2105 c['PUBLIC_DOMAIN'],
2106 args))
2107 th.daemon = True
2108 th.start()
2109
2110
2111 def spawn_list_stream(args, stuff=None):
2112 """
2113 Spawn a new list stream
2114 """
2115 try:
2116 owner, slug = check_slug(stuff)
2117 except:
2118 owner, slug = get_slug()
2119
2120 # Force python 2 not redraw readline buffer
2121 listname = '/'.join([owner, slug])
2122 # Set the listname variable
2123 # and reset tracked keyword
2124 g['listname'] = listname
2125 g['keyword'] = ''
2126 g['PREFIX'] = g['cmd'] = u2str(emojize(format_prefix(
2127 listname=g['listname']
2128 )))
2129 printNicely(light_yellow('getting list members ...'))
2130 # Get members
2131 t = Twitter(auth=authen())
2132 members = []
2133 next_cursor = -1
2134 while next_cursor != 0:
2135 m = t.lists.members(
2136 slug=slug,
2137 owner_screen_name=owner,
2138 cursor=next_cursor,
2139 include_entities=False)
2140 for u in m['users']:
2141 members.append('@' + u['screen_name'])
2142 next_cursor = m['next_cursor']
2143 printNicely(light_yellow('... done.'))
2144 # Build thread filter array
2145 args.filter = members
2146 # Start new thread
2147 th = threading.Thread(
2148 target=stream,
2149 args=(
2150 c['USER_DOMAIN'],
2151 args,
2152 slug))
2153 th.daemon = True
2154 th.start()
2155 printNicely('')
2156 if args.filter:
2157 printNicely(cyan('Include: ' + str(len(args.filter)) + ' people.'))
2158 if args.ignore:
2159 printNicely(red('Ignore: ' + str(len(args.ignore)) + ' people.'))
2160 printNicely('')
2161
2162
2163 def spawn_personal_stream(args, stuff=None):
2164 """
2165 Spawn a new personal stream
2166 """
2167 # Reset the tracked keyword and listname
2168 g['keyword'] = g['listname'] = ''
2169 # Reset prefix
2170 g['PREFIX'] = u2str(emojize(format_prefix()))
2171 # Start new thread
2172 th = threading.Thread(
2173 target=stream,
2174 args=(
2175 c['USER_DOMAIN'],
2176 args,
2177 g['original_name']))
2178 th.daemon = True
2179 th.start()
2180
2181
2182 def fly():
2183 """
2184 Main function
2185 """
2186 # Initial
2187 args = parse_arguments()
2188 try:
2189 proxy_connect(args)
2190 init(args)
2191 # Twitter API connection problem
2192 except TwitterHTTPError as e:
2193 printNicely('')
2194 printNicely(
2195 magenta('We have connection problem with twitter REST API right now :('))
2196 detail_twitter_error(e)
2197 save_history()
2198 sys.exit()
2199 # Proxy connection problem
2200 except (socks.ProxyConnectionError, URLError):
2201 printNicely(
2202 magenta('There seems to be a connection problem.'))
2203 printNicely(
2204 magenta('You might want to check your proxy settings (host, port and type)!'))
2205 save_history()
2206 sys.exit()
2207
2208 # Spawn stream thread
2209 target = args.stream.split()[0]
2210 if target == 'mine' :
2211 spawn_personal_stream(args)
2212 else:
2213 try:
2214 stuff = args.stream.split()[1]
2215 except:
2216 stuff = None
2217 spawn_dict = {
2218 'public': spawn_public_stream,
2219 'list': spawn_list_stream,
2220 }
2221 spawn_dict.get(target)(args, stuff)
2222
2223 # Start listen process
2224 time.sleep(0.5)
2225 g['reset'] = True
2226 g['prefix'] = True
2227 listen()