Search code examples
pythontwitterbotstweepy

Twitter bot that replies to a specific user


I want to code a Twitter bot using tweepy that automatically replies to all my friend tweets but the problem is that I must always run it by myself can somebody explains to me how to do that, please. Here is my actual code:

import tweepy
from keys import keys

CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

toReply = "USER" #user to get most recent tweet
api = tweepy.API(auth)

#get the most recent tweet from the user
tweets = api.user_timeline(screen_name = toReply, count=1)

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

Solution

  • You have to run the python script by yourself each time because the script finishes after running.

    Right now, when you click run or type python myscript.py the script runs, checks your friends' tweets and tweets out something. After the tweet is sent, the script stops. It's over.

    A solution to this could be putting the script in an infinite loop and check for tweets every period of time and keep it running on your device at all times.

    Of course, the script won't work when your PC is off and you're gonna have to run the script each time you turn on your PC (you could automate this as well, using TaskScheduler if you're on Windows)

    Or you could deploy your code to a cloud server where it's going to be running at all times but it's going to cost you some money.

    Have a look at Google Cloud, Amazon Web Services and Microsoft Azure, those are the three biggest cloud providers.

    The code would look something like this:

    import tweepy
    from keys import keys
    import time 
    
    def check_tweets(): 
        CONSUMER_KEY = keys['consumer_key']
        CONSUMER_SECRET = keys['consumer_secret']
        ACCESS_TOKEN = keys['access_token']
        ACCESS_TOKEN_SECRET = keys['access_token_secret']
        
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
        api = tweepy.API(auth)
        
        toReply = "USER" #user to get most recent tweet
        api = tweepy.API(auth)
        
        #get the most recent tweet from the user
        tweets = api.user_timeline(screen_name = toReply, count=1)
        
        for tweet in tweets:
        api.update_status("@" + toReply + " TEXT", in_reply_to_status_id = tweet.id)
    
    while True: 
        check_tweets()
        time.sleep(60) # 60 seconds