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