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