2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 from dateutil
import parser
16 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
17 from twitter
.api
import *
18 from twitter
.oauth
import OAuth
, read_token_file
19 from twitter
.oauth_dance
import oauth_dance
20 from twitter
.util
import printNicely
21 from StringIO
import StringIO
25 from .consumer
import *
26 from .interactive
import *
28 from .c_image
import *
51 def draw(t
, imgflg
= 0, keyword
=None, fil
=[], ig
=[]):
59 screen_name
= t
['user']['screen_name']
60 name
= t
['user']['name']
61 created_at
= t
['created_at']
62 favorited
= t
['favorited']
63 date
= parser
.parse(created_at
)
64 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
65 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
71 urls
= t
['entities']['urls']
73 expanded_url
.append(u
['expanded_url'])
82 media
= t
['entities']['media']
84 media_url
= m
['media_url']
89 screen_name
= '@' + screen_name
90 if fil
and screen_name
not in fil
:
92 if ig
and screen_name
in ig
:
95 res
= db
.tweet_query(tid
)
98 res
= db
.tweet_query(tid
)
99 rid
= res
[0].rainbow_id
102 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
103 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
105 meta
= meta
+ green(u
'\u2605')
109 for index
in range(len(expanded_url
)):
111 lambda x
: expanded_url
[index
] if x
== url
[index
] else x
,
114 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
115 # Highlight screen_name
116 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
118 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
119 # Highlight search keyword
122 lambda x
: on_yellow(x
) if
123 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
128 tweet
= ' '.join(tweet
)
131 line1
= u
"{u:>{uw}}:".format(
135 line2
= u
"{c:>{cw}}".format(
147 if imgflg
and media_url
:
148 response
= requests
.get(media_url
)
149 image_to_display(StringIO(response
.content
))
152 def parse_arguments():
156 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
160 help='Timeout for the stream (seconds).')
163 '--heartbeat-timeout',
164 help='Set heartbeat timeout.',
170 help='Set stream to non-blocking.')
174 help='Search the stream for specific text.')
178 help='Filter specific screen_name.')
182 help='Ignore specific screen_name.')
186 help='Display all photo on terminal.')
187 return parser
.parse_args()
192 Authenticate with Twitter OAuth
194 # When using rainbow stream you must authorize.
195 twitter_credential
= os
.environ
.get(
199 '')) + os
.sep
+ '.rainbow_oauth'
200 if not os
.path
.exists(twitter_credential
):
201 oauth_dance("Rainbow Stream",
205 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
213 def get_decorated_name():
215 Beginning of every line
217 t
= Twitter(auth
=authen())
218 name
= '@' + t
.account
.verify_credentials()['screen_name']
219 g
['original_name'] = name
[1:]
220 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
228 target
= g
['stuff'].split()[0]
231 args
= parse_arguments()
233 if g
['stuff'].split()[-1] == '-f':
234 only
= raw_input('Only nicks: ')
235 ignore
= raw_input('Ignore nicks: ')
236 args
.filter = filter(None, only
.split(','))
237 args
.ignore
= filter(None, ignore
.split(','))
238 elif g
['stuff'].split()[-1] == '-d':
239 args
.filter = ONLY_LIST
240 args
.ignore
= IGNORE_LIST
242 printNicely(red('Sorry, wrong format.'))
246 if target
== 'public':
247 keyword
= g
['stuff'].split()[1]
248 if keyword
[0] == '#':
249 keyword
= keyword
[1:]
251 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
252 args
.track_keywords
= keyword
260 g
['stream_pid'] = p
.pid
263 elif target
== 'mine':
265 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
274 g
['stream_pid'] = p
.pid
276 printNicely(green('Stream switched.'))
278 printNicely(cyan('Only: ' + str(args
.filter)))
280 printNicely(red('Ignore: ' + str(args
.ignore
)))
283 printNicely(red('Sorry I can\'t understand.'))
290 t
= Twitter(auth
=authen())
292 if g
['stuff'].isdigit():
294 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
295 draw(t
=tweet
, imgflg
=g
['image'])
303 t
= Twitter(auth
=authen())
304 user
= g
['stuff'].split()[0]
307 num
= int(g
['stuff'].split()[1])
310 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
311 draw(t
=tweet
, imgflg
=g
['image'])
314 printNicely(red('A name should begin with a \'@\''))
321 t
= Twitter(auth
=authen())
322 t
.statuses
.update(status
=g
['stuff'])
329 t
= Twitter(auth
=authen())
331 id = int(g
['stuff'].split()[0])
332 tid
= db
.rainbow_query(id)[0].tweet_id
333 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
335 printNicely(red('Sorry I can\'t retweet for you.'))
342 t
= Twitter(auth
=authen())
344 id = int(g
['stuff'].split()[0])
345 tid
= db
.rainbow_query(id)[0].tweet_id
346 t
.favorites
.create(_id
=tid
, include_entities
=False)
347 printNicely(green('Favorited.'))
348 draw(t
.statuses
.show(id=tid
), imgflg
=g
['image'])
350 printNicely(red('Omg some syntax is wrong.'))
357 t
= Twitter(auth
=authen())
359 id = int(g
['stuff'].split()[0])
360 tid
= db
.rainbow_query(id)[0].tweet_id
361 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
362 status
= ' '.join(g
['stuff'].split()[1:])
363 status
= '@' + user
+ ' ' + status
.decode('utf-8')
364 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
366 printNicely(red('Sorry I can\'t understand.'))
373 t
= Twitter(auth
=authen())
375 id = int(g
['stuff'].split()[0])
376 tid
= db
.rainbow_query(id)[0].tweet_id
377 t
.statuses
.destroy(id=tid
)
378 printNicely(green('Okay it\'s gone.'))
380 printNicely(red('Sorry I can\'t delete this tweet for you.'))
387 t
= Twitter(auth
=authen())
389 id = int(g
['stuff'].split()[0])
390 tid
= db
.rainbow_query(id)[0].tweet_id
391 t
.favorites
.destroy(_id
=tid
)
392 printNicely(green('Okay it\'s unfavorited.'))
393 draw(t
.statuses
.show(id=tid
), imgflg
=g
['image'])
395 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
402 t
= Twitter(auth
=authen())
404 if g
['stuff'][0] == '#':
405 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
407 printNicely('Newest tweets:')
408 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
411 keyword
=g
['stuff'].strip()[1:])
414 printNicely(magenta('I\'m afraid there is no result'))
416 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
418 printNicely(red('Sorry I can\'t understand.'))
423 List of friend (following)
425 t
= Twitter(auth
=authen())
426 g
['friends'] = t
.friends
.ids()['ids']
427 for i
in g
['friends']:
428 name
= t
.users
.lookup(user_id
=i
)[0]['name']
429 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
430 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
438 t
= Twitter(auth
=authen())
439 g
['followers'] = t
.followers
.ids()['ids']
440 for i
in g
['followers']:
441 name
= t
.users
.lookup(user_id
=i
)[0]['name']
442 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
443 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
452 h
, w
= os
.popen('stty size', 'r').read().split()
455 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
456 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
458 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
459 usage
+= s
* 2 + green('switch public #AKB') + \
460 ' will switch to public stream and follow "' + \
461 yellow('AKB') + '" keyword.\n'
462 usage
+= s
* 2 + green('switch mine') + \
463 ' will switch to your personal stream.\n'
464 usage
+= s
* 2 + green('switch mine -f ') + \
465 ' will prompt to enter the filter.\n'
466 usage
+= s
* 3 + yellow('Only nicks') + \
467 ' filter will decide nicks will be INCLUDE ONLY.\n'
468 usage
+= s
* 3 + yellow('Ignore nicks') + \
469 ' filter will decide nicks will be EXCLUDE.\n'
470 usage
+= s
* 2 + green('switch mine -d') + \
471 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
472 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
474 usage
+= s
+ 'For more action: \n'
475 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
476 green('home 7') + ' will show 7 tweet.\n'
477 usage
+= s
* 2 + green('view @mdo') + \
478 ' will show ' + yellow('@mdo') + '\'s home.\n'
479 usage
+= s
* 2 + green('t oops ') + \
480 'will tweet "' + yellow('oops') + '" immediately.\n'
482 green('rt 12 ') + ' will retweet to tweet with ' + \
483 yellow('[id=12]') + '.\n'
485 green('fav 12 ') + ' will favorite the tweet with ' + \
486 yellow('[id=12]') + '.\n'
487 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
488 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
490 green('del 12 ') + ' will delete tweet with ' + \
491 yellow('[id=12]') + '.\n'
493 green('ufav 12 ') + ' will unfavorite tweet with ' + \
494 yellow('[id=12]') + '.\n'
495 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
496 yellow('AKB48') + '" and return 5 newest tweet.\n'
497 usage
+= s
* 2 + green('fr') + ' will list out your following people.\n'
498 usage
+= s
* 2 + green('fl') + ' will list out your follower.\n'
499 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
500 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
501 usage
+= s
* 2 + green('q') + ' will quit.\n'
503 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
504 usage
+= s
+ 'Have fun and hang tight!\n'
519 os
.system('rm -rf rainbow.db')
520 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
529 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
561 Listen to user's input
566 ['public #', 'mine'], # switch
581 init_interactive_shell(d
)
585 line
= raw_input(g
['decorated_name'])
589 cmd
= line
.split()[0]
592 # Save cmd to global variable and call process
593 g
['stuff'] = ' '.join(line
.split()[1:])
595 if cmd
in ['switch', 't', 'rt', 'rep']:
601 def stream(domain
, args
, name
='Rainbow Stream'):
609 PUBLIC_DOMAIN
: args
.track_keywords
,
610 SITE_DOMAIN
: 'Site Stream',
612 ascii_art(art_dict
[domain
])
614 # These arguments are optional:
616 timeout
=args
.timeout
,
617 block
=not args
.no_block
,
618 heartbeat_timeout
=args
.heartbeat_timeout
)
622 if args
.track_keywords
:
623 query_args
['track'] = args
.track_keywords
626 stream
= TwitterStream(
631 if domain
== USER_DOMAIN
:
632 tweet_iter
= stream
.user(**query_args
)
633 elif domain
== SITE_DOMAIN
:
634 tweet_iter
= stream
.site(**query_args
)
636 if args
.track_keywords
:
637 tweet_iter
= stream
.statuses
.filter(**query_args
)
639 tweet_iter
= stream
.statuses
.sample()
641 # Iterate over the stream.
642 for tweet
in tweet_iter
:
644 printNicely("-- None --")
645 elif tweet
is Timeout
:
646 printNicely("-- Timeout --")
647 elif tweet
is HeartbeatTimeout
:
648 printNicely("-- Heartbeat Timeout --")
649 elif tweet
is Hangup
:
650 printNicely("-- Hangup --")
651 elif tweet
.get('text'):
655 keyword
=args
.track_keywords
,
665 # Spawn stream process
666 args
= parse_arguments()
668 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
671 # Start listen process
675 g
['stream_pid'] = p
.pid
676 g
['image'] = args
.image