2 Colorful user's timeline stream
4 from multiprocessing
import Process
5 from dateutil
import parser
15 from twitter
.stream
import TwitterStream
, Timeout
, HeartbeatTimeout
, Hangup
16 from twitter
.api
import *
17 from twitter
.oauth
import OAuth
, read_token_file
18 from twitter
.oauth_dance
import oauth_dance
19 from twitter
.util
import printNicely
23 from .interactive
import *
47 def draw(t
, keyword
=None, fil
=[], ig
=[]):
55 screen_name
= t
['user']['screen_name']
56 name
= t
['user']['name']
57 created_at
= t
['created_at']
58 favorited
= t
['favorited']
59 date
= parser
.parse(created_at
)
60 date
= date
- datetime
.timedelta(seconds
=time
.timezone
)
61 clock
= date
.strftime('%Y/%m/%d %H:%M:%S')
64 screen_name
= '@' + screen_name
65 if fil
and screen_name
not in fil
:
67 if ig
and screen_name
in ig
:
70 res
= db
.tweet_query(tid
)
73 res
= db
.tweet_query(tid
)
74 rid
= res
[0].rainbow_id
77 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
78 meta
= grey('[' + clock
+ '] [id=' + str(rid
) + '] ')
80 meta
= meta
+ green(u
'\u2605')
83 tweet
= map(lambda x
: grey(x
) if x
== 'RT' else x
, tweet
)
84 # Highlight screen_name
85 tweet
= map(lambda x
: cycle_color(x
) if x
[0] == '@' else x
, tweet
)
87 tweet
= map(lambda x
: cyan(x
) if x
[0:7] == 'http://' else x
, tweet
)
88 # Highlight search keyword
91 lambda x
: on_yellow(x
) if
92 ''.join(c
for c
in x
if c
.isalnum()).lower() == keyword
.lower()
96 tweet
= ' '.join(tweet
)
99 line1
= u
"{u:>{uw}}:".format(
103 line2
= u
"{c:>{cw}}".format(
115 def parse_arguments():
119 parser
= argparse
.ArgumentParser(description
=__doc__
or "")
123 help='Timeout for the stream (seconds).')
126 '--heartbeat-timeout',
127 help='Set heartbeat timeout.',
133 help='Set stream to non-blocking.')
137 help='Search the stream for specific text.')
141 help='Filter specific screen_name.')
145 help='Ignore specific screen_name.')
146 return parser
.parse_args()
151 Authenticate with Twitter OAuth
153 # When using rainbow stream you must authorize.
154 twitter_credential
= os
.environ
.get(
158 '')) + os
.sep
+ '.rainbow_oauth'
159 if not os
.path
.exists(twitter_credential
):
160 oauth_dance("Rainbow Stream",
164 oauth_token
, oauth_token_secret
= read_token_file(twitter_credential
)
172 def get_decorated_name():
174 Beginning of every line
176 t
= Twitter(auth
=authen())
177 name
= '@' + t
.account
.verify_credentials()['screen_name']
178 g
['original_name'] = name
[1:]
179 g
['decorated_name'] = grey('[') + grey(name
) + grey(']: ')
187 target
= g
['stuff'].split()[0]
190 args
= parse_arguments()
192 if g
['stuff'].split()[-1] == '-f':
193 only
= raw_input('Only nicks: ')
194 ignore
= raw_input('Ignore nicks: ')
195 args
.filter = filter(None, only
.split(','))
196 args
.ignore
= filter(None, ignore
.split(','))
197 elif g
['stuff'].split()[-1] == '-d':
198 args
.filter = ONLY_LIST
199 args
.ignore
= IGNORE_LIST
201 printNicely(red('Sorry, wrong format.'))
205 if target
== 'public':
206 keyword
= g
['stuff'].split()[1]
207 if keyword
[0] == '#':
208 keyword
= keyword
[1:]
210 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
211 args
.track_keywords
= keyword
219 g
['stream_pid'] = p
.pid
222 elif target
== 'mine':
224 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
233 g
['stream_pid'] = p
.pid
235 printNicely(green('Stream switched.'))
237 printNicely(cyan('Only: ' + str(args
.filter)))
239 printNicely(red('Ignore: ' + str(args
.ignore
)))
242 printNicely(red('Sorry I can\'t understand.'))
249 t
= Twitter(auth
=authen())
251 if g
['stuff'].isdigit():
253 for tweet
in reversed(t
.statuses
.home_timeline(count
=num
)):
262 t
= Twitter(auth
=authen())
263 user
= g
['stuff'].split()[0]
266 num
= int(g
['stuff'].split()[1])
269 for tweet
in reversed(t
.statuses
.user_timeline(count
=num
, screen_name
=user
[1:])):
273 printNicely(red('A name should begin with a \'@\''))
280 t
= Twitter(auth
=authen())
281 t
.statuses
.update(status
=g
['stuff'])
288 t
= Twitter(auth
=authen())
290 id = int(g
['stuff'].split()[0])
291 tid
= db
.rainbow_query(id)[0].tweet_id
292 t
.statuses
.retweet(id=tid
, include_entities
=False, trim_user
=True)
294 printNicely(red('Sorry I can\'t retweet for you.'))
301 t
= Twitter(auth
=authen())
303 id = int(g
['stuff'].split()[0])
304 tid
= db
.rainbow_query(id)[0].tweet_id
305 t
.favorites
.create(_id
=tid
, include_entities
=False)
306 printNicely(green('Favorited.'))
307 draw(t
.statuses
.show(id=tid
))
309 printNicely(red('Omg some syntax is wrong.'))
316 t
= Twitter(auth
=authen())
318 id = int(g
['stuff'].split()[0])
319 tid
= db
.rainbow_query(id)[0].tweet_id
320 user
= t
.statuses
.show(id=tid
)['user']['screen_name']
321 status
= ' '.join(g
['stuff'].split()[1:])
322 status
= '@' + user
+ ' ' + status
.decode('utf-8')
323 t
.statuses
.update(status
=status
, in_reply_to_status_id
=tid
)
325 printNicely(red('Sorry I can\'t understand.'))
332 t
= Twitter(auth
=authen())
334 id = int(g
['stuff'].split()[0])
335 tid
= db
.rainbow_query(id)[0].tweet_id
336 t
.statuses
.destroy(id=tid
)
337 printNicely(green('Okay it\'s gone.'))
339 printNicely(red('Sorry I can\'t delete this tweet for you.'))
346 t
= Twitter(auth
=authen())
348 id = int(g
['stuff'].split()[0])
349 tid
= db
.rainbow_query(id)[0].tweet_id
350 t
.favorites
.destroy(_id
=tid
)
351 printNicely(green('Okay it\'s unfavorited.'))
352 draw(t
.statuses
.show(id=tid
))
354 printNicely(red('Sorry I can\'t unfavorite this tweet for you.'))
361 t
= Twitter(auth
=authen())
363 if g
['stuff'][0] == '#':
364 rel
= t
.search
.tweets(q
=g
['stuff'])['statuses']
366 printNicely('Newest tweets:')
367 for i
in reversed(xrange(SEARCH_MAX_RECORD
)):
368 draw(t
=rel
[i
], keyword
=g
['stuff'].strip()[1:])
371 printNicely(magenta('I\'m afraid there is no result'))
373 printNicely(red('A keyword should be a hashtag (like \'#AKB48\')'))
375 printNicely(red('Sorry I can\'t understand.'))
380 List of friend (following)
382 t
= Twitter(auth
=authen())
383 g
['friends'] = t
.friends
.ids()['ids']
384 for i
in g
['friends']:
385 name
= t
.users
.lookup(user_id
=i
)[0]['name']
386 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
387 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
395 t
= Twitter(auth
=authen())
396 g
['followers'] = t
.followers
.ids()['ids']
397 for i
in g
['followers']:
398 name
= t
.users
.lookup(user_id
=i
)[0]['name']
399 screen_name
= '@' + t
.users
.lookup(user_id
=i
)[0]['screen_name']
400 user
= cycle_color(name
) + grey(' ' + screen_name
+ ' ')
409 h
, w
= os
.popen('stty size', 'r').read().split()
412 usage
+= s
+ 'Hi boss! I\'m ready to serve you right now!\n'
413 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
415 usage
+= s
+ 'You are ' + yellow('already') + ' on your personal stream.\n'
416 usage
+= s
* 2 + green('switch public #AKB') + \
417 ' will switch to public stream and follow "' + \
418 yellow('AKB') + '" keyword.\n'
419 usage
+= s
* 2 + green('switch mine') + \
420 ' will switch to your personal stream.\n'
421 usage
+= s
* 2 + green('switch mine -f ') + \
422 ' will prompt to enter the filter.\n'
423 usage
+= s
* 3 + yellow('Only nicks') + \
424 ' filter will decide nicks will be INCLUDE ONLY.\n'
425 usage
+= s
* 3 + yellow('Ignore nicks') + \
426 ' filter will decide nicks will be EXCLUDE.\n'
427 usage
+= s
* 2 + green('switch mine -d') + \
428 ' will use the config\'s ONLY_LIST and IGNORE_LIST.\n'
429 usage
+= s
* 3 + '(see ' + grey('rainbowstream/config.py') + ').\n'
431 usage
+= s
+ 'For more action: \n'
432 usage
+= s
* 2 + green('home') + ' will show your timeline. ' + \
433 green('home 7') + ' will show 7 tweet.\n'
434 usage
+= s
* 2 + green('view @mdo') + \
435 ' will show ' + yellow('@mdo') + '\'s home.\n'
436 usage
+= s
* 2 + green('t oops ') + \
437 'will tweet "' + yellow('oops') + '" immediately.\n'
439 green('rt 12 ') + ' will retweet to tweet with ' + \
440 yellow('[id=12]') + '.\n'
442 green('fav 12 ') + ' will favorite the tweet with ' + \
443 yellow('[id=12]') + '.\n'
444 usage
+= s
* 2 + green('rep 12 oops') + ' will reply "' + \
445 yellow('oops') + '" to tweet with ' + yellow('[id=12]') + '.\n'
447 green('del 12 ') + ' will delete tweet with ' + \
448 yellow('[id=12]') + '.\n'
450 green('ufav 12 ') + ' will unfavorite tweet with ' + \
451 yellow('[id=12]') + '.\n'
452 usage
+= s
* 2 + green('s #AKB48') + ' will search for "' + \
453 yellow('AKB48') + '" and return 5 newest tweet.\n'
454 usage
+= s
* 2 + green('fr') + ' will list out your following people.\n'
455 usage
+= s
* 2 + green('fl') + ' will list out your follower.\n'
456 usage
+= s
* 2 + green('h') + ' will show this help again.\n'
457 usage
+= s
* 2 + green('c') + ' will clear the screen.\n'
458 usage
+= s
* 2 + green('q') + ' will quit.\n'
460 usage
+= s
+ '-' * (int(w
) - 4) + '\n'
461 usage
+= s
+ 'Have fun and hang tight!\n'
476 os
.system('rm -rf rainbow.db')
477 os
.kill(g
['stream_pid'], signal
.SIGKILL
)
486 printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
518 Listen to user's input
523 ['public #', 'mine'], # switch
538 init_interactive_shell(d
)
542 line
= raw_input(g
['decorated_name'])
546 cmd
= line
.split()[0]
549 # Save cmd to global variable and call process
550 g
['stuff'] = ' '.join(line
.split()[1:])
552 if cmd
in ['switch', 't', 'rt', 'rep']:
558 def stream(domain
, args
, name
='Rainbow Stream'):
566 PUBLIC_DOMAIN
: args
.track_keywords
,
567 SITE_DOMAIN
: 'Site Stream',
569 ascii_art(art_dict
[domain
])
571 # These arguments are optional:
573 timeout
=args
.timeout
,
574 block
=not args
.no_block
,
575 heartbeat_timeout
=args
.heartbeat_timeout
)
579 if args
.track_keywords
:
580 query_args
['track'] = args
.track_keywords
583 stream
= TwitterStream(
588 if domain
== USER_DOMAIN
:
589 tweet_iter
= stream
.user(**query_args
)
590 elif domain
== SITE_DOMAIN
:
591 tweet_iter
= stream
.site(**query_args
)
593 if args
.track_keywords
:
594 tweet_iter
= stream
.statuses
.filter(**query_args
)
596 tweet_iter
= stream
.statuses
.sample()
598 # Iterate over the stream.
599 for tweet
in tweet_iter
:
601 printNicely("-- None --")
602 elif tweet
is Timeout
:
603 printNicely("-- Timeout --")
604 elif tweet
is HeartbeatTimeout
:
605 printNicely("-- Heartbeat Timeout --")
606 elif tweet
is Hangup
:
607 printNicely("-- Hangup --")
608 elif tweet
.get('text'):
611 keyword
=args
.track_keywords
,
620 # Spawn stream process
621 args
= parse_arguments()
623 p
= Process(target
=stream
, args
=(USER_DOMAIN
, args
, g
['original_name']))
626 # Start listen process
630 g
['stream_pid'] = p
.pid