CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-instabot

Instagram bot scripts for promotion and API python wrapper

Pending
Overview
Eval results
Files

api-access.mddocs/

API Access

Low-level Instagram API wrapper providing direct access to Instagram endpoints with minimal abstraction. The API class offers precise control over Instagram interactions without the automated behavior and filtering of the Bot class.

Capabilities

API Initialization and Authentication

Initialize and authenticate with Instagram's API endpoints using various configuration options.

class API:
    def __init__(self,
                 device=None,
                 base_path=current_path + "/config/",
                 save_logfile=True,
                 log_filename=None,
                 loglevel_file=logging.DEBUG,
                 loglevel_stream=logging.INFO):
        """
        Initialize Instagram API wrapper.
        
        Parameters:
        - device: Device identifier from devices.py (defaults to None)
        - base_path: Base path for configuration files (current_path + "/config/")
        - save_logfile: Whether to save API logs to file (default True)
        - log_filename: Custom log filename (default None)
        - loglevel_file: Log level for file logging (default logging.DEBUG)
        - loglevel_stream: Log level for console logging (default logging.INFO)
        """

    def login(self,
              username=None,
              password=None,
              force=False,
              proxy=None,
              use_cookie=True,
              use_uuid=True,
              cookie_fname=None,
              ask_for_code=False,
              set_device=True,
              generate_all_uuids=True,
              is_threaded=False):
        """
        Authenticate with Instagram API.
        
        Parameters:
        - username: Instagram username
        - password: Instagram password
        - force: Force new login session
        - proxy: Proxy server configuration
        - use_cookie: Use saved cookies for authentication
        - use_uuid: Generate/use UUID for session
        - cookie_fname: Custom cookie filename
        - ask_for_code: Prompt for 2FA code if needed
        - set_device: Set device fingerprint
        - generate_all_uuids: Generate all required UUIDs
        - is_threaded: Whether running in threaded environment
        
        Returns:
        bool: True if login successful, False otherwise
        """

    def logout(self):
        """
        Logout from Instagram API session.
        
        Returns:
        bool: True if logout successful
        """

    def two_factor_auth(self):
        """
        Handle two-factor authentication challenge.
        
        Returns:
        bool: True if 2FA successful
        """

    def solve_challenge(self):
        """
        Solve Instagram security challenge.
        
        Returns:
        bool: True if challenge solved successfully
        """

User Management Operations

Retrieve user information, manage followers/following relationships, and perform user-related actions.

def get_user_followers(self, user_id, max_id=""):
    """
    Retrieve user's followers list.
    
    Parameters:
    - user_id: Target user ID
    - max_id: Pagination cursor for next page
    
    Returns:
    dict: Response containing followers list and pagination info
    """

def get_user_followings(self, user_id, max_id=""):
    """
    Retrieve user's following list.
    
    Parameters:
    - user_id: Target user ID
    - max_id: Pagination cursor for next page
    
    Returns:
    dict: Response containing following list and pagination info
    """

def get_username_info(self, user_id):
    """
    Get detailed user information.
    
    Parameters:
    - user_id: Target user ID or username
    
    Returns:
    dict: User information including profile details, counts, and settings
    """

def get_self_username_info(self):
    """
    Get current authenticated user's information.
    
    Returns:
    dict: Current user's profile information
    """

def follow(self, user_id):
    """
    Follow a user.
    
    Parameters:
    - user_id: Target user ID
    
    Returns:
    dict: API response with follow status
    """

def unfollow(self, user_id):
    """
    Unfollow a user.
    
    Parameters:
    - user_id: Target user ID
    
    Returns:
    dict: API response with unfollow status
    """

def block(self, user_id):
    """
    Block a user.
    
    Parameters:
    - user_id: Target user ID
    
    Returns:
    dict: API response with block status
    """

def unblock(self, user_id):
    """
    Unblock a user.
    
    Parameters:
    - user_id: Target user ID
    
    Returns:
    dict: API response with unblock status
    """

def remove_follower(self, user_id):
    """
    Remove a follower.
    
    Parameters:
    - user_id: Follower user ID to remove
    
    Returns:
    dict: API response with removal status
    """

Media Management Operations

Upload, download, and manage photos and videos with detailed control over metadata and options.

def upload_photo(self,
                 photo,
                 caption=None,
                 upload_id=None,
                 from_video=False,
                 force_resize=False,
                 options={}):
    """
    Upload photo to Instagram.
    
    Parameters:
    - photo: Photo file path or data
    - caption: Photo caption text
    - upload_id: Custom upload identifier
    - from_video: Whether photo is extracted from video
    - force_resize: Force photo resizing
    - options: Additional upload options
    
    Returns:
    dict: Upload response with media information
    """

