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