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