从 Twitter 流中排除回复 - tweepy

Exclude replies from twitter streaming - tweepy

我正在使用 tweepy 从 Twitter 的流 api 中提取推文。然后我用它来自动回复那个用户。

例如,如果我想从中提取实时推文然后回复 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 测试包容性:
    • if user_id in [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)