为了账号安全,请及时绑定邮箱和手机立即绑定

从 Twitter 流中排除回复 - tweepy

从 Twitter 流中排除回复 - tweepy

陪伴而非守候 2023-06-13 10:51:03
我正在使用 tweepy 从 Twitter 的流媒体 API 中提取推文。然后我用它来自动回复那个用户。例如,如果我想从中提取实时推文然后回复唐纳德特朗普,我使用:import tweepyfrom tweepy import Streamfrom tweepy.streaming import StreamListenerimport jsonclass 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, authdef 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()如果你运行我上面的代码,你会注意到它确实回复了唐纳德特朗普,但也回复了他的推文的所有新回复我需要添加什么才能从流中排除对他的推文的回复?在此先感谢您的帮助。
查看完整描述

1 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

  • 您可以添加条件以仅直接从followid 响应推文。

  • 这应该只允许对所关注的帐户做出响应。

  • 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)


查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信