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