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