Skip to content

Instantly share code, notes, and snippets.

@AparaV
Last active July 22, 2021 16:22
Show Gist options
  • Select an option

  • Save AparaV/6facd7db460b905933cf908c8b919b89 to your computer and use it in GitHub Desktop.

Select an option

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.
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()
@Kwieeciol
Copy link

@AparaV, it's the only thread. I think the issue might be that the thread where stream.filter is being ran doesn't terminate. Thanks anyways! I'll investigate the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment