fix small bug
[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
8101275e 510 tid = c['tweet_dict'][int(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.'))
8101275e 1175 except:
1f2f6159 1176 printNicely(red('No such theme exists.'))
632c6fa5
O
1177
1178
2d341029 1179def help_discover():
f405a7d0 1180 """
2d341029 1181 Discover the world
f405a7d0 1182 """
7e4ccbf3 1183 s = ' ' * 2
1f24a05a 1184 # Discover the world
2d341029 1185 usage = '\n'
8bc30efd 1186 usage += s + grey(u'\u266A' + ' Discover the world \n')
c075e6dc
O
1187 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1188 'You can try ' + light_green('trend US') + ' or ' + \
1189 light_green('trend JP Tokyo') + '.\n'
1190 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1191 light_green('home 7') + ' will show 7 tweets.\n'
1192 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1193 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1194 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
8bc30efd 1195 magenta('@mdo') + '.\n'
c075e6dc 1196 usage += s * 2 + light_green('view @mdo') + \
8bc30efd 1197 ' will show ' + magenta('@mdo') + '\'s home.\n'
03e08f86
O
1198 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1199 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1200 'Search can be performed with or without hashtag.\n'
2d341029
O
1201 printNicely(usage)
1202
8bc30efd 1203
2d341029
O
1204def help_tweets():
1205 """
1206 Tweets
1207 """
1208 s = ' ' * 2
1f24a05a 1209 # Tweet
2d341029 1210 usage = '\n'
8bc30efd 1211 usage += s + grey(u'\u266A' + ' Tweets \n')
c075e6dc
O
1212 usage += s * 2 + light_green('t oops ') + \
1213 'will tweet "' + light_yellow('oops') + '" immediately.\n'
7e4ccbf3 1214 usage += s * 2 + \
c075e6dc
O
1215 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1216 light_yellow('[id=12]') + '.\n'
1f24a05a 1217 usage += s * 2 + \
80b70d60
O
1218 light_green('quote 12 ') + ' will quote the tweet with ' + \
1219 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1220 'the quote will be canceled.\n'
1221 usage += s * 2 + \
c075e6dc
O
1222 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1223 light_yellow('[id=12]') + '.\n'
1224 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
1225 light_yellow('oops') + '" to tweet with ' + \
1226 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1227 usage += s * 2 + \
c075e6dc
O
1228 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1229 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1230 usage += s * 2 + \
c075e6dc
O
1231 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1232 light_yellow('[id=12]') + '.\n'
8bc30efd 1233 usage += s * 2 + \
c075e6dc
O
1234 light_green('del 12 ') + ' will delete tweet with ' + \
1235 light_yellow('[id=12]') + '.\n'
1236 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1237 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
80b70d60
O
1238 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1239 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
2d341029 1240 printNicely(usage)
8bc30efd 1241
2d341029
O
1242
1243def help_messages():
1244 """
1245 Messages
1246 """
1247 s = ' ' * 2
5b2c4faf 1248 # Direct message
2d341029 1249 usage = '\n'
8bc30efd 1250 usage += s + grey(u'\u266A' + ' Direct messages \n')
c075e6dc
O
1251 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1252 light_green('inbox 7') + ' will show newest 7 messages.\n'
1253 usage += s * 2 + light_green('sent') + ' will show sent messages. ' + \
1254 light_green('sent 7') + ' will show newest 7 messages.\n'
1255 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
8bc30efd 1256 magenta('@dtvd88') + '.\n'
c075e6dc
O
1257 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1258 light_yellow('[message_id=5]') + '.\n'
2d341029 1259 printNicely(usage)
8bc30efd 1260
2d341029
O
1261
1262def help_friends_and_followers():
1263 """
1264 Friends and Followers
1265 """
1266 s = ' ' * 2
8bc30efd 1267 # Follower and following
2d341029 1268 usage = '\n'
cdccb0d6 1269 usage += s + grey(u'\u266A' + ' Friends and followers \n')
8bc30efd 1270 usage += s * 2 + \
c075e6dc 1271 light_green('ls fl') + \
8bc30efd 1272 ' will list all followers (people who are following you).\n'
1273 usage += s * 2 + \
c075e6dc 1274 light_green('ls fr') + \
8bc30efd 1275 ' will list all friends (people who you are following).\n'
c075e6dc 1276 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
305ce127 1277 magenta('@dtvd88') + '.\n'
c075e6dc 1278 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
305ce127 1279 magenta('@dtvd88') + '.\n'
c075e6dc 1280 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
5b2c4faf 1281 magenta('@dtvd88') + '.\n'
c075e6dc 1282 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
5b2c4faf 1283 magenta('@dtvd88') + '.\n'
c075e6dc
O
1284 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1285 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
305ce127 1286 magenta('@dtvd88') + '.\n'
c075e6dc 1287 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
305ce127 1288 magenta('@dtvd88') + '.\n'
c075e6dc 1289 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
305ce127 1290 magenta('@dtvd88') + ' as a spam account.\n'
2d341029
O
1291 printNicely(usage)
1292
1293
1294def help_list():
1295 """
1296 Lists
1297 """
1298 s = ' ' * 2
1299 # Twitter list
1300 usage = '\n'
1301 usage += s + grey(u'\u266A' + ' Twitter list\n')
1302 usage += s * 2 + light_green('list') + \
1303 ' will show all lists you are belong to.\n'
1304 usage += s * 2 + light_green('list home') + \
bef33491 1305 ' will show timeline of list. You will be asked for list\'s name.\n'
a65bd34c 1306 usage += s * 2 + light_green('list all_mem') + \
2d341029 1307 ' will show list\'s all members.\n'
a65bd34c 1308 usage += s * 2 + light_green('list all_sub') + \
2d341029 1309 ' will show list\'s all subscribers.\n'
422dd385
O
1310 usage += s * 2 + light_green('list add') + \
1311 ' will add specific person to a list owned by you.' + \
1312 ' You will be asked for list\'s name and person\'s name.\n'
2d341029
O
1313 usage += s * 2 + light_green('list rm') + \
1314 ' will remove specific person from a list owned by you.' + \
1315 ' You will be asked for list\'s name and person\'s name.\n'
422dd385
O
1316 usage += s * 2 + light_green('list sub') + \
1317 ' will subscribe you to a specific list.\n'
1318 usage += s * 2 + light_green('list unsub') + \
1319 ' will unsubscribe you from a specific list.\n'
1320 usage += s * 2 + light_green('list own') + \
1321 ' will show all list owned by you.\n'
1322 usage += s * 2 + light_green('list new') + \
1323 ' will create a new list.\n'
1324 usage += s * 2 + light_green('list update') + \
1325 ' will update a list owned by you.\n'
1326 usage += s * 2 + light_green('list del') + \
1327 ' will delete a list owned by you.\n'
2d341029 1328 printNicely(usage)
8bc30efd 1329
2d341029
O
1330
1331def help_stream():
1332 """
1333 Stream switch
1334 """
1335 s = ' ' * 2
8bc30efd 1336 # Switch
2d341029 1337 usage = '\n'
8bc30efd 1338 usage += s + grey(u'\u266A' + ' Switching streams \n')
c075e6dc 1339 usage += s * 2 + light_green('switch public #AKB') + \
48a25fe8 1340 ' will switch to public stream and follow "' + \
c075e6dc
O
1341 light_yellow('AKB') + '" keyword.\n'
1342 usage += s * 2 + light_green('switch mine') + \
48a25fe8 1343 ' will switch to your personal stream.\n'
c075e6dc 1344 usage += s * 2 + light_green('switch mine -f ') + \
48a25fe8 1345 ' will prompt to enter the filter.\n'
c075e6dc 1346 usage += s * 3 + light_yellow('Only nicks') + \
48a25fe8 1347 ' filter will decide nicks will be INCLUDE ONLY.\n'
c075e6dc 1348 usage += s * 3 + light_yellow('Ignore nicks') + \
48a25fe8 1349 ' filter will decide nicks will be EXCLUDE.\n'
c075e6dc 1350 usage += s * 2 + light_green('switch mine -d') + \
48a25fe8 1351 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
2d341029
O
1352 printNicely(usage)
1353
1354
1355def help():
1356 """
1357 Help
1358 """
1359 s = ' ' * 2
1360 h, w = os.popen('stty size', 'r').read().split()
2d341029
O
1361 # Start
1362 usage = '\n'
1363 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1364 usage += s + '-' * (int(w) - 4) + '\n'
1365 usage += s + 'You are ' + \
1366 light_yellow('already') + ' on your personal stream.\n'
1367 usage += s + 'Any update from Twitter will show up ' + \
1368 light_yellow('immediately') + '.\n'
1369 usage += s + 'In addtion, following commands are available right now:\n'
2d341029
O
1370 # Twitter help section
1371 usage += '\n'
1372 usage += s + grey(u'\u266A' + ' Twitter help\n')
1373 usage += s * 2 + light_green('h discover') + \
1374 ' will show help for discover commands.\n'
1375 usage += s * 2 + light_green('h tweets') + \
1376 ' will show help for tweets commands.\n'
1377 usage += s * 2 + light_green('h messages') + \
1378 ' will show help for messages commands.\n'
1379 usage += s * 2 + light_green('h friends_and_followers') + \
1380 ' will show help for friends and followers commands.\n'
1381 usage += s * 2 + light_green('h list') + \
1382 ' will show help for list commands.\n'
1383 usage += s * 2 + light_green('h stream') + \
1384 ' will show help for stream commands.\n'
1f24a05a 1385 # Smart shell
1386 usage += '\n'
1387 usage += s + grey(u'\u266A' + ' Smart shell\n')
c075e6dc 1388 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1f24a05a 1389 'will be evaluate by Python interpreter.\n'
c075e6dc 1390 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1f24a05a 1391 ' for current month.\n'
29fd0be6 1392 # Config
1f24a05a 1393 usage += '\n'
29fd0be6
O
1394 usage += s + grey(u'\u266A' + ' Config \n')
1395 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
c075e6dc 1396 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
632c6fa5 1397 ' theme immediately.\n'
29fd0be6
O
1398 usage += s * 2 + light_green('config') + ' will list all config.\n'
1399 usage += s * 3 + \
1400 light_green('config ASCII_ART') + ' will output current value of ' +\
a8c5fce4 1401 light_yellow('ASCII_ART') + ' config key.\n'
29fd0be6 1402 usage += s * 3 + \
fe9bb33b 1403 light_green('config TREND_MAX default') + ' will output default value of ' + \
1404 light_yellow('TREND_MAX') + ' config key.\n'
1405 usage += s * 3 + \
1406 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1407 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
29fd0be6 1408 usage += s * 3 + \
fe9bb33b 1409 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1410 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1411 light_yellow('True') + '.\n'
29fd0be6
O
1412 # Screening
1413 usage += '\n'
1414 usage += s + grey(u'\u266A' + ' Screening \n')
c075e6dc 1415 usage += s * 2 + light_green('h') + ' will show this help again.\n'
d6cc4c67
O
1416 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1417 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
c075e6dc
O
1418 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
1419 usage += s * 2 + light_green('q') + ' will quit.\n'
8bc30efd 1420 # End
1421 usage += '\n'
7e4ccbf3 1422 usage += s + '-' * (int(w) - 4) + '\n'
8bc30efd 1423 usage += s + 'Have fun and hang tight! \n'
2d341029
O
1424 # Show help
1425 d = {
422dd385
O
1426 'discover': help_discover,
1427 'tweets': help_tweets,
1428 'messages': help_messages,
1429 'friends_and_followers': help_friends_and_followers,
1430 'list': help_list,
1431 'stream': help_stream,
2d341029
O
1432 }
1433 if g['stuff']:
1434 d[g['stuff'].strip()]()
1435 else:
1436 printNicely(usage)
f405a7d0
O
1437
1438
d6cc4c67
O
1439def pause():
1440 """
1441 Pause stream display
1442 """
99b52f5f 1443 c['pause'] = True
d6cc4c67
O
1444 printNicely(green('Stream is paused'))
1445
1446
1447def replay():
1448 """
1449 Replay stream
1450 """
99b52f5f 1451 c['pause'] = False
d6cc4c67
O
1452 printNicely(green('Stream is running back now'))
1453
1454
843647ad 1455def clear():
f405a7d0 1456 """
7b674cef 1457 Clear screen
f405a7d0 1458 """
843647ad 1459 os.system('clear')
f405a7d0
O
1460
1461
843647ad 1462def quit():
b8dda704
O
1463 """
1464 Exit all
1465 """
4c025026 1466 try:
1467 save_history()
4c025026 1468 printNicely(green('See you next time :)'))
1469 except:
1470 pass
843647ad 1471 sys.exit()
b8dda704
O
1472
1473
94a5f62e 1474def reset():
f405a7d0 1475 """
94a5f62e 1476 Reset prefix of line
f405a7d0 1477 """
c91f75f2 1478 if g['reset']:
e3885f55 1479 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
c91f75f2 1480 g['reset'] = False
d0a726d6 1481 try:
2a0cabee
O
1482 printNicely(str(eval(g['cmd'])))
1483 except Exception:
d0a726d6 1484 pass
54277114
O
1485
1486
94a5f62e 1487def process(cmd):
54277114 1488 """
94a5f62e 1489 Process switch
54277114 1490 """
94a5f62e 1491 return dict(zip(
1492 cmdset,
b2b933a9 1493 [
42fde775 1494 switch,
4592d231 1495 trend,
b2b933a9 1496 home,
1497 view,
305ce127 1498 mentions,
b2b933a9 1499 tweet,
1500 retweet,
80b70d60 1501 quote,
1f24a05a 1502 allretweet,
7e4ccbf3 1503 favorite,
b2b933a9 1504 reply,
1505 delete,
7e4ccbf3 1506 unfavorite,
b2b933a9 1507 search,
305ce127 1508 message,
f5677fb1 1509 show,
80bb2040 1510 urlopen,
2d341029 1511 ls,
305ce127 1512 inbox,
1513 sent,
1514 trash,
e2b81717 1515 whois,
f5677fb1
O
1516 follow,
1517 unfollow,
5b2c4faf 1518 mute,
1519 unmute,
1520 muting,
305ce127 1521 block,
1522 unblock,
1523 report,
2d341029 1524 list,
813a5d80 1525 cal,
29fd0be6 1526 config,
632c6fa5 1527 theme,
b2b933a9 1528 help,
d6cc4c67
O
1529 pause,
1530 replay,
b2b933a9 1531 clear,
1532 quit
1533 ]
94a5f62e 1534 )).get(cmd, reset)
1535
1536
1537def listen():
42fde775 1538 """
1539 Listen to user's input
1540 """
d51b4107
O
1541 d = dict(zip(
1542 cmdset,
1543 [
affcb149 1544 ['public', 'mine'], # switch
4592d231 1545 [], # trend
7e4ccbf3 1546 [], # home
1547 ['@'], # view
305ce127 1548 [], # mentions
7e4ccbf3 1549 [], # tweet
1550 [], # retweet
80b70d60 1551 [], # quote
1f24a05a 1552 [], # allretweet
f5677fb1 1553 [], # favorite
7e4ccbf3 1554 [], # reply
1555 [], # delete
f5677fb1 1556 [], # unfavorite
7e4ccbf3 1557 ['#'], # search
305ce127 1558 ['@'], # message
f5677fb1 1559 ['image'], # show image
80b70d60 1560 [''], # open url
305ce127 1561 ['fl', 'fr'], # list
1562 [], # inbox
1563 [], # sent
1564 [], # trash
e2b81717 1565 ['@'], # whois
affcb149
O
1566 ['@'], # follow
1567 ['@'], # unfollow
5b2c4faf 1568 ['@'], # mute
1569 ['@'], # unmute
1570 ['@'], # muting
305ce127 1571 ['@'], # block
1572 ['@'], # unblock
1573 ['@'], # report
422dd385
O
1574 [
1575 'home',
1576 'all_mem',
1577 'all_sub',
1578 'add',
1579 'rm',
1580 'sub',
1581 'unsub',
1582 'own',
1583 'new',
1584 'update',
1585 'del'
1586 ], # list
813a5d80 1587 [], # cal
a8c5fce4 1588 [key for key in dict(get_all_config())], # config
ceec8593 1589 g['themes'], # theme
422dd385
O
1590 [
1591 'discover',
1592 'tweets',
1593 'messages',
1594 'friends_and_followers',
1595 'list',
1596 'stream'
1597 ], # help
d6cc4c67
O
1598 [], # pause
1599 [], # reconnect
7e4ccbf3 1600 [], # clear
1601 [], # quit
d51b4107 1602 ]
7e4ccbf3 1603 ))
d51b4107 1604 init_interactive_shell(d)
f5677fb1 1605 read_history()
819569e8 1606 reset()
b2b933a9 1607 while True:
99b52f5f 1608 # raw_input
1dd312f5 1609 if g['prefix']:
ceec8593 1610 line = raw_input(g['decorated_name'](c['PREFIX']))
1dd312f5
O
1611 else:
1612 line = raw_input()
843647ad
O
1613 try:
1614 cmd = line.split()[0]
1615 except:
1616 cmd = ''
d0a726d6 1617 g['cmd'] = cmd
b8c1f42a 1618 try:
9683e61d 1619 # Lock the semaphore
99b52f5f 1620 c['lock'] = True
9683e61d 1621 # Save cmd to global variable and call process
b8c1f42a 1622 g['stuff'] = ' '.join(line.split()[1:])
9683e61d 1623 # Process the command
b8c1f42a 1624 process(cmd)()
9683e61d 1625 # Not re-display
99b52f5f 1626 if cmd in ['switch', 't', 'rt', 'rep']:
9683e61d
O
1627 g['prefix'] = False
1628 else:
1629 g['prefix'] = True
1630 # Release the semaphore lock
99b52f5f 1631 c['lock'] = False
eadd85a8 1632 except Exception:
b8c1f42a 1633 printNicely(red('OMG something is wrong with Twitter right now.'))
54277114
O
1634
1635
42fde775 1636def stream(domain, args, name='Rainbow Stream'):
54277114 1637 """
f405a7d0 1638 Track the stream
54277114 1639 """
54277114 1640 # The Logo
42fde775 1641 art_dict = {
632c6fa5
O
1642 c['USER_DOMAIN']: name,
1643 c['PUBLIC_DOMAIN']: args.track_keywords,
1f2f6159 1644 c['SITE_DOMAIN']: name,
42fde775 1645 }
687567eb 1646 if c['ASCII_ART']:
c075e6dc 1647 ascii_art(art_dict[domain])
91476ec3
O
1648 # These arguments are optional:
1649 stream_args = dict(
1650 timeout=args.timeout,
92983945 1651 block=False,
91476ec3 1652 heartbeat_timeout=args.heartbeat_timeout)
91476ec3
O
1653 # Track keyword
1654 query_args = dict()
1655 if args.track_keywords:
1656 query_args['track'] = args.track_keywords
91476ec3 1657 # Get stream
2a6238f5 1658 stream = TwitterStream(
22be990e 1659 auth=authen(),
42fde775 1660 domain=domain,
2a6238f5 1661 **stream_args)
2a0cabee
O
1662 try:
1663 if domain == c['USER_DOMAIN']:
1664 tweet_iter = stream.user(**query_args)
1665 elif domain == c['SITE_DOMAIN']:
1666 tweet_iter = stream.site(**query_args)
42fde775 1667 else:
2a0cabee
O
1668 if args.track_keywords:
1669 tweet_iter = stream.statuses.filter(**query_args)
1670 else:
1671 tweet_iter = stream.statuses.sample()
92983945
BS
1672 # Block new stream until other one exits
1673 StreamLock.acquire()
1674 g['stream_stop'] = False
72c02928 1675 for tweet in tweet_iter:
99b52f5f 1676 if(g['stream_stop']):
92983945
BS
1677 StreamLock.release()
1678 break
72c02928 1679 if tweet is None:
92983945 1680 pass
72c02928
VNM
1681 elif tweet is Timeout:
1682 printNicely("-- Timeout --")
1683 elif tweet is HeartbeatTimeout:
1684 printNicely("-- Heartbeat Timeout --")
1685 elif tweet is Hangup:
1686 printNicely("-- Hangup --")
1687 elif tweet.get('text'):
1688 draw(
1689 t=tweet,
72c02928 1690 keyword=args.track_keywords,
9683e61d 1691 check_semaphore=True,
72c02928
VNM
1692 fil=args.filter,
1693 ig=args.ignore,
1694 )
14db58c7 1695 elif tweet.get('direct_message'):
8141aca6 1696 print_message(tweet['direct_message'], check_semaphore=True)
2a0cabee
O
1697 except TwitterHTTPError:
1698 printNicely('')
c075e6dc 1699 printNicely(
2a0cabee 1700 magenta("We have maximum connection problem with twitter'stream API right now :("))
54277114
O
1701
1702
1703def fly():
1704 """
1705 Main function
1706 """
531f5682 1707 # Initial
42fde775 1708 args = parse_arguments()
2a0cabee 1709 try:
fe9bb33b 1710 init(args)
2a0cabee
O
1711 except TwitterHTTPError:
1712 printNicely('')
1713 printNicely(
4c025026 1714 magenta("We have maximum connection problem with twitter'stream API right now :("))
1715 printNicely(magenta("Let's try again later."))
2a0cabee 1716 save_history()
2a0cabee 1717 sys.exit()
92983945
BS
1718 # Spawn stream thread
1719 th = threading.Thread(target=stream, args=(c['USER_DOMAIN'], args, g['original_name']))
1720 th.daemon = True
1721 th.start()
42fde775 1722 # Start listen process
819569e8 1723 time.sleep(0.5)
c91f75f2 1724 g['reset'] = True
1dd312f5 1725 g['prefix'] = True
0f6e4daf 1726 listen()