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