Using Python and Tweepy - How to reply with set text each time a specific user tweets?

Viewed 14

I am able to reply to a specific tweet by getting tweet IDs, but cannot get my configuration to do what I want it to do, which is to reply to every tweet from a specific user. I have that user's username and ID. Currently it appears to only be pulling one tweet, which I suspect has something to do with line 23's tweet.id. I guess what I'm looking for is a way to ensure that my bot replies every single time this user tweets. Here is my current code (sensitive info redacted)

from ast import For
import tweepy

api_key = "###############################################"
api_secret = "###############################################"
bearer_token = r"###############################################"
access_token = "###############################################"
access_token_secret = "###############################################"

client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)

auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
api = tweepy.API(auth)

toReply = "TwitterUsernameHere"
api = tweepy.API(auth)

tweets = api.user_timeline(screen_name = toReply, count=1)

for tweet in tweets:
    api.update_status("@" + toReply + " Why? ", in_reply_to_status_id = tweet.id)

1 Answers

Assuming that you are following the Twitter automation rules (i.e. that you're only replying to Tweets that the user has opted-in for your app to reply to - otherwise your user account or app will be restricted)...

... your code currently checks the user's Timeline, and then replies to the most recent single Tweet (count=1 on the user_timeline call). You would need this to check for new Tweets in order to reply to different ones. You could store tweet.id somewhere and only reply to it when it changes.

Note that there are a few other things to tidy up:

  • from ast import For is not required
  • client = tweepy.Client targets the Twitter API v2 but the rest of the code uses Twitter API v1.1 (via tweepy.API)
  • bearer_token is unused in this code and will only work for a read operation in v1.1 of the API so you could remove it.
Related