How to Automate Your Instagram with Python using instagrapi and replit.com
Introduction
This week, I wrote a simple program that takes some images and automatically uploads them one-by-one to an Instagram account.
If you are not too familiar with Python, I’d recommend starting with a basic version of the script that uploads a single image at a time. However, if you do have some experience with the language, I will walk you through the process of creating a script with a scheduler. We’ll explore how to leverage instagrapi, a fast and robust Python library for interacting with Instagram’s private API. We will be using replit.com, a free, cloud-based development platform, to host and run our script. This approach eliminates the need for local setup and allows your script to run continuously without relying on your personal computer.
By the end of this tutorial, you’ll have a fully functional Instagram auto-posting script that you can customize and expand to suit your specific needs.
I created the images using Midjourney, a popular AI image generation tool, and saved them to a folder. The script, when executed, uploads each image from the folder to the account.
Setting Up the Environment
Before we dive into coding our script, we need to set up our development environment on replit.com. To do this, you’ll have to:
Create an account (the free tier will do for this project)
- Create an account. You can sign up using your email, Google account, or GitHub account. Follow the prompts to complete your account creation.
- Create a new Python Repl: Click on the “+” icon on the top right.
- Select “Python” as your language, give your program a name, and click on the blue Create Repl button.
Install required libraries
In the repl’s shell (usually on the right side of the screen), install the necessary libraries by typing:
python -m pip install instagrapi schedule
This command installs the instagrapi library for Instagram interaction and the schedule library for managing post timing.
Configure environment variables
Since there is no way to make projects private on the free tier, to keep our Instagram login information secure, we’ll use environment variables:
- In the left sidebar of your repl, click on the padlock icon to open the “Secrets” tab.
- Add two new secrets:
- Key: INSTAGRAM_USERNAME, Value: Your Instagram username
- Key: INSTAGRAM_PASSWORD, Value: Your Instagram password
These environment variables can be accessed in your script without exposing sensitive information in your code.
With these steps completed, your replit.com environment is now set up and ready for us to start writing our Instagram auto-posting script.
Writing the Auto-Posting Script
In this section, we’ll break down the main components of our Instagram auto-posting script and explain how each part works.
Create a new Python file
Create a new file in the Files tab and give it a name, making sure to use the suffix ‘.py’ when naming it.
Enter the code provided below into the same file…
Importing necessary libraries
First, let’s look at the libraries we’re using:
import os
from instagrapi import Client
from datetime import datetime, timedelta
import schedule
import time
import logging
These imports provide essential functionality:
os
for file and directory operationsinstagrapi
for interacting with Instagramdatetime
andtimedelta
for time-based operationsschedule
for scheduling poststime
for adding delayslogging
for keeping track of the script's activities
Setting up logging and credentials
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
USERNAME = os.getenv('INSTAGRAM_USERNAME')
PASSWORD = os.getenv('INSTAGRAM_PASSWORD')
We set up basic logging to keep track of the script’s activities. The Instagram credentials are retrieved from environment variables for security.
Implementing the login function
The login_user()
function is a crucial part of our script.
def login_user():
cl = Client()
cl.login(USERNAME, PASSWORD)
logger.info("Successfully logged in")
return cl
This function creates a new Client instance, logs in using the provided credentials, and returns the client object.
Creating the image posting function
The post_image()
function handles uploading an image to Instagram:
def post_image(cl, image_path, caption):
cl.photo_upload(path=image_path, caption=caption)
logger.info(f"Posted image: {image_path}")
It takes a client object, the path to an image, and a caption, then uploads the photo to Instagram.
Generating the daily schedule
The generate_daily_schedule()
function creates a posting schedule:
def generate_daily_schedule(image_folder, start_time):
images = os.listdir(image_folder)
schedule_times = []
current_time = start_time
for _ in images:
schedule_times.append(current_time.strftime("%H:%M"))
current_time += timedelta(minutes=60) # Post every hour
if current_time.day != start_time.day:
break
return schedule_times
This function generates a list of posting times, starting from the given start time and posting every hour until either all images are scheduled or midnight is reached.
Implementing the main posting function
The schedule_and_post()
function is the core of our auto-posting script:
def schedule_and_post():
cl = login_user()
image_folder = 'images'
images = os.listdir(image_folder)
if images:
image = images[0]
caption = os.path.splitext(image)[0] + "\n #midjourney #aiart #promptengineering #chaos #midjourneychaos"
image_path = os.path.join(image_folder, image)
post_image(cl, image_path, caption)
os.remove(image_path)
logger.info(f"Posted and removed image: {image_path}")
return True
else:
logger.info("No images left to post")
return False
This function:
- Logs in to Instagram
- Checks for images in the ‘images’ folder
- If images are present, it takes the first image, generates a caption, posts the image, and then removes it from the folder
- If no images are left, it logs this information and returns False
Setting up the scheduling system
We set up the scheduling system as follows:
start_time = datetime.now() + timedelta(minutes=1)
image_folder = 'images'
images = os.listdir(image_folder)
daily_schedule = generate_daily_schedule(image_folder, start_time)
images_to_post = len(images)
for post_time in daily_schedule:
schedule.every().day.at(post_time).do(schedule_and_post)
logger.info(f"Scheduled {len(daily_schedule)} posts starting at: {daily_schedule[0]}")
logger.info(f"Full schedule: {', '.join(daily_schedule)}")
This code generates a daily schedule starting one minute from now, then uses the schedule
library to set up tasks for each posting time.
Main loop for continuous operation
Finally, we have the main loop that keeps the script running:
while images_to_post > 0:
schedule.run_pending()
time.sleep(1)
if not os.listdir(image_folder):
images_to_post = 0
logger.info("All images have been posted. Script is ending.")
This loop continues running until all images have been posted. It checks for scheduled tasks every second and updates the images_to_post
count when the image folder becomes empty.
It’s important to note that while this script is functional, it doesn’t incorporate all the best practices for using the Instagram API, such as using proxies, implementing delays between requests, or using persistent sessions. These practices will go a long way in ensuring your account does not get banned by Instagram. For a more robust solution, you might want to incorporate these practices as described in the instagrapi documentation.
Creating the Image Folder
In your project directory, create a folder named “images”. This folder will contain all the images you want to post to Instagram.
Image naming convention
The script is designed to use the filename of each image as its caption on Instagram. This feature allows for easy and automatic caption generation.
You can change the feature and even hardcode the captions, if you wish, by editing the code.
If you prefer custom captions, you can modify the schedule_and_post()
function in the script. Look for the following line:
caption = os.path.splitext(image)[0] + "\n #midjourney #aiart #promptengineering #chaos #midjourneychaos"
You can replace this line with your own caption generation logic. For example, you could:
- Read captions from a separate text file
- Use a more complex naming convention for your image files
- Implement a random caption generator
Image creation
The images used in this project were generated using Midjourney, an AI-powered image generation tool.
Best Practices for Image Management:
- Ensure all images are in a format supported by Instagram (JPEG is recommended).
- Resize images to appropriate dimensions for Instagram before adding them to the folder.
- Add new images to the folder regularly to maintain a steady posting schedule.
- Consider using subfolders to organize images by theme or posting date if you have a large number of images.
Running The Script
Now that we have finished writing our code, we can finally run our new Python script!
To do this, first we will create a configuration file:
- Hit the green button on top that says Run. You will see the following message appear in the console. Click on >Configuration to continue.
- In the Confiration Pane, you will have to provide a command that is run every time you click on the Run button.
- Enter the following command replacing “[your Python file name]” with the name of the file you created and its extension:
python ./[your Python file name]
- Once you click the save you will see a new configuration file appear in the Files tab on the left called ‘.replit’. This file can be modified later if you wish to change the default Run command.
- Now hit Run again and your script should come to life!
- You should see the following output in the console:
Troubleshooting Common Issues
When running an automated Instagram posting script, you may encounter various issues. This section covers some common problems and their potential solutions:
Login Failures
Incorrect Credentials:
- Double-check that your USERNAME and PASSWORD environment variables are set correctly in Replit.
- Ensure there are no typos or extra spaces in your credentials.
Temporary Login Issues:
- Instagram might temporarily block login attempts if there are too many in a short period.
- Solution: Implement a delay between login attempts and use exponential backoff for retries.
Account Security Features:
- Instagram may block logins from new locations or devices.
- Solution: You might need to manually log in to your account and confirm the new login attempt.
Rate Limiting Errors
Too Many Requests:
- If you’re seeing errors related to “too many requests” or “try again later,” you’re likely hitting Instagram’s rate limits.
- Solution: Increase the delay between posts. Consider implementing a random delay between 30 minutes to 2 hours between posts.
Account Action Block:
- Instagram may temporarily block your account’s ability to perform certain actions if it suspects automated behavior.
- Solution: Reduce posting frequency and add more randomness to your posting schedule.
Image Upload Problems
Unsupported File Format:
- Ensure all your images are in a format supported by Instagram (JPEG is recommended).
- Solution: Convert all images to JPEG format before adding them to your images folder.
File Size Issues:
- Instagram has limitations on image file sizes.
- Solution: Compress your images to reduce file size while maintaining quality.
Image Dimensions:
- Instagram prefers specific aspect ratios for images.
- Solution: Resize your images to fit Instagram’s recommended dimensions (1:1 square, 4:5 vertical, or 16:9 horizontal).
Empty Image Folder
No Images to Post:
- If your script runs out of images, it will stop posting.
- Solution: Regularly check and replenish your images folder. Consider implementing a notification system to alert you when the folder is running low on images.
Replit-Specific Issues
Project Going to Sleep:
- Free Replit projects go to sleep after periods of inactivity.
- Solution: Use Replit’s “Always On” feature (requires Replit Hacker Plan) or implement a way to periodically wake up your project.
Environment Variable Issues:
- Ensure your environment variables are correctly set in Replit’s Secrets tab.
- If variables aren’t being recognized, try restarting your Replit project.
Instagrapi Library Issues
Outdated Library:
- Instagram frequently updates its API, which can break older versions of instagrapi.
- Solution: Regularly update the instagrapi library to the latest version.
Unexpected Errors:
- If you encounter unfamiliar errors, check the instagrapi GitHub issues page for known problems and solutions.
- Consider implementing more robust error handling in your script to catch and log unexpected exceptions.
Remember, when troubleshooting, it’s crucial to check your logs thoroughly. The logging system implemented in the script will be your primary tool for identifying and diagnosing issues. If problems persist, consider reaching out to the instagrapi community or consulting Instagram’s developer documentation for any recent changes that might affect your script’s functionality.
Recap
We’ve walked through the process of creating a Python script that automates Instagram posting. We covered:
- Setting up the environment on Replit
- Writing the core auto-posting script
- Hosting and running the script on Replit
- Troubleshooting common issues
This script provides a foundation for automating your Instagram content strategy, allowing you to maintain a consistent posting schedule with minimal manual intervention.
Responsible and Ethical Use of Automation
While automation can be a powerful tool for managing social media presence, it’s crucial to use it responsibly:
- Respect Instagram’s terms of service and community guidelines
- Maintain authenticity in your content and engagement
- Use automation as a tool to enhance your strategy, not replace genuine interaction
- Be mindful of posting frequency to avoid overwhelming your followers or triggering Instagram’s anti-spam measures
Happy posting!