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