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