def download_photo(self, media_id, filename, media=False, folder="photos"):
    """
    Download photo from Instagram.
    
    Parameters:
    - media_id: Instagram media ID
    - filename: Download filename
    - media: Media object instead of ID
    - folder: Download folder path
    
    Returns:
    bool: True if download successful
    """

def upload_video(self,
                 video,
                 caption=None,
                 upload_id=None,
                 thumbnail=None,
                 options={}):
    """
    Upload video to Instagram.
    
    Parameters:
    - video: Video file path
    - caption: Video caption text
    - upload_id: Custom upload identifier
    - thumbnail: Thumbnail image path
    - options: Additional upload options
    
    Returns:
    dict: Upload response with media information
    """

def download_video(self, media_id, filename, media=False, folder="video"):
    """
    Download video from Instagram.
    
    Parameters:
    - media_id: Instagram media ID
    - filename: Download filename
    - media: Media object instead of ID
    - folder: Download folder path
    
    Returns:
    bool: True if download successful
    """

def media_info(self, media_id):
    """
    Get detailed media information.
    
    Parameters:
    - media_id: Instagram media ID
    
    Returns:
    dict: Media information including URLs, dimensions, user data
    """

def delete_media(self, media):
    """
    Delete media post.
    
    Parameters:
    - media: Media object or media ID
    
    Returns:
    dict: Deletion response
    """

def archive_media(self, media, undo=False):
    """
    Archive or unarchive media post.
    
    Parameters:
    - media: Media object or media ID
    - undo: Unarchive if True, archive if False
    
    Returns:
    dict: Archive operation response
    """

Interaction Operations

Perform likes, comments, and other engagement actions with detailed tracking parameters.

def like(self,
         media_id,
         double_tap=None,
         container_module="feed_short_url",
         feed_position=0,
         username=None,
         user_id=None,
         hashtag_name=None,
         hashtag_id=None,
         entity_page_name=None,
         entity_page_id=None):
    """
    Like a media post with detailed tracking.
    
    Parameters:
    - media_id: Instagram media ID
    - double_tap: Double tap like indicator
    - container_module: Source module for analytics
    - feed_position: Position in feed for analytics
    - username: Username for context tracking
    - user_id: User ID for context tracking
    - hashtag_name: Hashtag context
    - hashtag_id: Hashtag ID for context
    - entity_page_name: Entity page context
    - entity_page_id: Entity page ID
    
    Returns:
    dict: Like operation response
    """

def unlike(self, media_id):
    """
    Unlike a media post.
    
    Parameters:
    - media_id: Instagram media ID
    
    Returns:
    dict: Unlike operation response
    """

def comment(self, media_id, comment_text):
    """
    Comment on a media post.
    
    Parameters:
    - media_id: Instagram media ID
    - comment_text: Comment content
    
    Returns:
    dict: Comment operation response with comment ID
    """

def reply_to_comment(self, media_id, comment_text, parent_comment_id):
    """
    Reply to an existing comment.
    
    Parameters:
    - media_id: Instagram media ID
    - comment_text: Reply content
    - parent_comment_id: ID of comment being replied to
    
    Returns:
    dict: Reply operation response
    """

def delete_comment(self, media_id, comment_id):
    """
    Delete a comment.
    
    Parameters:
    - media_id: Instagram media ID
    - comment_id: Comment ID to delete
    
    Returns:
    dict: Delete operation response
    """

Feed Operations

Access various Instagram feeds including timeline, user feeds, hashtag feeds, and location-based content.

def get_timeline_feed(self, options=[]):
    """
    Get user's timeline feed.
    
    Parameters:
    - options: Additional feed options
    
    Returns:
    dict: Timeline feed response with media items
    """

def get_user_feed(self, user_id, max_id="", min_timestamp=None):
    """
    Get specific user's media feed.
    
    Parameters:
    - user_id: Target user ID
    - max_id: Pagination cursor
    - min_timestamp: Minimum timestamp for posts
    
    Returns:
    dict: User feed response with media items and pagination
    """

def get_hashtag_feed(self, hashtag, max_id=""):
    """
    Get hashtag feed.
    
    Parameters:
    - hashtag: Hashtag name (without #)
    - max_id: Pagination cursor
    
    Returns:
    dict: Hashtag feed response with media items
    """

def get_location_feed(self, location_id, max_id=""):
    """
    Get location-based feed.
    
    Parameters:
    - location_id: Instagram location ID
    - max_id: Pagination cursor
    
    Returns:
    dict: Location feed response with media items
    """

def get_liked_media(self, max_id=""):
    """
    Get user's liked media.
    
    Parameters:
    - max_id: Pagination cursor
    
    Returns:
    dict: Liked media response with items and pagination
    """

Story Operations

Upload, download, and manage Instagram Stories content.

