Last active
July 22, 2021 16:22
-
-
Save AparaV/6facd7db460b905933cf908c8b919b89 to your computer and use it in GitHub Desktop.
Using the tweepy library to stream tweets has a catch. There is no built-in feature that allows you to stop streaming after a fixed time. To avoid manually terminating the stream, this code proposes a simple solution without any (complex) multi-threading.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import time | |
| import tweepy | |
| from tweepy import OAuthHandler | |
| from tweepy import Stream | |
| from tweepy import StreamListener | |
| def authenticate(): | |
| '''Use credentials to authenticate user''' | |
| consumerkey = os.environ.get('CONSUMER_KEY') | |
| consumersecret = os.environ.get('CONSUMER_SECRET') | |
| accesstoken = os.environ.get('ACCESS_TOKEN') | |
| accesssecret = os.environ.get('ACCESS_SECRET') | |
| auth = OAuthHandler(consumerkey, consumersecret) | |
| auth.set_access_token(accesstoken, accesssecret) | |
| api = tweepy.API(auth) | |
| return auth, api | |
| if __name__ == "__main__": | |
| auth, api = authenticate() | |
| '''Live streaming tweets for a specific interval of time''' | |
| runtime = 60 #Tracking for 60 seconds | |
| tweetstream = Stream(auth, StreamListener()) | |
| tweetstream.filter(track=['twitter'], is_async=True) | |
| time.sleep(runtime) | |
| tweetstream.disconnect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@AparaV, it's the only thread. I think the issue might be that the thread where
stream.filteris being ran doesn't terminate. Thanks anyways! I'll investigate the issue.