2 min read

Instagram Automation with Instabot

This guide demonstrates how to automate uploading photos to Instagram using the instabot library.

Modules Used:

  • instabot: A Python wrapper for the private Instagram API.
  • argparse: To handle command-line arguments.
  • shutil & os: To manage the session configuration folder.

Installation

pip install instabot

The Code

Save this as insta_poster.py.

from instabot import Bot
import argparse
import os
import shutil
import sys

def clean_session():
    """
    Instabot saves session data in a 'config' folder. 
    Deleting this folder forces a fresh login, which resolves many common errors
    related to stale cookies or session loops.
    """
    if os.path.exists("config"):
        try:
            shutil.rmtree("config")
        except Exception:
            pass

def post_to_instagram(username, password, image_path, caption):
    # Clean up old session data before starting
    clean_session()

    bot = Bot()

    print(f"Logging in as {username}...")
    try:
        bot.login(username=username, password=password)
    except Exception as e:
        print(f"Login failed: {e}")
        return

    print(f"Uploading {image_path}...")

    # upload_photo handles resizing and converting to jpg if necessary.
    # Note: It often renames the original file to include .REMOVE_ME extension.
    try:
        bot.upload_photo(image_path, caption=caption)
        print("Upload complete!")
    except Exception as e:
        print(f"Error uploading photo: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Instagram Auto Poster")
    parser.add_argument("-u", "--username", required=True, help="Instagram Username")
    parser.add_argument("-p", "--password", required=True, help="Instagram Password")
    parser.add_argument("-i", "--image", required=True, help="Path to image file (JPG)")
    parser.add_argument("-c", "--caption", default="", help="Post caption")

    args = parser.parse_args()

    if not os.path.exists(args.image):
        print(f"Error: File '{args.image}' not found.")
        sys.exit(1)

    post_to_instagram(args.username, args.password, args.image, args.caption)

Usage

python insta_poster.py -u your_username -p your_password -i photo.jpg -c "Hello Instagram! <a href='/?search=%23python' class='obsidian-tag'>#python</a>"

Important: instabot modifies the input image file during the upload process (it might rename it). It is recommended to use a copy of your image if you want to preserve the original filename.

programming/python/python