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