import os import time import json import random import logging from dotenv import load_dotenv from instagrapi import Client from instagrapi.exceptions import LoginRequired # Sane defaults for safer automation POLL_INTERVAL_SECONDS = 600 # Check every 10 minutes DM_DELAY_SECONDS_MIN = 30 # Wait at least 30s before sending DM DM_DELAY_SECONDS_MAX = 120 # Random delay up to 2m # Setup logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Load environment variables load_dotenv() USERNAME = os.getenv("IG_USERNAME") PASSWORD = os.getenv("IG_PASSWORD") MESSAGE_TEXT = os.getenv("IG_MESSAGE_TEXT", "Thanks for following!") FOLLOWERS_FILE = "followers.json" def login(cl): """Handles login and 2FA if needed.""" logger.info(f"Attempting to login as {USERNAME}...") try: cl.login(USERNAME, PASSWORD) logger.info("Login successful!") except Exception as e: logger.error(f"Login failed: {e}") raise e def load_known_followers(): """Loads the set of known follower user IDs from a JSON file.""" if os.path.exists(FOLLOWERS_FILE): with open(FOLLOWERS_FILE, "r") as f: try: data = json.load(f) return set(data.keys()) # We store as dict {id: username} except json.JSONDecodeError: return set() return set() def save_known_followers(followers_dict): """Saves the current followers to a JSON file.""" # Load existing to merge updates (though we usually have full state) existing_data = {} if os.path.exists(FOLLOWERS_FILE): with open(FOLLOWERS_FILE, "r") as f: try: existing_data = json.load(f) except: pass existing_data.update(followers_dict) with open(FOLLOWERS_FILE, "w") as f: json.dump(existing_data, f, indent=2) def main(): if not USERNAME or not PASSWORD: logger.error("Please set IG_USERNAME and IG_PASSWORD in .env file") return cl = Client() # It takes time to mimic a real phone, so set delays cl.delay_range = [1, 3] try: login(cl) except Exception: return # Initial State Loading known_followers = load_known_followers() # On first run, we might want to just fetch current state and NOT send DMs to everyone. # If file doesn't exist or is empty, we assume it's the first run. first_run = len(known_followers) == 0 if first_run: logger.info("First run detected. Fetching current followers to build baseline...") else: logger.info(f"Loaded {len(known_followers)} known followers.") while True: try: logger.info("Fetching current followers...") # fetch_followers returns a dict of {user_id: user_object} # Note: For very large accounts, this might need pagination or be slow. # user_id is the account ID current_followers = cl.user_followers(cl.user_id) # Create a simple dict for storage {id: username} current_followers_simple = {uid: user.username for uid, user in current_followers.items()} current_ids = set(current_followers_simple.keys()) if first_run: # Just save the state and continue save_known_followers(current_followers_simple) known_followers = current_ids logger.info(f"Baseline established with {len(current_ids)} followers.") first_run = False else: # Determine new followers new_follower_ids = current_ids - known_followers if new_follower_ids: logger.info(f"Found {len(new_follower_ids)} new followers!") for uid in new_follower_ids: username = current_followers_simple.get(uid, "Unknown") logger.info(f"New follower: {username} ({uid})") # Send DM logger.info(f"Sending DM to {username}...") try: cl.direct_send(MESSAGE_TEXT, user_ids=[uid]) logger.info(f"DM sent to {username}.") except Exception as e: logger.error(f"Failed to send DM to {username}: {e}") # Wait to avoid spam limits delay = random.randint(DM_DELAY_SECONDS_MIN, DM_DELAY_SECONDS_MAX) logger.info(f"Sleeping {delay}s before next action...") time.sleep(delay) # Update known followers save_known_followers(current_followers_simple) known_followers = current_ids else: logger.info("No new followers found.") # Sleep before next poll logger.info(f"Sleeping for {POLL_INTERVAL_SECONDS}s...") time.sleep(POLL_INTERVAL_SECONDS) except LoginRequired: logger.warning("Session expired. Relogging...") login(cl) except Exception as e: logger.error(f"An error occurred in polling loop: {e}") logger.info("Retrying in 60s...") time.sleep(60) if __name__ == "__main__": main()