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