def upload_story_photo(self, photo, upload_id=None):
    """
    Upload photo to Instagram Story.
    
    Parameters:
    - photo: Photo file path
    - upload_id: Custom upload identifier
    
    Returns:
    dict: Story upload response
    """

def download_story(self, filename, story_url, username):
    """
    Download story content.
    
    Parameters:
    - filename: Download filename
    - story_url: Story media URL
    - username: Story owner username
    
    Returns:
    bool: True if download successful
    """

def get_user_reel(self, user_id):
    """
    Get user's story reel.
    
    Parameters:
    - user_id: Target user ID
    
    Returns:
    dict: User reel response with story items
    """

Direct Message Operations

Send and manage direct messages and message threads.

def send_direct_item(self, item_type, users, **options):
    """
    Send direct message item.
    
    Parameters:
    - item_type: Type of message item ("text", "media", etc.)
    - users: List of recipient user IDs
    - **options: Additional message options (text content, media_id, etc.)
    
    Returns:
    dict: Send message response
    """

def get_direct_v2_inbox(self):
    """
    Get direct message inbox.
    
    Returns:
    dict: Inbox response with message threads
    """

def get_thread(self, thread_id, cursor_id=None):
    """
    Get direct message thread.
    
    Parameters:
    - thread_id: Message thread ID
    - cursor_id: Pagination cursor
    
    Returns:
    dict: Thread response with messages
    """

Search Operations

Search for users, hashtags, and locations across Instagram.

def search_users(self, query):
    """
    Search for users by query.
    
    Parameters:
    - query: Search query string
    
    Returns:
    dict: Search results with user list
    """

def search_tags(self, query):
    """
    Search for hashtags by query.
    
    Parameters:
    - query: Hashtag search query
    
    Returns:
    dict: Search results with hashtag list
    """

def search_location(self, query="", lat=None, lng=None):
    """
    Search for locations by query or coordinates.
    
    Parameters:
    - query: Location search query
    - lat: Latitude coordinate
    - lng: Longitude coordinate
    
    Returns:
    dict: Search results with location list
    """

def fb_user_search(self, query):
    """
    Search Facebook users connected to Instagram.
    
    Parameters:
    - query: Search query string
    
    Returns:
    dict: Facebook user search results
    """

API Properties and State

Access current session state and configuration information.

@property
def user_id(self):
    """Current authenticated user ID"""

@property
def username(self):
    """Current authenticated username"""

@property
def cookie_dict(self):
    """Session cookie dictionary"""

@property
def token(self):
    """CSRF token for API requests"""

@property
def rank_token(self):
    """Rank token for API requests"""

Usage Examples

Basic API Usage

from instabot import API

# Initialize API
api = API(save_logfile=True, loglevel_stream=logging.INFO)

# Login
success = api.login(username="your_username", password="your_password")
if not success:
    print("Login failed")
    exit()

# Get user information
user_info = api.get_username_info("target_user")
print(f"User: {user_info['user']['username']}")
print(f"Followers: {user_info['user']['follower_count']}")

# Upload a photo
result = api.upload_photo("photo.jpg", caption="Hello Instagram!")
if result:
    print("Photo uploaded successfully")

# Like some media
media_info = api.get_user_feed("target_user")
for media in media_info['items'][:3]:
    api.like(media['id'])
    print(f"Liked media: {media['id']}")

# Logout
api.logout()

Advanced API Operations

from instabot import API
import logging

# Initialize with custom configuration
api = API(
    device="samsung_galaxy_s9_plus",
    save_logfile=True,
    log_filename="my_api.log",
    loglevel_file=logging.DEBUG
)

# Login with advanced options
api.login(
    username="advanced_user",
    password="secure_password",
    use_cookie=True,
    generate_all_uuids=True
)

# Complex feed operations
hashtag_feed = api.get_hashtag_feed("photography", max_id="")
for media in hashtag_feed['items'][:10]:
    # Get detailed media info
    media_details = api.media_info(media['id'])
    
    # Like with tracking parameters
    api.like(
        media['id'],
        container_module="hashtag_feed",
        hashtag_name="photography",
        username=media['user']['username']
    )
    
    # Comment on selected posts
    if media['like_count'] > 100:
        api.comment(media['id'], "Amazing shot! 📸")

# Direct message operations
inbox = api.get_direct_v2_inbox()
for thread in inbox['inbox']['threads'][:5]:
    thread_details = api.get_thread(thread['thread_id'])
    print(f"Thread with: {thread['users'][0]['username']}")

# Search operations
user_results = api.search_users("photographer")
for user in user_results['users'][:10]:
    user_info = api.get_username_info(user['pk'])
    if user_info['user']['follower_count'] > 1000:
        api.follow(user['pk'])

api.logout()

Install with Tessl CLI

npx tessl i tessl/pypi-instabot

docs

api-access.md

bot-automation.md

file-management.md

index.md

tile.json