[英]Is there a way to stream tweets using python only for specific time?
I'm working on tweepy to stream tweets.我正在处理 tweepy 到 stream 条推文。
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.我一直在寻找一种方法来限制这个 stream 并在我们可以指定的 10 分钟左右的时间后退出流媒体。
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你可以在那里添加一个计时器,比如在它的末尾添加一个
break
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.