Search code examples
pythontwittertweepytwitterapi-python

Python - Tweepy - What do I need to add to make this code reply to an account rather than a keyword?


This is my current code that I use, which responds immediately to any tweet containing any keyword. Instead, I want to change this code to automatically respond to a specific account (whenever it tweets). What do I need to add or remove to make this happen? This current code works, I just would like to know how to change what it replies to.

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 REPLY HERE"
        respondToTweet(tweet, tweetId)

def setUpAuth():
    auth = tweepy.OAuthHandler("consumer_key", "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(track=["KEYWORDS"])

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

Solution

  • Solved!

    For anyone else wondering how this was done, here's what I did:

    I changed this line in my code:

    stream.filter(track=["KEYWORDS"])
    

    to:

    stream.filter(follow=["TWITTER_ID"])
    

    TWITTER_ID = the twitter id of the user you want to automatically reply to, which can be found by plugging their handle into tweeterid.com.

    For example realdonaldtrump's twitter id is 25073877, therefore you would replace TWITTER_ID with 25073877.