我正在使用 tweepy 从 Twitter 的流媒体 API 中提取推文。然后我使用它来自动回复该用户。
例如,如果我想从 Donald Trump 中提取实时推文然后回复 Donald Trump,我会使用:
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
import json
class StdOutListener(StreamListener):
def on_data(self, data):
clean_data = json.loads(data)
tweetId = clean_data["id"]
tweet = "YOUR MESSAGE HERE"
respondToTweet(tweet, tweetId)
def setUpAuth():
auth = tweepy.OAuthHandler("consumer_token", "consumer_secret")
auth.set_access_token("access_token", "Access_token_secret")
api = tweepy.API(auth)
return api, auth
def followStream():
api, auth = setUpAuth()
listener = StdOutListener()
stream = Stream(auth, listener)
stream.filter(follow=["25073877"], is_async=True)
def respondToTweet(tweet, tweetId):
api, auth = setUpAuth()
api.update_status(tweet, in_reply_to_status_id=tweetId, auto_populate_reply_metadata=True)
if __name__ == "__main__":
followStream()
如果你运行我上面的代码,你会注意到它确实回复了唐纳德特朗普,但也回复了所有对他的推文的新回复
我需要添加什么才能从信息流中排除对其推文的回复?
在此先感谢您的帮助。
最佳答案
- 您可以添加条件以仅直接响应来自
follow
id 的推文。 - 这应该只允许对关注的帐户做出回应。
- 因此在这种情况下,仅当关注的帐户回复时,才会对
tweetId
做出响应。 - 对于多个用户,使用
in
测试包容性:如果 user_id 在 [25073877, id2, id3,...] 中:
class StdOutListener(StreamListener):
def on_data(self, data):
clean_data = json.loads(data)
tweetId = clean_data["id"]
user_id = clean_data['user']['id']
tweet = 'Trying to figure out this code to answer a question on SO, just ignore this'
if user_id == 25073877:
print('Tweeting a reply now') # optional
respondToTweet(tweet, tweetId)
关于python - 从 Twitter 流中排除回复 - tweepy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63542654/