我正在使用 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個贊
您可以添加條件以僅直接從
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)
添加回答
舉報
0/150
提交
取消