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