skip to Main Content

The script stops after 100 items and then I have to rerun
it manually. How can I automate this and have the script
rerun automatically?

#IMPORT LIBRARIES 
import tweepy
import time

# API KEYS AND TOKENS
api_key= "API KEY GOES IN HERE"
api_key_secret = "API SECRET KEY GOES IN HERE"
access_token = "ACCESS TOKEN GOES HERE"
access_token_secret = "SECRET ACCESS TOKEN GOES HERE"

# AUTHENTICATING TWITTER
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token , access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

# HASHTAG AND NUMBER OF ITEMS
hashtag = "#AmisomOut"
tweet_number = 100

# THE CURSOR METHOD
tweets = tweepy.Cursor(api.search, hashtag).items(tweet_number)


def searchBot():
    for tweet in tweets:
        try:
            tweet.retweet()
            print("retweet done!")
            time.sleep(2)
        except tweepy.TweepError as e:
            print(e.reason)
            time.sleep(15)

searchBot()

2

Answers


  1. Putting the code you want to repeat in a while loop will make it repeat infinitely. In this case, it looks like you only need to repeat some of the code for the desired result.

    First, define your searchBot function, then put the following lines inside the loop:

    while True:
        tweets = tweepy.Cursor(api.search, hashtag).items(tweet_number)
        searchBot()
    

    This will continue until you manually quit the program, either by exiting the terminal window or pressing ctrl+c.

    Login or Signup to reply.
  2. You can use crontab to run tasks on a schedule.

    Assuming you’re on Linux/MacOS and the file name is searchbot.py:

    In Terminal type EDITOR=nano crontab -e

    This will open your crontab file. It will run the bash commands at the given time schedule. The example I’ve given is for every 5 minutes.

    */5 * * * * python3 searchbot.py
    

    CTRL+X to save and exit the file.

    You can type crontab -l to confirm the changes have been written.

    You can use https://crontab.guru/ to come up with your own schedules and to understand the format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search