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import json
|
| 4 |
+
import random
|
| 5 |
+
import logging
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from instagrapi import Client
|
| 8 |
+
from instagrapi.exceptions import LoginRequired
|
| 9 |
+
|
| 10 |
+
# Sane defaults for safer automation
|
| 11 |
+
POLL_INTERVAL_SECONDS = 600 # Check every 10 minutes
|
| 12 |
+
DM_DELAY_SECONDS_MIN = 30 # Wait at least 30s before sending DM
|
| 13 |
+
DM_DELAY_SECONDS_MAX = 120 # Random delay up to 2m
|
| 14 |
+
|
| 15 |
+
# Setup logging
|
| 16 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Load environment variables
|
| 20 |
+
load_dotenv()
|
| 21 |
+
USERNAME = os.getenv("IG_USERNAME")
|
| 22 |
+
PASSWORD = os.getenv("IG_PASSWORD")
|
| 23 |
+
MESSAGE_TEXT = os.getenv("IG_MESSAGE_TEXT", "Thanks for following!")
|
| 24 |
+
|
| 25 |
+
FOLLOWERS_FILE = "followers.json"
|
| 26 |
+
|
| 27 |
+
def login(cl):
|
| 28 |
+
"""Handles login and 2FA if needed."""
|
| 29 |
+
logger.info(f"Attempting to login as {USERNAME}...")
|
| 30 |
+
try:
|
| 31 |
+
cl.login(USERNAME, PASSWORD)
|
| 32 |
+
logger.info("Login successful!")
|
| 33 |
+
except Exception as e:
|
| 34 |
+
logger.error(f"Login failed: {e}")
|
| 35 |
+
raise e
|
| 36 |
+
|
| 37 |
+
def load_known_followers():
|
| 38 |
+
"""Loads the set of known follower user IDs from a JSON file."""
|
| 39 |
+
if os.path.exists(FOLLOWERS_FILE):
|
| 40 |
+
with open(FOLLOWERS_FILE, "r") as f:
|
| 41 |
+
try:
|
| 42 |
+
data = json.load(f)
|
| 43 |
+
return set(data.keys()) # We store as dict {id: username}
|
| 44 |
+
except json.JSONDecodeError:
|
| 45 |
+
return set()
|
| 46 |
+
return set()
|
| 47 |
+
|
| 48 |
+
def save_known_followers(followers_dict):
|
| 49 |
+
"""Saves the current followers to a JSON file."""
|
| 50 |
+
# Load existing to merge updates (though we usually have full state)
|
| 51 |
+
existing_data = {}
|
| 52 |
+
if os.path.exists(FOLLOWERS_FILE):
|
| 53 |
+
with open(FOLLOWERS_FILE, "r") as f:
|
| 54 |
+
try:
|
| 55 |
+
existing_data = json.load(f)
|
| 56 |
+
except:
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
existing_data.update(followers_dict)
|
| 60 |
+
|
| 61 |
+
with open(FOLLOWERS_FILE, "w") as f:
|
| 62 |
+
json.dump(existing_data, f, indent=2)
|
| 63 |
+
|
| 64 |
+
def main():
|
| 65 |
+
if not USERNAME or not PASSWORD:
|
| 66 |
+
logger.error("Please set IG_USERNAME and IG_PASSWORD in .env file")
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
cl = Client()
|
| 70 |
+
# It takes time to mimic a real phone, so set delays
|
| 71 |
+
cl.delay_range = [1, 3]
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
login(cl)
|
| 75 |
+
except Exception:
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
# Initial State Loading
|
| 79 |
+
known_followers = load_known_followers()
|
| 80 |
+
|
| 81 |
+
# On first run, we might want to just fetch current state and NOT send DMs to everyone.
|
| 82 |
+
# If file doesn't exist or is empty, we assume it's the first run.
|
| 83 |
+
first_run = len(known_followers) == 0
|
| 84 |
+
|
| 85 |
+
if first_run:
|
| 86 |
+
logger.info("First run detected. Fetching current followers to build baseline...")
|
| 87 |
+
else:
|
| 88 |
+
logger.info(f"Loaded {len(known_followers)} known followers.")
|
| 89 |
+
|
| 90 |
+
while True:
|
| 91 |
+
try:
|
| 92 |
+
logger.info("Fetching current followers...")
|
| 93 |
+
# fetch_followers returns a dict of {user_id: user_object}
|
| 94 |
+
# Note: For very large accounts, this might need pagination or be slow.
|
| 95 |
+
# user_id is the account ID
|
| 96 |
+
current_followers = cl.user_followers(cl.user_id)
|
| 97 |
+
|
| 98 |
+
# Create a simple dict for storage {id: username}
|
| 99 |
+
current_followers_simple = {uid: user.username for uid, user in current_followers.items()}
|
| 100 |
+
current_ids = set(current_followers_simple.keys())
|
| 101 |
+
|
| 102 |
+
if first_run:
|
| 103 |
+
# Just save the state and continue
|
| 104 |
+
save_known_followers(current_followers_simple)
|
| 105 |
+
known_followers = current_ids
|
| 106 |
+
logger.info(f"Baseline established with {len(current_ids)} followers.")
|
| 107 |
+
first_run = False
|
| 108 |
+
else:
|
| 109 |
+
# Determine new followers
|
| 110 |
+
new_follower_ids = current_ids - known_followers
|
| 111 |
+
|
| 112 |
+
if new_follower_ids:
|
| 113 |
+
logger.info(f"Found {len(new_follower_ids)} new followers!")
|
| 114 |
+
|
| 115 |
+
for uid in new_follower_ids:
|
| 116 |
+
username = current_followers_simple.get(uid, "Unknown")
|
| 117 |
+
logger.info(f"New follower: {username} ({uid})")
|
| 118 |
+
|
| 119 |
+
# Send DM
|
| 120 |
+
logger.info(f"Sending DM to {username}...")
|
| 121 |
+
try:
|
| 122 |
+
cl.direct_send(MESSAGE_TEXT, user_ids=[uid])
|
| 123 |
+
logger.info(f"DM sent to {username}.")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
logger.error(f"Failed to send DM to {username}: {e}")
|
| 126 |
+
|
| 127 |
+
# Wait to avoid spam limits
|
| 128 |
+
delay = random.randint(DM_DELAY_SECONDS_MIN, DM_DELAY_SECONDS_MAX)
|
| 129 |
+
logger.info(f"Sleeping {delay}s before next action...")
|
| 130 |
+
time.sleep(delay)
|
| 131 |
+
|
| 132 |
+
# Update known followers
|
| 133 |
+
save_known_followers(current_followers_simple)
|
| 134 |
+
known_followers = current_ids
|
| 135 |
+
else:
|
| 136 |
+
logger.info("No new followers found.")
|
| 137 |
+
|
| 138 |
+
# Sleep before next poll
|
| 139 |
+
logger.info(f"Sleeping for {POLL_INTERVAL_SECONDS}s...")
|
| 140 |
+
time.sleep(POLL_INTERVAL_SECONDS)
|
| 141 |
+
|
| 142 |
+
except LoginRequired:
|
| 143 |
+
logger.warning("Session expired. Relogging...")
|
| 144 |
+
login(cl)
|
| 145 |
+
except Exception as e:
|
| 146 |
+
logger.error(f"An error occurred in polling loop: {e}")
|
| 147 |
+
logger.info("Retrying in 60s...")
|
| 148 |
+
time.sleep(60)
|
| 149 |
+
|
| 150 |
+
if __name__ == "__main__":
|
| 151 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
instagrapi
|
| 2 |
+
python-dotenv
|
walkthrough.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Instagram Bot Setup Guide
|
| 2 |
+
|
| 3 |
+
The Instagram automation agent has been generated. Follow these steps to get it running.
|
| 4 |
+
|
| 5 |
+
## 1. Setup Environment
|
| 6 |
+
1. Open the file `.env.example` and rename it to `.env` (or create a new `.env` file).
|
| 7 |
+
2. Fill in your Instagram credentials:
|
| 8 |
+
```bash
|
| 9 |
+
IG_USERNAME=your_actual_username
|
| 10 |
+
IG_PASSWORD=your_actual_password
|
| 11 |
+
IG_MESSAGE_TEXT=Hi! Thanks for following. Check out my link...
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
## 2. Install Dependencies
|
| 15 |
+
Open a terminal in the project directory and run:
|
| 16 |
+
```bash
|
| 17 |
+
pip install -r requirements.txt
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
## 3. Run the Bot
|
| 21 |
+
```bash
|
| 22 |
+
python main.py
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## How it works
|
| 26 |
+
1. **First Run**: It will just fetch your current followers and save them to `followers.json`. It **will not** sends DMs to existing followers.
|
| 27 |
+
2. **Subsequent Runs**: It checks every 10 minutes. If it finds a *new* follower (someone not in the JSON file), it sends them the DM and adds them to the list.
|
| 28 |
+
|
| 29 |
+
> [!WARNING]
|
| 30 |
+
> - **Two-Factor Authentication (2FA)**: If you have 2FA enabled, `instagrapi` might ask for the code in the terminal or fail. It is recommended to use a dedicated account or disable 2FA for the bot if possible (though less secure).
|
| 31 |
+
> - **Safety**: Do not decrease the polling interval (600s). Fast actions can lead to temporary or permanent bans.
|