]> jfr.im git - z_archive/twitter.git/blame_incremental - twitter/stream_example.py
Set a timeout on the main sample stream to test that code path.
[z_archive/twitter.git] / twitter / stream_example.py
... / ...
CommitLineData
1"""
2Example program for the Stream API. This prints public status messages
3from the "sample" stream as fast as possible.
4
5USAGE
6
7 stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret>
8
9"""
10
11from __future__ import print_function
12
13import argparse
14
15from twitter.stream import TwitterStream
16from twitter.oauth import OAuth
17from twitter.util import printNicely
18
19
20def parse_arguments():
21
22 parser = argparse.ArgumentParser()
23
24 parser.add_argument('-t', '--token', help='The Twitter Access Token.')
25 parser.add_argument('-ts', '--token_secret', help='The Twitter Access Token Secret.')
26 parser.add_argument('-ck', '--consumer_key', help='The Twitter Consumer Key.')
27 parser.add_argument('-cs', '--consumer_secret', help='The Twitter Consumer Secret.')
28 parser.add_argument('-us', '--user_stream', action='store_true', help='Connect to the user stream endpoint.')
29 parser.add_argument('-ss', '--site_stream', action='store_true', help='Connect to the site stream endpoint.')
30
31 return parser.parse_args()
32
33## parse_arguments()
34
35
36def main():
37
38 args = parse_arguments()
39
40 # When using twitter stream you must authorize.
41 auth = OAuth(args.token, args.token_secret, args.consumer_key, args.consumer_secret)
42 if args.user_stream:
43 stream = TwitterStream(auth=auth, domain='userstream.twitter.com')
44 tweet_iter = stream.user()
45 elif args.site_stream:
46 stream = TwitterStream(auth=auth, domain='sitestream.twitter.com')
47 tweet_iter = stream.site()
48 else:
49 stream = TwitterStream(auth=auth, timeout=60.0)
50 tweet_iter = stream.statuses.sample()
51
52 # Iterate over the sample stream.
53 for tweet in tweet_iter:
54 # You must test that your tweet has text. It might be a delete
55 # or data message.
56 if tweet.get('text'):
57 printNicely(tweet['text'])
58
59## main()
60
61if __name__ == '__main__':
62 main()