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