Improvements to nicks handling in 'repall' command:
[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
JT
533 nick_ary = [original_tweet['user']['screen_name']]
534 for user in tweet['entities']['user_mentions']:
535 if user['screen_name'] not in nick_ary:
536 nick_ary.append(user['screen_name'])
537 if g['original_name'] in nick_ary:
538 nick_ary.remove(g['original_name'])
ba6c09d1 539 status = ' '.join(g['stuff'].split()[1:])
247c4e80 540 status = ' '.join(['@' + nick for nick in nick_ary]) + ' ' + str2u(status)
ba6c09d1
O
541 t.statuses.update(status=status, in_reply_to_status_id=tid)
542
543
fd87ddac 544def favorite():
7b674cef 545 """
fd87ddac 546 Favorite
7b674cef 547 """
548 t = Twitter(auth=authen())
549 try:
99b52f5f 550 id = int(g['stuff'].split()[0])
7b674cef 551 except:
305ce127 552 printNicely(red('Sorry I can\'t understand.'))
b8c1f42a 553 return
99b52f5f 554 tid = c['tweet_dict'][id]
fd87ddac
O
555 t.favorites.create(_id=tid, include_entities=False)
556 printNicely(green('Favorited.'))
557 draw(t.statuses.show(id=tid))
558 printNicely('')
829cc2d8
O
559
560
7e4ccbf3 561def unfavorite():
562 """
563 Unfavorite
564 """
565 t = Twitter(auth=authen())
566 try:
567 id = int(g['stuff'].split()[0])
7e4ccbf3 568 except:
b8c1f42a
O
569 printNicely(red('Sorry I can\'t understand.'))
570 return
99b52f5f 571 tid = c['tweet_dict'][id]
b8c1f42a
O
572 t.favorites.destroy(_id=tid)
573 printNicely(green('Okay it\'s unfavorited.'))
fe9bb33b 574 draw(t.statuses.show(id=tid))
b8c1f42a 575 printNicely('')
7e4ccbf3 576
577
413857b5
O
578def share():
579 """
580 Copy url of a tweet to clipboard
581 """
582 t = Twitter(auth=authen())
583 try:
584 id = int(g['stuff'].split()[0])
66fe9f75 585 tid = c['tweet_dict'][id]
413857b5 586 except:
66fe9f75 587 printNicely(red('Tweet id is not valid.'))
413857b5 588 return
413857b5
O
589 tweet = t.statuses.show(id=tid)
590 url = 'https://twitter.com/' + \
591 tweet['user']['screen_name'] + '/status/' + str(tid)
eb9b6273 592 import platform
593 if platform.system().lower() == 'darwin':
594 os.system("echo '%s' | pbcopy" % url)
595 printNicely(green('Copied tweet\'s url to clipboard.'))
596 else:
597 printNicely('Direct link: ' + yellow(url))
413857b5
O
598
599
fd87ddac 600def delete():
305ce127 601 """
fd87ddac 602 Delete
305ce127 603 """
604 t = Twitter(auth=authen())
fd87ddac
O
605 try:
606 id = int(g['stuff'].split()[0])
607 except:
608 printNicely(red('Sorry I can\'t understand.'))
609 return
610 tid = c['tweet_dict'][id]
611 t.statuses.destroy(id=tid)
612 printNicely(green('Okay it\'s gone.'))
305ce127 613
614
f5677fb1 615def show():
843647ad 616 """
f5677fb1 617 Show image
843647ad
O
618 """
619 t = Twitter(auth=authen())
f5677fb1
O
620 try:
621 target = g['stuff'].split()[0]
622 if target != 'image':
623 return
624 id = int(g['stuff'].split()[1])
99b52f5f 625 tid = c['tweet_dict'][id]
f5677fb1
O
626 tweet = t.statuses.show(id=tid)
627 media = tweet['entities']['media']
628 for m in media:
629 res = requests.get(m['media_url'])
b3164e62 630 img = Image.open(BytesIO(res.content))
f5677fb1
O
631 img.show()
632 except:
7a8a52fc 633 debug_option()
f5677fb1 634 printNicely(red('Sorry I can\'t show this image.'))
843647ad
O
635
636
80bb2040 637def urlopen():
80b70d60
O
638 """
639 Open url
640 """
641 t = Twitter(auth=authen())
642 try:
643 if not g['stuff'].isdigit():
644 return
8101275e 645 tid = c['tweet_dict'][int(g['stuff'])]
80b70d60 646 tweet = t.statuses.show(id=tid)
571ea706
O
647 link_prefix = ('http://', 'https://')
648 link_ary = [u for u in tweet['text'].split()
649 if u.startswith(link_prefix)]
80b70d60
O
650 if not link_ary:
651 printNicely(light_magenta('No url here @.@!'))
652 return
653 for link in link_ary:
654 webbrowser.open(link)
655 except:
7a8a52fc 656 debug_option()
80b70d60
O
657 printNicely(red('Sorry I can\'t open url in this tweet.'))
658
659
305ce127 660def inbox():
661 """
67c663f8 662 Inbox threads
305ce127 663 """
664 t = Twitter(auth=authen())
632c6fa5 665 num = c['MESSAGES_DISPLAY']
305ce127 666 if g['stuff'].isdigit():
667 num = g['stuff']
67c663f8 668 # Get inbox messages
305ce127 669 cur_page = 1
67c663f8 670 inbox = []
305ce127 671 while num > 20:
67c663f8 672 inbox = inbox + t.direct_messages(
305ce127 673 count=20,
674 page=cur_page,
675 include_entities=False,
676 skip_status=False
48a25fe8 677 )
305ce127 678 num -= 20
679 cur_page += 1
67c663f8 680 inbox = inbox + t.direct_messages(
305ce127 681 count=num,
682 page=cur_page,
683 include_entities=False,
684 skip_status=False
48a25fe8 685 )
67c663f8 686 # Get sent messages
632c6fa5 687 num = c['MESSAGES_DISPLAY']
305ce127 688 if g['stuff'].isdigit():
67c663f8 689 num = g['stuff']
305ce127 690 cur_page = 1
67c663f8 691 sent = []
305ce127 692 while num > 20:
67c663f8 693 sent = sent + t.direct_messages.sent(
305ce127 694 count=20,
695 page=cur_page,
696 include_entities=False,
697 skip_status=False
48a25fe8 698 )
305ce127 699 num -= 20
700 cur_page += 1
67c663f8 701 sent = sent + t.direct_messages.sent(
305ce127 702 count=num,
703 page=cur_page,
704 include_entities=False,
705 skip_status=False
48a25fe8 706 )
67c663f8
O
707
708 d = {}
709 uniq_inbox = list(set(
03c0d30b 710 [(m['sender_screen_name'], m['sender']['name']) for m in inbox]
67c663f8 711 ))
03c0d30b 712 uniq_sent = list(set(
713 [(m['recipient_screen_name'], m['recipient']['name']) for m in sent]
67c663f8
O
714 ))
715 for partner in uniq_inbox:
716 inbox_ary = [m for m in inbox if m['sender_screen_name'] == partner[0]]
03c0d30b 717 sent_ary = [
718 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
719 d[partner] = inbox_ary + sent_ary
720 for partner in uniq_sent:
721 if partner not in d:
03c0d30b 722 d[partner] = [
723 m for m in sent if m['recipient_screen_name'] == partner[0]]
67c663f8
O
724 g['message_threads'] = print_threads(d)
725
726
727def thread():
728 """
729 View a thread of message
730 """
731 try:
732 thread_id = int(g['stuff'])
03c0d30b 733 print_thread(
734 g['message_threads'][thread_id],
735 g['original_name'],
736 g['full_name'])
737 except Exception:
7a8a52fc 738 debug_option()
67c663f8 739 printNicely(red('No such thread.'))
e2b81717 740
305ce127 741
fd87ddac
O
742def message():
743 """
744 Send a direct message
745 """
746 t = Twitter(auth=authen())
03c0d30b 747 try:
748 user = g['stuff'].split()[0]
749 if user[0].startswith('@'):
750 content = ' '.join(g['stuff'].split()[1:])
751 t.direct_messages.new(
752 screen_name=user[1:],
753 text=content
754 )
755 printNicely(green('Message sent.'))
756 else:
757 printNicely(red('A name should begin with a \'@\''))
758 except:
7a8a52fc 759 debug_option()
03c0d30b 760 printNicely(red('Sorry I can\'t understand.'))
fd87ddac
O
761
762
305ce127 763def trash():
764 """
765 Remove message
766 """
767 t = Twitter(auth=authen())
768 try:
99b52f5f 769 id = int(g['stuff'].split()[0])
305ce127 770 except:
771 printNicely(red('Sorry I can\'t understand.'))
99b52f5f 772 mid = c['message_dict'][id]
b8c1f42a
O
773 t.direct_messages.destroy(id=mid)
774 printNicely(green('Message deleted.'))
305ce127 775
776
fd87ddac 777def ls():
e2b81717 778 """
fd87ddac 779 List friends for followers
e2b81717
O
780 """
781 t = Twitter(auth=authen())
fd87ddac
O
782 # Get name
783 try:
784 name = g['stuff'].split()[1]
785 if name.startswith('@'):
786 name = name[1:]
787 else:
788 printNicely(red('A name should begin with a \'@\''))
789 raise Exception('Invalid name')
790 except:
791 name = g['original_name']
792 # Get list followers or friends
793 try:
794 target = g['stuff'].split()[0]
795 except:
796 printNicely(red('Omg some syntax is wrong.'))
04610460 797 return
fd87ddac
O
798 # Init cursor
799 d = {'fl': 'followers', 'fr': 'friends'}
800 next_cursor = -1
801 rel = {}
802 # Cursor loop
803 while next_cursor != 0:
804 list = getattr(t, d[target]).list(
805 screen_name=name,
806 cursor=next_cursor,
807 skip_status=True,
808 include_entities=False,
809 )
810 for u in list['users']:
811 rel[u['name']] = '@' + u['screen_name']
812 next_cursor = list['next_cursor']
813 # Print out result
814 printNicely('All: ' + str(len(rel)) + ' ' + d[target] + '.')
815 for name in rel:
816 user = ' ' + cycle_color(name)
817 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
818 printNicely(user)
e2b81717
O
819
820
f5677fb1 821def follow():
843647ad 822 """
f5677fb1 823 Follow a user
843647ad
O
824 """
825 t = Twitter(auth=authen())
f5677fb1 826 screen_name = g['stuff'].split()[0]
b8c1f42a
O
827 if screen_name.startswith('@'):
828 t.friendships.create(screen_name=screen_name[1:], follow=True)
829 printNicely(green('You are following ' + screen_name + ' now!'))
f5677fb1 830 else:
b8c1f42a 831 printNicely(red('A name should begin with a \'@\''))
f5677fb1
O
832
833
834def unfollow():
835 """
836 Unfollow a user
837 """
838 t = Twitter(auth=authen())
839 screen_name = g['stuff'].split()[0]
b8c1f42a
O
840 if screen_name.startswith('@'):
841 t.friendships.destroy(
842 screen_name=screen_name[1:],
843 include_entities=False)
844 printNicely(green('Unfollow ' + screen_name + ' success!'))
f5677fb1 845 else:
b8c1f42a 846 printNicely(red('A name should begin with a \'@\''))
843647ad
O
847
848
5b2c4faf 849def mute():
850 """
851 Mute a user
852 """
853 t = Twitter(auth=authen())
854 try:
855 screen_name = g['stuff'].split()[0]
856 except:
857 printNicely(red('A name should be specified. '))
858 return
859 if screen_name.startswith('@'):
e3927852
O
860 try:
861 rel = t.mutes.users.create(screen_name=screen_name[1:])
862 if isinstance(rel, dict):
863 printNicely(green(screen_name + ' is muted.'))
612d6863 864 c['IGNORE_LIST'] += [unc(screen_name)]
e3927852
O
865 c['IGNORE_LIST'] = list(set(c['IGNORE_LIST']))
866 else:
867 printNicely(red(rel))
868 except:
7a8a52fc 869 debug_option()
e3927852 870 printNicely(red('Something is wrong, can not mute now :('))
5b2c4faf 871 else:
872 printNicely(red('A name should begin with a \'@\''))
873
874
875def unmute():
876 """
877 Unmute a user
878 """
879 t = Twitter(auth=authen())
880 try:
881 screen_name = g['stuff'].split()[0]
882 except:
883 printNicely(red('A name should be specified. '))
884 return
885 if screen_name.startswith('@'):
e3927852
O
886 try:
887 rel = t.mutes.users.destroy(screen_name=screen_name[1:])
888 if isinstance(rel, dict):
889 printNicely(green(screen_name + ' is unmuted.'))
890 c['IGNORE_LIST'].remove(screen_name)
891 else:
892 printNicely(red(rel))
893 except:
894 printNicely(red('Maybe you are not muting this person ?'))
5b2c4faf 895 else:
896 printNicely(red('A name should begin with a \'@\''))
897
898
899def muting():
900 """
901 List muting user
902 """
e3927852
O
903 # Get dict of muting users
904 md = build_mute_dict(dict_data=True)
905 printNicely('All: ' + str(len(md)) + ' people.')
906 for name in md:
907 user = ' ' + cycle_color(md[name])
908 user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
5b2c4faf 909 printNicely(user)
e3927852
O
910 # Update from Twitter
911 c['IGNORE_LIST'] = [n for n in md]
5b2c4faf 912
913
305ce127 914def block():
915 """
916 Block a user
917 """
918 t = Twitter(auth=authen())
919 screen_name = g['stuff'].split()[0]
b8c1f42a
O
920 if screen_name.startswith('@'):
921 t.blocks.create(
5b2c4faf 922 screen_name=screen_name[1:],
923 include_entities=False,
924 skip_status=True)
b8c1f42a 925 printNicely(green('You blocked ' + screen_name + '.'))
305ce127 926 else:
b8c1f42a 927 printNicely(red('A name should begin with a \'@\''))
305ce127 928
929
930def unblock():
931 """
932 Unblock a user
933 """
934 t = Twitter(auth=authen())
935 screen_name = g['stuff'].split()[0]
b8c1f42a
O
936 if screen_name.startswith('@'):
937 t.blocks.destroy(
938 screen_name=screen_name[1:],
939 include_entities=False,
940 skip_status=True)
941 printNicely(green('Unblock ' + screen_name + ' success!'))
305ce127 942 else:
b8c1f42a 943 printNicely(red('A name should begin with a \'@\''))
305ce127 944
945
946def report():
947 """
948 Report a user as a spam account
949 """
950 t = Twitter(auth=authen())
951 screen_name = g['stuff'].split()[0]
b8c1f42a
O
952 if screen_name.startswith('@'):
953 t.users.report_spam(
954 screen_name=screen_name[1:])
955 printNicely(green('You reported ' + screen_name + '.'))
305ce127 956 else:
957 printNicely(red('Sorry I can\'t understand.'))
958
959
8b8566d1
O
960def get_slug():
961 """
ee4c94b1 962 Get slug
8b8566d1 963 """
a8c5fce4 964 # Get list name
be4dba0e 965 list_name = raw_input(
966 light_magenta('Give me the list\'s name ("@owner/list_name"): ', rl=True))
8b8566d1
O
967 # Get list name and owner
968 try:
969 owner, slug = list_name.split('/')
970 if slug.startswith('@'):
971 slug = slug[1:]
972 return owner, slug
973 except:
a8c5fce4
O
974 printNicely(
975 light_magenta('List name should follow "@owner/list_name" format.'))
8b8566d1
O
976 raise Exception('Wrong list name')
977
56702c8f 978
434c2160 979def check_slug(list_name):
980 """
981 Check slug
982 """
983 # Get list name and owner
984 try:
985 owner, slug = list_name.split('/')
986 if slug.startswith('@'):
987 slug = slug[1:]
988 return owner, slug
989 except:
990 printNicely(
991 light_magenta('List name should follow "@owner/list_name" format.'))
992 raise Exception('Wrong list name')
8b8566d1 993
56702c8f 994
2d341029
O
995def show_lists(t):
996 """
422dd385 997 List list
2d341029
O
998 """
999 rel = t.lists.list(screen_name=g['original_name'])
1000 if rel:
1001 print_list(rel)
1002 else:
1003 printNicely(light_magenta('You belong to no lists :)'))
1004
1005
1006def list_home(t):
1007 """
1008 List home
1009 """
8b8566d1 1010 owner, slug = get_slug()
2d341029 1011 res = t.lists.statuses(
422dd385
O
1012 slug=slug,
1013 owner_screen_name=owner,
1014 count=c['LIST_MAX'],
2d341029 1015 include_entities=False)
7304256c 1016 for tweet in reversed(res):
2d341029
O
1017 draw(t=tweet)
1018 printNicely('')
1019
1020
1021def list_members(t):
1022 """
1023 List members
1024 """
8b8566d1 1025 owner, slug = get_slug()
422dd385 1026 # Get members
2d341029
O
1027 rel = {}
1028 next_cursor = -1
422dd385 1029 while next_cursor != 0:
2d341029 1030 m = t.lists.members(
422dd385
O
1031 slug=slug,
1032 owner_screen_name=owner,
1033 cursor=next_cursor,
2d341029
O
1034 include_entities=False)
1035 for u in m['users']:
1036 rel[u['name']] = '@' + u['screen_name']
1037 next_cursor = m['next_cursor']
1038 printNicely('All: ' + str(len(rel)) + ' members.')
1039 for name in rel:
1040 user = ' ' + cycle_color(name)
422dd385 1041 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
1042 printNicely(user)
1043
1044
1045def list_subscribers(t):
1046 """
1047 List subscribers
1048 """
8b8566d1 1049 owner, slug = get_slug()
422dd385 1050 # Get subscribers
2d341029
O
1051 rel = {}
1052 next_cursor = -1
422dd385 1053 while next_cursor != 0:
2d341029 1054 m = t.lists.subscribers(
422dd385
O
1055 slug=slug,
1056 owner_screen_name=owner,
1057 cursor=next_cursor,
2d341029
O
1058 include_entities=False)
1059 for u in m['users']:
1060 rel[u['name']] = '@' + u['screen_name']
1061 next_cursor = m['next_cursor']
1062 printNicely('All: ' + str(len(rel)) + ' subscribers.')
1063 for name in rel:
1064 user = ' ' + cycle_color(name)
422dd385 1065 user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
2d341029
O
1066 printNicely(user)
1067
1068
422dd385
O
1069def list_add(t):
1070 """
1071 Add specific user to a list
1072 """
8b8566d1 1073 owner, slug = get_slug()
422dd385 1074 # Add
be4dba0e 1075 user_name = raw_input(
1076 light_magenta(
1077 'Give me name of the newbie: ',
1078 rl=True))
422dd385
O
1079 if user_name.startswith('@'):
1080 user_name = user_name[1:]
1081 try:
1082 t.lists.members.create(
1083 slug=slug,
1084 owner_screen_name=owner,
1085 screen_name=user_name)
d6cc4c67 1086 printNicely(green('Added.'))
422dd385 1087 except:
7a8a52fc 1088 debug_option()
422dd385
O
1089 printNicely(light_magenta('I\'m sorry we can not add him/her.'))
1090
1091
2d341029
O
1092def list_remove(t):
1093 """
1094 Remove specific user from a list
1095 """
8b8566d1 1096 owner, slug = get_slug()
2d341029 1097 # Remove
be4dba0e 1098 user_name = raw_input(
1099 light_magenta(
1100 'Give me name of the unlucky one: ',
1101 rl=True))
422dd385
O
1102 if user_name.startswith('@'):
1103 user_name = user_name[1:]
2d341029
O
1104 try:
1105 t.lists.members.destroy(
422dd385
O
1106 slug=slug,
1107 owner_screen_name=owner,
1108 screen_name=user_name)
d6cc4c67 1109 printNicely(green('Gone.'))
422dd385 1110 except:
7a8a52fc 1111 debug_option()
422dd385
O
1112 printNicely(light_magenta('I\'m sorry we can not remove him/her.'))
1113
1114
1115def list_subscribe(t):
1116 """
1117 Subscribe to a list
1118 """
8b8566d1 1119 owner, slug = get_slug()
422dd385
O
1120 # Subscribe
1121 try:
1122 t.lists.subscribers.create(
1123 slug=slug,
1124 owner_screen_name=owner)
d6cc4c67 1125 printNicely(green('Done.'))
422dd385 1126 except:
7a8a52fc 1127 debug_option()
422dd385
O
1128 printNicely(
1129 light_magenta('I\'m sorry you can not subscribe to this list.'))
1130
1131
1132def list_unsubscribe(t):
1133 """
1134 Unsubscribe a list
1135 """
8b8566d1 1136 owner, slug = get_slug()
422dd385
O
1137 # Subscribe
1138 try:
1139 t.lists.subscribers.destroy(
1140 slug=slug,
1141 owner_screen_name=owner)
d6cc4c67 1142 printNicely(green('Done.'))
422dd385 1143 except:
7a8a52fc 1144 debug_option()
422dd385
O
1145 printNicely(
1146 light_magenta('I\'m sorry you can not unsubscribe to this list.'))
1147
1148
1149def list_own(t):
1150 """
1151 List own
1152 """
1153 rel = []
1154 next_cursor = -1
1155 while next_cursor != 0:
1156 res = t.lists.ownerships(
1157 screen_name=g['original_name'],
1158 cursor=next_cursor)
1159 rel += res['lists']
1160 next_cursor = res['next_cursor']
1161 if rel:
1162 print_list(rel)
1163 else:
1164 printNicely(light_magenta('You own no lists :)'))
1165
1166
1167def list_new(t):
1168 """
1169 Create a new list
1170 """
be4dba0e 1171 name = raw_input(light_magenta('New list\'s name: ', rl=True))
1172 mode = raw_input(
1173 light_magenta(
1174 'New list\'s mode (public/private): ',
1175 rl=True))
1176 description = raw_input(
1177 light_magenta(
1178 'New list\'s description: ',
1179 rl=True))
422dd385
O
1180 try:
1181 t.lists.create(
1182 name=name,
1183 mode=mode,
1184 description=description)
d6cc4c67 1185 printNicely(green(name + ' list is created.'))
422dd385 1186 except:
7a8a52fc 1187 debug_option()
422dd385
O
1188 printNicely(red('Oops something is wrong with Twitter :('))
1189
1190
1191def list_update(t):
1192 """
1193 Update a list
1194 """
be4dba0e 1195 slug = raw_input(
1196 light_magenta(
1197 'Your list that you want to update: ',
1198 rl=True))
1199 name = raw_input(
1200 light_magenta(
1201 'Update name (leave blank to unchange): ',
1202 rl=True))
1203 mode = raw_input(light_magenta('Update mode (public/private): ', rl=True))
1204 description = raw_input(light_magenta('Update description: ', rl=True))
422dd385
O
1205 try:
1206 if name:
1207 t.lists.update(
1208 slug='-'.join(slug.split()),
1209 owner_screen_name=g['original_name'],
1210 name=name,
1211 mode=mode,
1212 description=description)
1213 else:
1214 t.lists.update(
1215 slug=slug,
1216 owner_screen_name=g['original_name'],
1217 mode=mode,
1218 description=description)
d6cc4c67 1219 printNicely(green(slug + ' list is updated.'))
3c85d8fc 1220 except:
7a8a52fc 1221 debug_option()
422dd385
O
1222 printNicely(red('Oops something is wrong with Twitter :('))
1223
1224
1225def list_delete(t):
1226 """
1227 Delete a list
1228 """
be4dba0e 1229 slug = raw_input(
1230 light_magenta(
1231 'Your list that you want to delete: ',
1232 rl=True))
422dd385
O
1233 try:
1234 t.lists.destroy(
1235 slug='-'.join(slug.split()),
1236 owner_screen_name=g['original_name'])
d6cc4c67 1237 printNicely(green(slug + ' list is deleted.'))
2d341029 1238 except:
7a8a52fc 1239 debug_option()
422dd385 1240 printNicely(red('Oops something is wrong with Twitter :('))
2d341029
O
1241
1242
e3927852 1243def twitterlist():
2d341029
O
1244 """
1245 Twitter's list
1246 """
1247 t = Twitter(auth=authen())
1248 # List all lists or base on action
1249 try:
1250 g['list_action'] = g['stuff'].split()[0]
1251 except:
1252 show_lists(t)
1253 return
422dd385 1254 # Sub-function
2d341029
O
1255 action_ary = {
1256 'home': list_home,
1257 'all_mem': list_members,
1258 'all_sub': list_subscribers,
422dd385 1259 'add': list_add,
2d341029 1260 'rm': list_remove,
422dd385
O
1261 'sub': list_subscribe,
1262 'unsub': list_unsubscribe,
1263 'own': list_own,
1264 'new': list_new,
1265 'update': list_update,
1266 'del': list_delete,
2d341029
O
1267 }
1268 try:
1269 return action_ary[g['list_action']](t)
3c85d8fc 1270 except:
8b8566d1 1271 printNicely(red('Please try again.'))
2d341029
O
1272
1273
fd87ddac
O
1274def switch():
1275 """
1276 Switch stream
1277 """
1278 try:
1279 target = g['stuff'].split()[0]
1280 # Filter and ignore
1281 args = parse_arguments()
1282 try:
1283 if g['stuff'].split()[-1] == '-f':
1284 guide = 'To ignore an option, just hit Enter key.'
1285 printNicely(light_magenta(guide))
1286 only = raw_input('Only nicks [Ex: @xxx,@yy]: ')
1287 ignore = raw_input('Ignore nicks [Ex: @xxx,@yy]: ')
1288 args.filter = filter(None, only.split(','))
1289 args.ignore = filter(None, ignore.split(','))
fd87ddac
O
1290 except:
1291 printNicely(red('Sorry, wrong format.'))
1292 return
56702c8f 1293 # Kill old thread
1294 g['stream_stop'] = True
1295 try:
1296 stuff = g['stuff'].split()[1]
1297 except:
1298 stuff = None
1299 # Spawn new thread
1300 spawn_dict = {
1301 'public': spawn_public_stream,
1302 'list': spawn_list_stream,
1303 'mine': spawn_personal_stream,
1304 }
1305 spawn_dict.get(target)(args, stuff)
050a294e 1306 except:
ee4c94b1 1307 debug_option()
fd87ddac
O
1308 printNicely(red('Sorry I can\'t understand.'))
1309
1310
813a5d80 1311def cal():
1312 """
1313 Unix's command `cal`
1314 """
1315 # Format
1316 rel = os.popen('cal').read().split('\n')
1317 month = rel.pop(0)
813a5d80 1318 date = rel.pop(0)
2a0cabee 1319 show_calendar(month, date, rel)
813a5d80 1320
1321
fd87ddac
O
1322def theme():
1323 """
1324 List and change theme
1325 """
1326 if not g['stuff']:
1327 # List themes
1328 for theme in g['themes']:
1329 line = light_magenta(theme)
1330 if c['THEME'] == theme:
1331 line = ' ' * 2 + light_yellow('* ') + line
1332 else:
1333 line = ' ' * 4 + line
1334 printNicely(line)
1335 else:
1336 # Change theme
1337 try:
1338 # Load new theme
1339 c['THEME'] = reload_theme(g['stuff'], c['THEME'])
1340 # Redefine decorated_name
1341 g['decorated_name'] = lambda x: color_func(
1342 c['DECORATED_NAME'])(
1343 '[' + x + ']: ')
1344 printNicely(green('Theme changed.'))
1345 except:
1346 printNicely(red('No such theme exists.'))
1347
1348
29fd0be6
O
1349def config():
1350 """
1351 Browse and change config
1352 """
1353 all_config = get_all_config()
1354 g['stuff'] = g['stuff'].strip()
1355 # List all config
1356 if not g['stuff']:
1357 for k in all_config:
a8c5fce4 1358 line = ' ' * 2 + \
d6cc4c67 1359 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1360 printNicely(line)
1361 guide = 'Detailed explanation can be found at ' + \
a8c5fce4
O
1362 color_func(c['TWEET']['link'])(
1363 'http://rainbowstream.readthedocs.org/en/latest/#config-explanation')
29fd0be6
O
1364 printNicely(guide)
1365 # Print specific config
1366 elif len(g['stuff'].split()) == 1:
1367 if g['stuff'] in all_config:
1368 k = g['stuff']
a8c5fce4 1369 line = ' ' * 2 + \
d6cc4c67 1370 green(k) + ': ' + light_yellow(str(all_config[k]))
29fd0be6
O
1371 printNicely(line)
1372 else:
fe9bb33b 1373 printNicely(red('No such config key.'))
29fd0be6
O
1374 # Print specific config's default value
1375 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'default':
1376 key = g['stuff'].split()[0]
fe9bb33b 1377 try:
1378 value = get_default_config(key)
d6cc4c67 1379 line = ' ' * 2 + green(key) + ': ' + light_magenta(value)
fe9bb33b 1380 printNicely(line)
050a294e
O
1381 except:
1382 debug_option()
1383 printNicely(red('Just can not get the default.'))
fe9bb33b 1384 # Delete specific config key in config file
1385 elif len(g['stuff'].split()) == 2 and g['stuff'].split()[-1] == 'drop':
1386 key = g['stuff'].split()[0]
1387 try:
1388 delete_config(key)
d6cc4c67 1389 printNicely(green('Config key is dropped.'))
050a294e
O
1390 except:
1391 debug_option()
1392 printNicely(red('Just can not drop the key.'))
29fd0be6 1393 # Set specific config
a8c5fce4 1394 elif len(g['stuff'].split()) == 3 and g['stuff'].split()[1] == '=':
29fd0be6
O
1395 key = g['stuff'].split()[0]
1396 value = g['stuff'].split()[-1]
ceec8593 1397 if key == 'THEME' and not validate_theme(value):
1398 printNicely(red('Invalid theme\'s value.'))
1399 return
3c01ba57 1400 try:
a8c5fce4 1401 set_config(key, value)
050a294e 1402 # Keys that needs to be apply immediately
ceec8593 1403 if key == 'THEME':
baec5f50 1404 c['THEME'] = reload_theme(value, c['THEME'])
ceec8593 1405 g['decorated_name'] = lambda x: color_func(
a8e71259 1406 c['DECORATED_NAME'])('[' + x + ']: ')
050a294e 1407 elif key == 'PREFIX':
063f6bb1 1408 g['PREFIX'] = u2str(emojize(format_prefix(
1409 listname=g['listname'],
1410 keyword=g['keyword']
1411 )))
a8e71259 1412 reload_config()
d6cc4c67 1413 printNicely(green('Updated successfully.'))
050a294e
O
1414 except:
1415 debug_option()
1416 printNicely(red('Just can not set the key.'))
29fd0be6
O
1417 else:
1418 printNicely(light_magenta('Sorry I can\'s understand.'))
1419
1420
2d341029 1421def help_discover():
f405a7d0 1422 """
2d341029 1423 Discover the world
f405a7d0 1424 """
7e4ccbf3 1425 s = ' ' * 2
1f24a05a 1426 # Discover the world
2d341029 1427 usage = '\n'
8bc30efd 1428 usage += s + grey(u'\u266A' + ' Discover the world \n')
c075e6dc
O
1429 usage += s * 2 + light_green('trend') + ' will show global trending topics. ' + \
1430 'You can try ' + light_green('trend US') + ' or ' + \
1431 light_green('trend JP Tokyo') + '.\n'
1432 usage += s * 2 + light_green('home') + ' will show your timeline. ' + \
1433 light_green('home 7') + ' will show 7 tweets.\n'
99cd1fba
O
1434 usage += s * 2 + \
1435 light_green('notification') + ' will show your recent notification.\n'
c075e6dc
O
1436 usage += s * 2 + light_green('mentions') + ' will show mentions timeline. ' + \
1437 light_green('mentions 7') + ' will show 7 mention tweets.\n'
1438 usage += s * 2 + light_green('whois @mdo') + ' will show profile of ' + \
8bc30efd 1439 magenta('@mdo') + '.\n'
c075e6dc 1440 usage += s * 2 + light_green('view @mdo') + \
8bc30efd 1441 ' will show ' + magenta('@mdo') + '\'s home.\n'
03e08f86
O
1442 usage += s * 2 + light_green('s AKB48') + ' will search for "' + \
1443 light_yellow('AKB48') + '" and return 5 newest tweet. ' + \
1444 'Search can be performed with or without hashtag.\n'
2d341029
O
1445 printNicely(usage)
1446
8bc30efd 1447
2d341029
O
1448def help_tweets():
1449 """
1450 Tweets
1451 """
1452 s = ' ' * 2
1f24a05a 1453 # Tweet
2d341029 1454 usage = '\n'
8bc30efd 1455 usage += s + grey(u'\u266A' + ' Tweets \n')
c075e6dc
O
1456 usage += s * 2 + light_green('t oops ') + \
1457 'will tweet "' + light_yellow('oops') + '" immediately.\n'
7e4ccbf3 1458 usage += s * 2 + \
c075e6dc
O
1459 light_green('rt 12 ') + ' will retweet to tweet with ' + \
1460 light_yellow('[id=12]') + '.\n'
80b70d60
O
1461 usage += s * 2 + \
1462 light_green('quote 12 ') + ' will quote the tweet with ' + \
1463 light_yellow('[id=12]') + '. If no extra text is added, ' + \
1464 'the quote will be canceled.\n'
1f24a05a 1465 usage += s * 2 + \
c075e6dc
O
1466 light_green('allrt 12 20 ') + ' will list 20 newest retweet of the tweet with ' + \
1467 light_yellow('[id=12]') + '.\n'
fd87ddac
O
1468 usage += s * 2 + light_green('conversation 12') + ' will show the chain of ' + \
1469 'replies prior to the tweet with ' + light_yellow('[id=12]') + '.\n'
c075e6dc 1470 usage += s * 2 + light_green('rep 12 oops') + ' will reply "' + \
ba6c09d1
O
1471 light_yellow('oops') + '" to the owner of the tweet with ' + \
1472 light_yellow('[id=12]') + '.\n'
1473 usage += s * 2 + light_green('repall 12 oops') + ' will reply "' + \
1474 light_yellow('oops') + '" to all people in the tweet with ' + \
c075e6dc 1475 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1476 usage += s * 2 + \
c075e6dc
O
1477 light_green('fav 12 ') + ' will favorite the tweet with ' + \
1478 light_yellow('[id=12]') + '.\n'
7e4ccbf3 1479 usage += s * 2 + \
c075e6dc
O
1480 light_green('ufav 12 ') + ' will unfavorite tweet with ' + \
1481 light_yellow('[id=12]') + '.\n'
413857b5 1482 usage += s * 2 + \
66fe9f75 1483 light_green('share 12 ') + ' will get the direct link of the tweet with ' + \
1484 light_yellow('[id=12]') + '.\n'
8bc30efd 1485 usage += s * 2 + \
c075e6dc
O
1486 light_green('del 12 ') + ' will delete tweet with ' + \
1487 light_yellow('[id=12]') + '.\n'
1488 usage += s * 2 + light_green('show image 12') + ' will show image in tweet with ' + \
1489 light_yellow('[id=12]') + ' in your OS\'s image viewer.\n'
80b70d60
O
1490 usage += s * 2 + light_green('open 12') + ' will open url in tweet with ' + \
1491 light_yellow('[id=12]') + ' in your OS\'s default browser.\n'
2d341029 1492 printNicely(usage)
8bc30efd 1493
2d341029
O
1494
1495def help_messages():
1496 """
1497 Messages
1498 """
1499 s = ' ' * 2
5b2c4faf 1500 # Direct message
2d341029 1501 usage = '\n'
8bc30efd 1502 usage += s + grey(u'\u266A' + ' Direct messages \n')
c075e6dc
O
1503 usage += s * 2 + light_green('inbox') + ' will show inbox messages. ' + \
1504 light_green('inbox 7') + ' will show newest 7 messages.\n'
03c0d30b 1505 usage += s * 2 + light_green('thread 2') + ' will show full thread with ' + \
1506 light_yellow('[thread_id=2]') + '.\n'
c075e6dc 1507 usage += s * 2 + light_green('mes @dtvd88 hi') + ' will send a "hi" messege to ' + \
8bc30efd 1508 magenta('@dtvd88') + '.\n'
c075e6dc
O
1509 usage += s * 2 + light_green('trash 5') + ' will remove message with ' + \
1510 light_yellow('[message_id=5]') + '.\n'
2d341029 1511 printNicely(usage)
8bc30efd 1512
2d341029
O
1513
1514def help_friends_and_followers():
1515 """
1516 Friends and Followers
1517 """
1518 s = ' ' * 2
8bc30efd 1519 # Follower and following
2d341029 1520 usage = '\n'
cdccb0d6 1521 usage += s + grey(u'\u266A' + ' Friends and followers \n')
8bc30efd 1522 usage += s * 2 + \
c075e6dc 1523 light_green('ls fl') + \
8bc30efd 1524 ' will list all followers (people who are following you).\n'
1525 usage += s * 2 + \
c075e6dc 1526 light_green('ls fr') + \
8bc30efd 1527 ' will list all friends (people who you are following).\n'
c075e6dc 1528 usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
305ce127 1529 magenta('@dtvd88') + '.\n'
c075e6dc 1530 usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
305ce127 1531 magenta('@dtvd88') + '.\n'
c075e6dc 1532 usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
5b2c4faf 1533 magenta('@dtvd88') + '.\n'
c075e6dc 1534 usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
5b2c4faf 1535 magenta('@dtvd88') + '.\n'
c075e6dc
O
1536 usage += s * 2 + light_green('muting') + ' will list muting users.\n'
1537 usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
305ce127 1538 magenta('@dtvd88') + '.\n'
c075e6dc 1539 usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
305ce127 1540 magenta('@dtvd88') + '.\n'
c075e6dc 1541 usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
305ce127 1542 magenta('@dtvd88') + ' as a spam account.\n'
2d341029
O
1543 printNicely(usage)
1544
1545
1546def help_list():
1547 """
1548 Lists
1549 """
1550 s = ' ' * 2
1551 # Twitter list
1552 usage = '\n'
1553 usage += s + grey(u'\u266A' + ' Twitter list\n')
1554 usage += s * 2 + light_green('list') + \
1555 ' will show all lists you are belong to.\n'
1556 usage += s * 2 + light_green('list home') + \
bef33491 1557 ' will show timeline of list. You will be asked for list\'s name.\n'
a65bd34c 1558 usage += s * 2 + light_green('list all_mem') + \
2d341029 1559 ' will show list\'s all members.\n'
a65bd34c 1560 usage += s * 2 + light_green('list all_sub') + \
2d341029 1561 ' will show list\'s all subscribers.\n'
422dd385
O
1562 usage += s * 2 + light_green('list add') + \
1563 ' will add specific person to a list owned by you.' + \
1564 ' You will be asked for list\'s name and person\'s name.\n'
2d341029
O
1565 usage += s * 2 + light_green('list rm') + \
1566 ' will remove specific person from a list owned by you.' + \
1567 ' You will be asked for list\'s name and person\'s name.\n'
422dd385
O
1568 usage += s * 2 + light_green('list sub') + \
1569 ' will subscribe you to a specific list.\n'
1570 usage += s * 2 + light_green('list unsub') + \
1571 ' will unsubscribe you from a specific list.\n'
1572 usage += s * 2 + light_green('list own') + \
1573 ' will show all list owned by you.\n'
1574 usage += s * 2 + light_green('list new') + \
1575 ' will create a new list.\n'
1576 usage += s * 2 + light_green('list update') + \
1577 ' will update a list owned by you.\n'
1578 usage += s * 2 + light_green('list del') + \
1579 ' will delete a list owned by you.\n'
2d341029 1580 printNicely(usage)
8bc30efd 1581
2d341029
O
1582
1583def help_stream():
1584 """
1585 Stream switch
1586 """
1587 s = ' ' * 2
8bc30efd 1588 # Switch
2d341029 1589 usage = '\n'
8bc30efd 1590 usage += s + grey(u'\u266A' + ' Switching streams \n')
c075e6dc 1591 usage += s * 2 + light_green('switch public #AKB') + \
48a25fe8 1592 ' will switch to public stream and follow "' + \
c075e6dc
O
1593 light_yellow('AKB') + '" keyword.\n'
1594 usage += s * 2 + light_green('switch mine') + \
48a25fe8 1595 ' will switch to your personal stream.\n'
c075e6dc 1596 usage += s * 2 + light_green('switch mine -f ') + \
48a25fe8 1597 ' will prompt to enter the filter.\n'
c075e6dc 1598 usage += s * 3 + light_yellow('Only nicks') + \
48a25fe8 1599 ' filter will decide nicks will be INCLUDE ONLY.\n'
c075e6dc 1600 usage += s * 3 + light_yellow('Ignore nicks') + \
48a25fe8 1601 ' filter will decide nicks will be EXCLUDE.\n'
ee4c94b1
O
1602 usage += s * 2 + light_green('switch list') + \
1603 ' will switch to a Twitter list\'s stream. You will be asked for list name\n'
2d341029
O
1604 printNicely(usage)
1605
1606
1607def help():
1608 """
1609 Help
1610 """
1611 s = ' ' * 2
1612 h, w = os.popen('stty size', 'r').read().split()
2d341029
O
1613 # Start
1614 usage = '\n'
1615 usage += s + 'Hi boss! I\'m ready to serve you right now!\n'
1616 usage += s + '-' * (int(w) - 4) + '\n'
1617 usage += s + 'You are ' + \
1618 light_yellow('already') + ' on your personal stream.\n'
1619 usage += s + 'Any update from Twitter will show up ' + \
1620 light_yellow('immediately') + '.\n'
37d1047f 1621 usage += s + 'In addition, following commands are available right now:\n'
2d341029
O
1622 # Twitter help section
1623 usage += '\n'
1624 usage += s + grey(u'\u266A' + ' Twitter help\n')
1625 usage += s * 2 + light_green('h discover') + \
1626 ' will show help for discover commands.\n'
1627 usage += s * 2 + light_green('h tweets') + \
1628 ' will show help for tweets commands.\n'
1629 usage += s * 2 + light_green('h messages') + \
1630 ' will show help for messages commands.\n'
1631 usage += s * 2 + light_green('h friends_and_followers') + \
1632 ' will show help for friends and followers commands.\n'
1633 usage += s * 2 + light_green('h list') + \
1634 ' will show help for list commands.\n'
1635 usage += s * 2 + light_green('h stream') + \
1636 ' will show help for stream commands.\n'
1f24a05a 1637 # Smart shell
1638 usage += '\n'
1639 usage += s + grey(u'\u266A' + ' Smart shell\n')
c075e6dc 1640 usage += s * 2 + light_green('111111 * 9 / 7') + ' or any math expression ' + \
1f24a05a 1641 'will be evaluate by Python interpreter.\n'
c075e6dc 1642 usage += s * 2 + 'Even ' + light_green('cal') + ' will show the calendar' + \
1f24a05a 1643 ' for current month.\n'
29fd0be6 1644 # Config
1f24a05a 1645 usage += '\n'
29fd0be6
O
1646 usage += s + grey(u'\u266A' + ' Config \n')
1647 usage += s * 2 + light_green('theme') + ' will list available theme. ' + \
c075e6dc 1648 light_green('theme monokai') + ' will apply ' + light_yellow('monokai') + \
632c6fa5 1649 ' theme immediately.\n'
29fd0be6
O
1650 usage += s * 2 + light_green('config') + ' will list all config.\n'
1651 usage += s * 3 + \
1652 light_green('config ASCII_ART') + ' will output current value of ' +\
a8c5fce4 1653 light_yellow('ASCII_ART') + ' config key.\n'
29fd0be6 1654 usage += s * 3 + \
fe9bb33b 1655 light_green('config TREND_MAX default') + ' will output default value of ' + \
1656 light_yellow('TREND_MAX') + ' config key.\n'
1657 usage += s * 3 + \
1658 light_green('config CUSTOM_CONFIG drop') + ' will drop ' + \
1659 light_yellow('CUSTOM_CONFIG') + ' config key.\n'
29fd0be6 1660 usage += s * 3 + \
fe9bb33b 1661 light_green('config IMAGE_ON_TERM = true') + ' will set value of ' + \
1662 light_yellow('IMAGE_ON_TERM') + ' config key to ' + \
1663 light_yellow('True') + '.\n'
29fd0be6
O
1664 # Screening
1665 usage += '\n'
1666 usage += s + grey(u'\u266A' + ' Screening \n')
c075e6dc 1667 usage += s * 2 + light_green('h') + ' will show this help again.\n'
d6cc4c67
O
1668 usage += s * 2 + light_green('p') + ' will pause the stream.\n'
1669 usage += s * 2 + light_green('r') + ' will unpause the stream.\n'
c075e6dc 1670 usage += s * 2 + light_green('c') + ' will clear the screen.\n'
806f42df 1671 usage += s * 2 + light_green('v') + ' will show version info.\n'
c075e6dc 1672 usage += s * 2 + light_green('q') + ' will quit.\n'
8bc30efd 1673 # End
1674 usage += '\n'
7e4ccbf3 1675 usage += s + '-' * (int(w) - 4) + '\n'
8bc30efd 1676 usage += s + 'Have fun and hang tight! \n'
2d341029
O
1677 # Show help
1678 d = {
422dd385
O
1679 'discover': help_discover,
1680 'tweets': help_tweets,
1681 'messages': help_messages,
1682 'friends_and_followers': help_friends_and_followers,
1683 'list': help_list,
1684 'stream': help_stream,
2d341029
O
1685 }
1686 if g['stuff']:
baec5f50 1687 d.get(
1688 g['stuff'].strip(),
1689 lambda: printNicely(red('No such command.'))
3d48702f 1690 )()
2d341029
O
1691 else:
1692 printNicely(usage)
f405a7d0
O
1693
1694
d6cc4c67
O
1695def pause():
1696 """
1697 Pause stream display
1698 """
4dc385b5 1699 g['pause'] = True
d6cc4c67
O
1700 printNicely(green('Stream is paused'))
1701
1702
1703def replay():
1704 """
1705 Replay stream
1706 """
4dc385b5 1707 g['pause'] = False
d6cc4c67
O
1708 printNicely(green('Stream is running back now'))
1709
1710
843647ad 1711def clear():
f405a7d0 1712 """
7b674cef 1713 Clear screen
f405a7d0 1714 """
843647ad 1715 os.system('clear')
f405a7d0
O
1716
1717
843647ad 1718def quit():
b8dda704
O
1719 """
1720 Exit all
1721 """
4c025026 1722 try:
1723 save_history()
4c025026 1724 printNicely(green('See you next time :)'))
1725 except:
1726 pass
843647ad 1727 sys.exit()
b8dda704
O
1728
1729
94a5f62e 1730def reset():
f405a7d0 1731 """
94a5f62e 1732 Reset prefix of line
f405a7d0 1733 """
c91f75f2 1734 if g['reset']:
a8e71259 1735 if c.get('USER_JSON_ERROR'):
1736 printNicely(red('Your ~/.rainbow_config.json is messed up:'))
1737 printNicely(red('>>> ' + c['USER_JSON_ERROR']))
1738 printNicely('')
e3885f55 1739 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
c91f75f2 1740 g['reset'] = False
d0a726d6 1741 try:
779b0640 1742 printNicely(str(eval(g['cmd'])))
2a0cabee 1743 except Exception:
d0a726d6 1744 pass
54277114
O
1745
1746
f1c1dfea
O
1747# Command set
1748cmdset = [
1749 'switch',
1750 'trend',
1751 'home',
99cd1fba 1752 'notification',
f1c1dfea
O
1753 'view',
1754 'mentions',
1755 't',
1756 'rt',
1757 'quote',
1758 'allrt',
fd87ddac 1759 'conversation',
f1c1dfea
O
1760 'fav',
1761 'rep',
ba6c09d1 1762 'repall',
f1c1dfea
O
1763 'del',
1764 'ufav',
413857b5 1765 'share',
f1c1dfea
O
1766 's',
1767 'mes',
1768 'show',
1769 'open',
1770 'ls',
1771 'inbox',
67c663f8 1772 'thread',
f1c1dfea
O
1773 'trash',
1774 'whois',
1775 'fl',
1776 'ufl',
1777 'mute',
1778 'unmute',
1779 'muting',
1780 'block',
1781 'unblock',
1782 'report',
1783 'list',
1784 'cal',
1785 'config',
1786 'theme',
1787 'h',
1788 'p',
1789 'r',
1790 'c',
806f42df 1791 'v',
bf766c7b 1792 'q',
f1c1dfea
O
1793]
1794
1795# Handle function set
1796funcset = [
1797 switch,
1798 trend,
1799 home,
99cd1fba 1800 notification,
f1c1dfea
O
1801 view,
1802 mentions,
1803 tweet,
1804 retweet,
1805 quote,
1806 allretweet,
fd87ddac 1807 conversation,
f1c1dfea
O
1808 favorite,
1809 reply,
ba6c09d1 1810 reply_all,
f1c1dfea
O
1811 delete,
1812 unfavorite,
413857b5 1813 share,
f1c1dfea
O
1814 search,
1815 message,
1816 show,
1817 urlopen,
1818 ls,
1819 inbox,
67c663f8 1820 thread,
f1c1dfea
O
1821 trash,
1822 whois,
1823 follow,
1824 unfollow,
1825 mute,
1826 unmute,
1827 muting,
1828 block,
1829 unblock,
1830 report,
1831 twitterlist,
1832 cal,
1833 config,
1834 theme,
1835 help,
1836 pause,
1837 replay,
1838 clear,
bf766c7b 1839 upgrade_center,
806f42df 1840 quit,
f1c1dfea
O
1841]
1842
1843
94a5f62e 1844def process(cmd):
54277114 1845 """
94a5f62e 1846 Process switch
54277114 1847 """
f1c1dfea 1848 return dict(zip(cmdset, funcset)).get(cmd, reset)
94a5f62e 1849
1850
1851def listen():
42fde775 1852 """
1853 Listen to user's input
1854 """
d51b4107
O
1855 d = dict(zip(
1856 cmdset,
1857 [
ee4c94b1 1858 ['public', 'mine', 'list'], # switch
4592d231 1859 [], # trend
7e4ccbf3 1860 [], # home
99cd1fba 1861 [], # notification
7e4ccbf3 1862 ['@'], # view
305ce127 1863 [], # mentions
7e4ccbf3 1864 [], # tweet
1865 [], # retweet
80b70d60 1866 [], # quote
1f24a05a 1867 [], # allretweet
fd87ddac 1868 [], # conversation
f5677fb1 1869 [], # favorite
7e4ccbf3 1870 [], # reply
ba6c09d1 1871 [], # reply_all
7e4ccbf3 1872 [], # delete
f5677fb1 1873 [], # unfavorite
413857b5 1874 [], # url
7e4ccbf3 1875 ['#'], # search
305ce127 1876 ['@'], # message
f5677fb1 1877 ['image'], # show image
80b70d60 1878 [''], # open url
305ce127 1879 ['fl', 'fr'], # list
1880 [], # inbox
03c0d30b 1881 [i for i in g['message_threads']], # sent
305ce127 1882 [], # trash
e2b81717 1883 ['@'], # whois
affcb149
O
1884 ['@'], # follow
1885 ['@'], # unfollow
5b2c4faf 1886 ['@'], # mute
1887 ['@'], # unmute
1888 ['@'], # muting
305ce127 1889 ['@'], # block
1890 ['@'], # unblock
1891 ['@'], # report
422dd385
O
1892 [
1893 'home',
1894 'all_mem',
1895 'all_sub',
1896 'add',
1897 'rm',
1898 'sub',
1899 'unsub',
1900 'own',
1901 'new',
1902 'update',
1903 'del'
1904 ], # list
813a5d80 1905 [], # cal
a8c5fce4 1906 [key for key in dict(get_all_config())], # config
ceec8593 1907 g['themes'], # theme
422dd385
O
1908 [
1909 'discover',
1910 'tweets',
1911 'messages',
1912 'friends_and_followers',
1913 'list',
1914 'stream'
1915 ], # help
d6cc4c67
O
1916 [], # pause
1917 [], # reconnect
7e4ccbf3 1918 [], # clear
7cfb8af4 1919 [], # version
806f42df 1920 [], # quit
d51b4107 1921 ]
7e4ccbf3 1922 ))
d51b4107 1923 init_interactive_shell(d)
f5677fb1 1924 read_history()
819569e8 1925 reset()
b2b933a9 1926 while True:
b8c1f42a 1927 try:
39b8e6b3
O
1928 # raw_input
1929 if g['prefix']:
aa452ee9 1930 # Only use PREFIX as a string with raw_input
c285decf 1931 line = raw_input(g['decorated_name'](g['PREFIX']))
39b8e6b3
O
1932 else:
1933 line = raw_input()
1934 # Save cmd to compare with readline buffer
1935 g['cmd'] = line.strip()
1936 # Get short cmd to pass to handle function
1937 try:
1938 cmd = line.split()[0]
1939 except:
1940 cmd = ''
9683e61d 1941 # Lock the semaphore
99b52f5f 1942 c['lock'] = True
9683e61d 1943 # Save cmd to global variable and call process
b8c1f42a 1944 g['stuff'] = ' '.join(line.split()[1:])
9683e61d 1945 # Process the command
b8c1f42a 1946 process(cmd)()
9683e61d 1947 # Not re-display
99b52f5f 1948 if cmd in ['switch', 't', 'rt', 'rep']:
9683e61d
O
1949 g['prefix'] = False
1950 else:
1951 g['prefix'] = True
1952 # Release the semaphore lock
99b52f5f 1953 c['lock'] = False
39b8e6b3
O
1954 except EOFError:
1955 printNicely('')
eadd85a8 1956 except Exception:
7a8a52fc 1957 debug_option()
b8c1f42a 1958 printNicely(red('OMG something is wrong with Twitter right now.'))
ee444288 1959
54277114 1960
47cee703
O
1961def reconn_notice():
1962 """
1963 Notice when Hangup or Timeout
1964 """
f07cfb6b 1965 guide = light_magenta('You can use ') + \
1966 light_green('switch') + \
1967 light_magenta(' command to return to your stream.\n')
1968 guide += light_magenta('Type ') + \
1969 light_green('h stream') + \
1970 light_magenta(' for more details.')
47cee703 1971 printNicely(guide)
211e8be1 1972 sys.stdout.write(g['decorated_name'](g['PREFIX']))
47cee703
O
1973 sys.stdout.flush()
1974
1975
42fde775 1976def stream(domain, args, name='Rainbow Stream'):
54277114 1977 """
f405a7d0 1978 Track the stream
54277114 1979 """
54277114 1980 # The Logo
42fde775 1981 art_dict = {
632c6fa5 1982 c['USER_DOMAIN']: name,
3e06aa8f 1983 c['PUBLIC_DOMAIN']: args.track_keywords or 'Global',
1f2f6159 1984 c['SITE_DOMAIN']: name,
42fde775 1985 }
687567eb 1986 if c['ASCII_ART']:
56702c8f 1987 ascii_art(art_dict.get(domain, name))
91476ec3
O
1988 # These arguments are optional:
1989 stream_args = dict(
e3927852 1990 timeout=0.5, # To check g['stream_stop'] after each 0.5 s
cb45dc23 1991 block=True,
1992 heartbeat_timeout=c['HEARTBEAT_TIMEOUT'] * 60)
91476ec3
O
1993 # Track keyword
1994 query_args = dict()
1995 if args.track_keywords:
1996 query_args['track'] = args.track_keywords
91476ec3 1997 # Get stream
2a6238f5 1998 stream = TwitterStream(
22be990e 1999 auth=authen(),
42fde775 2000 domain=domain,
2a6238f5 2001 **stream_args)
2a0cabee
O
2002 try:
2003 if domain == c['USER_DOMAIN']:
2004 tweet_iter = stream.user(**query_args)
2005 elif domain == c['SITE_DOMAIN']:
2006 tweet_iter = stream.site(**query_args)
42fde775 2007 else:
2a0cabee
O
2008 if args.track_keywords:
2009 tweet_iter = stream.statuses.filter(**query_args)
2010 else:
2011 tweet_iter = stream.statuses.sample()
92983945
BS
2012 # Block new stream until other one exits
2013 StreamLock.acquire()
2014 g['stream_stop'] = False
e53e2c70 2015 last_tweet_time = time.time()
72c02928
VNM
2016 for tweet in tweet_iter:
2017 if tweet is None:
f07cfb6b 2018 printNicely('-- None --')
72c02928 2019 elif tweet is Timeout:
47cee703
O
2020 # Because the stream check for each 0.3s
2021 # so we shouldn't output anything here
335e7803
O
2022 if(g['stream_stop']):
2023 StreamLock.release()
2024 break
72c02928 2025 elif tweet is HeartbeatTimeout:
f07cfb6b 2026 printNicely('-- Heartbeat Timeout --')
47cee703 2027 reconn_notice()
8715dda0
O
2028 StreamLock.release()
2029 break
72c02928 2030 elif tweet is Hangup:
f07cfb6b 2031 printNicely('-- Hangup --')
47cee703
O
2032 reconn_notice()
2033 StreamLock.release()
2034 break
72c02928 2035 elif tweet.get('text'):
84b41f58
O
2036 # Slow down the stream by STREAM_DELAY config key
2037 if time.time() - last_tweet_time < c['STREAM_DELAY']:
2038 continue
2039 last_tweet_time = time.time()
2040 # Check the semaphore pause and lock (stream process only)
2041 if g['pause']:
2042 continue
2043 while c['lock']:
2044 time.sleep(0.5)
2045 # Draw the tweet
2046 draw(
2047 t=tweet,
2048 keyword=args.track_keywords,
2049 humanize=False,
2050 fil=args.filter,
2051 ig=args.ignore,
2052 )
2053 # Current readline buffer
2054 current_buffer = readline.get_line_buffer().strip()
2055 # There is an unexpected behaviour in MacOSX readline + Python 2:
2056 # after completely delete a word after typing it,
2057 # somehow readline buffer still contains
2058 # the 1st character of that word
2059 if current_buffer and g['cmd'] != current_buffer:
2060 sys.stdout.write(
211e8be1 2061 g['decorated_name'](g['PREFIX']) + current_buffer)
84b41f58
O
2062 sys.stdout.flush()
2063 elif not c['HIDE_PROMPT']:
211e8be1 2064 sys.stdout.write(g['decorated_name'](g['PREFIX']))
84b41f58 2065 sys.stdout.flush()
14db58c7 2066 elif tweet.get('direct_message'):
4dc385b5
O
2067 # Check the semaphore pause and lock (stream process only)
2068 if g['pause']:
2069 continue
2070 while c['lock']:
2071 time.sleep(0.5)
2072 print_message(tweet['direct_message'])
99cd1fba 2073 elif tweet.get('event'):
d7d9c67c 2074 c['events'].append(tweet)
99cd1fba 2075 print_event(tweet)
742266f8 2076 except TwitterHTTPError as e:
2a0cabee 2077 printNicely('')
c075e6dc 2078 printNicely(
f07cfb6b 2079 magenta('We have connection problem with twitter stream API right now :('))
9e38891f 2080 detail_twitter_error(e)
211e8be1 2081 sys.stdout.write(g['decorated_name'](g['PREFIX']))
62058715 2082 sys.stdout.flush()
ba6c09d1
O
2083 except (URLError, ConnectionResetError):
2084 printNicely(
2085 magenta('There seems to be a connection problem.'))
2086 save_history()
2087 sys.exit()
54277114
O
2088
2089
56702c8f 2090def spawn_public_stream(args, keyword=None):
2091 """
2092 Spawn a new public stream
2093 """
2094 # Only set keyword if specified
2095 if keyword:
2096 if keyword[0] == '#':
2097 keyword = keyword[1:]
2098 args.track_keywords = keyword
3e06aa8f 2099 g['keyword'] = keyword
2100 else:
2101 g['keyword'] = 'Global'
56702c8f 2102 g['PREFIX'] = u2str(emojize(format_prefix(keyword=g['keyword'])))
3e06aa8f 2103 g['listname'] = ''
56702c8f 2104 # Start new thread
2105 th = threading.Thread(
2106 target=stream,
2107 args=(
2108 c['PUBLIC_DOMAIN'],
2109 args))
2110 th.daemon = True
2111 th.start()
2112
2113
2114def spawn_list_stream(args, stuff=None):
2115 """
2116 Spawn a new list stream
2117 """
2118 try:
2119 owner, slug = check_slug(stuff)
2120 except:
2121 owner, slug = get_slug()
3e06aa8f 2122
56702c8f 2123 # Force python 2 not redraw readline buffer
2124 listname = '/'.join([owner, slug])
2125 # Set the listname variable
2126 # and reset tracked keyword
2127 g['listname'] = listname
2128 g['keyword'] = ''
2129 g['PREFIX'] = g['cmd'] = u2str(emojize(format_prefix(
2130 listname=g['listname']
2131 )))
2132 printNicely(light_yellow('getting list members ...'))
2133 # Get members
2134 t = Twitter(auth=authen())
2135 members = []
2136 next_cursor = -1
2137 while next_cursor != 0:
2138 m = t.lists.members(
2139 slug=slug,
2140 owner_screen_name=owner,
2141 cursor=next_cursor,
2142 include_entities=False)
2143 for u in m['users']:
2144 members.append('@' + u['screen_name'])
2145 next_cursor = m['next_cursor']
2146 printNicely(light_yellow('... done.'))
2147 # Build thread filter array
2148 args.filter = members
2149 # Start new thread
2150 th = threading.Thread(
2151 target=stream,
2152 args=(
2153 c['USER_DOMAIN'],
2154 args,
2155 slug))
2156 th.daemon = True
2157 th.start()
2158 printNicely('')
2159 if args.filter:
2160 printNicely(cyan('Include: ' + str(len(args.filter)) + ' people.'))
2161 if args.ignore:
2162 printNicely(red('Ignore: ' + str(len(args.ignore)) + ' people.'))
2163 printNicely('')
2164
2165
2166def spawn_personal_stream(args, stuff=None):
2167 """
2168 Spawn a new personal stream
2169 """
2170 # Reset the tracked keyword and listname
2171 g['keyword'] = g['listname'] = ''
2172 # Reset prefix
2173 g['PREFIX'] = u2str(emojize(format_prefix()))
2174 # Start new thread
2175 th = threading.Thread(
2176 target=stream,
2177 args=(
2178 c['USER_DOMAIN'],
2179 args,
2180 g['original_name']))
2181 th.daemon = True
2182 th.start()
2183
2184
54277114
O
2185def fly():
2186 """
2187 Main function
2188 """
531f5682 2189 # Initial
42fde775 2190 args = parse_arguments()
2a0cabee 2191 try:
a65129d4 2192 proxy_connect(args)
fe9bb33b 2193 init(args)
a65129d4 2194 # Twitter API connection problem
742266f8 2195 except TwitterHTTPError as e:
2a0cabee
O
2196 printNicely('')
2197 printNicely(
f07cfb6b 2198 magenta('We have connection problem with twitter REST API right now :('))
9e38891f 2199 detail_twitter_error(e)
2a0cabee 2200 save_history()
2a0cabee 2201 sys.exit()
a65129d4
O
2202 # Proxy connection problem
2203 except (socks.ProxyConnectionError, URLError):
c426a344 2204 printNicely(
f07cfb6b 2205 magenta('There seems to be a connection problem.'))
c426a344 2206 printNicely(
f07cfb6b 2207 magenta('You might want to check your proxy settings (host, port and type)!'))
c426a344 2208 save_history()
2209 sys.exit()
2210
92983945 2211 # Spawn stream thread
434c2160 2212 target = args.stream.split()[0]
56702c8f 2213 if target == 'mine' :
2214 spawn_personal_stream(args)
3e06aa8f 2215 else:
434c2160 2216 try:
56702c8f 2217 stuff = args.stream.split()[1]
434c2160 2218 except:
3e06aa8f 2219 stuff = None
2220 spawn_dict = {
2221 'public': spawn_public_stream,
2222 'list': spawn_list_stream,
2223 }
2224 spawn_dict.get(target)(args, stuff)
2225
42fde775 2226 # Start listen process
819569e8 2227 time.sleep(0.5)
c91f75f2 2228 g['reset'] = True
1dd312f5 2229 g['prefix'] = True
0f6e4daf 2230 listen()