File size: 5,548 Bytes
06fcc09 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | 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()
|