I'm working on tweepy to stream tweets.
As far I know we can start the streamer and leave it running indefinitely to work with tweets.
I was looking for a way to limit this stream and exit the streamer after some time like 10 minutes or so which we can specify.
From the docs, I couldn't find anything to do so. (I may have missed too.)
How do I specify the amount of time that the streamer can keep listening to the tweets.
import json
from tweepy import StreamListener, OAuthHandler, Stream
class StdOutListener(StreamListener):
def __init__(self):
self.hashtag_frequency = {}
def on_data(self, data):
hashtags = json.loads(data)["entities"]["hashtags"]
for hashtag in hashtags:
text = hashtag["text"]
self.hashtag_frequency[text] = self.hashtag_frequency.get(text, 1) + 1
print(self.hashtag_frequency)
return True
def on_error(self, status):
print(status)
listener = StdOutListener()
auth = OAuthHandler('', '')
auth.set_access_token('', '')
stream = Stream(auth, listener)
stream.filter(track=['testing'])
You could add a timer in there, something like and just add a break
at the end of it
import time
t = #Add number of seconds you want the bot to run, if you want 10 minutes, than it's 600 seconds
if t != 0:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
t -= 1
else:
return
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.