]> jfr.im git - z_archive/twitter.git/blame - 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
640e695c
MV
1"""
2Example program for the Stream API. This prints public status messages
3from the "sample" stream as fast as possible.
4
5USAGE
6
95d49800 7 stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret>
640e695c
MV
8
9"""
10
11from __future__ import print_function
12
95d49800 13import argparse
640e695c 14
95d49800
AD
15from twitter.stream import TwitterStream
16from twitter.oauth import OAuth
17from twitter.util import printNicely
640e695c 18
640e695c 19
95d49800
AD
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.')
7333aa5a
AD
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.')
95d49800
AD
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.
7333aa5a
AD
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:
b01fa3f8 49 stream = TwitterStream(auth=auth, timeout=60.0)
7333aa5a 50 tweet_iter = stream.statuses.sample()
640e695c
MV
51
52 # Iterate over the sample stream.
640e695c
MV
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'])
95d49800
AD
58
59## main()
60
61if __name__ == '__main__':
62 main()