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