Skip to content

Repository files navigation

FastGram — Instagram Outreach Automation MVP 🚀

A self-hosted, safety-first Instagram DM outreach pipeline built with FastAPI and n8n. Manages user interactions, tracks replies, classifies leads, and protects accounts through gradient warm-up, proxy rotation, and automatic pause/resume logic.

PythonFastAPIn8nDockerLicenseBuild


⚠️ Disclaimer

This project interacts with Instagram via the unofficial instagrapi library. Use at your own risk. Automated messaging may violate Instagram's Terms of Service. The authors are not responsible for account bans or other consequences.


✨ Features

  • Automated DM outreach — sends batched Instagram direct messages to contacts sourced from Google Sheets, respecting configurable daily limits
  • Gradient account warm-up — automatically ramps daily message limits from 5 to 50 over a 15-day schedule to reduce ban risk on new accounts
  • Proxy rotation — integrates with a 4G/mobile proxy provider REST API; rotates IP after every 50 messages or 24 hours
  • Human-like delays — Gaussian-distributed inter-message delays and typing-speed simulation to mimic organic behavior
  • Reply tracking & lead classification — polls Instagram inbox every 30 minutes, classifies responses as Interested / Not Interested / Unclear, and writes tags back to Google Sheets
  • Auto-pause & auto-resume — detects ChallengeRequired / LoginRequired errors, pauses outreach for 24 hours, validates session health before resuming
  • Telegram alerts — instant notifications on account block events and new interested leads via n8n webhook workflows
  • API key authentication — all FastAPI endpoints protected by X-API-Key header
  • Encrypted session storage — Instagram session persisted to an encrypted JSON file
  • Fully containerized — FastAPI backend and n8n orchestrator run in Docker Compose on a shared internal network

🛠 Tech Stack

LayerTechnology
API BackendFastAPI + Uvicorn
Instagram Libraryinstagrapi
Workflow Orchestratorn8n (self-hosted)
Data LayerGoogle Sheets via gspread
ConfigurationPydantic Settings
ContainerizationDocker + Docker Compose
Dependency ManagementPoetry
Linting & FormattingRuff
State PersistenceJSON file (MVP); Redis-compatible for production
Proxy4G Mobile Proxy with provider REST API rotation

📐 Architecture Overview

┌─────────────────────────────────────────────────────┐
│ n8n (port 5679) │
│ │
│ ┌─────────────────┐ ┌──────────────────────────┐ │
│ │ Outreach Trigger │ │ Reply Polling (30 min) │ │
│ │ (cron 10:00) │ │ → FastAPI check-replies │ │
│ └────────┬────────┘ └──────────────┬───────────┘ │
│ │ │ │
│ ┌────────▼────────┐ ┌──────────────▼───────────┐ │
│ │ Warmup Trigger │ │ Telegram Lead Alert │ │
│ │ (cron 00:01) │ │ (if interested > 0) │ │
│ └────────┬────────┘ └──────────────────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Block Alert │ │
│ │ (webhook POST) │ │
│ └─────────────────┘ │
└──────────────────────┬──────────────────────────────┘
│ HTTP (internal network)
┌──────────────────────▼──────────────────────────────┐
│ FastAPI Backend (port 8003) │
│ │
│ OutreachEngine │ ReplyTracker │ WarmupManager │
│ PauseManager │ ProxyRotator │ SheetsClient │
└──────────────────────────────────────────────────────┘

📦 Installation

Prerequisites

  • Docker & Docker Compose
  • A Google Cloud service account with Sheets API enabled (credentials.json)
  • A 4G/mobile proxy with REST API access
  • A Telegram bot token and chat ID for alerts

1. Clone the repository

git clone https://github.com/PyDevDeep/FastGram-Outreach.git
cd fastgram

2. Create environment file

cp .env.example .env

Edit .env with your credentials:

# InstagramINSTAGRAM_USERNAME=your_usernameINSTAGRAM_PASSWORD=your_password# SecurityAPI_KEY=your_secure_api_key_hereSESSION_ENCRYPTION_KEY=your_32_byte_key# Google SheetsGOOGLE_SHEETS_ID=your_spreadsheet_idGOOGLE_APPLICATION_CREDENTIALS=/app/credentials.json# ProxyPROXY_URL=http://user:pass@host:portPROXY_API_URL=https://api.your-proxy-provider.comPROXY_API_KEY=your_proxy_api_key# n8n WebhooksN8N_WEBHOOK_URL=http://fastgram_n8n:5678/webhook/alert-block# LimitsDAILY_MESSAGE_LIMIT=20MIN_DELAY_SECONDS=30MAX_DELAY_SECONDS=60

3. Place Google credentials

cp /path/to/your/credentials.json ./credentials.json

4. Start services

docker compose up -d

API is available at http://localhost:8003. n8n UI is available at http://localhost:5679.


▶️ Usage

Import n8n Workflows

In the n8n UI, import the four workflows from n8n/workflows/:

FilePurpose
outreach_trigger.jsonDaily cron at 10:00 — starts outreach batch
warmup_trigger.jsonDaily cron at 00:01 — increments warm-up day
reply_polling.jsonEvery 30 min — polls replies and alerts on leads
alert_on_block.jsonWebhook — fires Telegram alert on account block

Set your YOUR_TELEGRAM_CHAT_ID in the Telegram Alert nodes.

API Endpoints

All requests require the header: X-API-Key: your_secure_api_key_here

# Start outreach batch
POST http://localhost:8003/outreach/start
Content-Type: application/json
{"dry_run": false}
# Check for new replies and classify leads
GET http://localhost:8003/tracking/check-replies
# Increment warm-up day counter (also called by n8n cron)
POST http://localhost:8003/outreach/warmup/increment
# Health check
GET http://localhost:8003/health
# Warmup status
GET http://localhost:8003/admin/warmup-status
# Account health check
GET http://localhost:8003/admin/account-health
# Manual resume after pause
POST http://localhost:8003/admin/resume-pause

Google Sheets Structure

The Contacts sheet must contain these columns:

ColumnDescription
Instagram UsernameTarget account handle (without @)
Instagram User IDNumeric user ID (populated after first contact)
StatusPending / Sent / Replied / Error
TagInterested / Not Interested / Unclear (set by ReplyTracker)

Validate connections before first run

# Test Instagram authentication
docker compose exec api python scripts/test_instagram.py
# Test Google Sheets access
docker compose exec api python scripts/test_sheets.py

🔥 Warm-up Schedule

DaysDaily Message Limit
1–35
4–610
7–915
10–1225
13–1435
15+50 (warm-up deactivates)

💰 Estimated Monthly Cost (MVP)

ResourceCost
VPS (n8n + FastAPI, e.g. Hetzner CX22)$5–10
4G Mobile Proxy (1 slot with rotation)$30–80
Google Sheets APIFree
Domain + SSL (optional)$0–5
Total$35–95

🔒 Security Notes

  • The X-API-Key header is required on all endpoints; unauthorized requests return HTTP 401
  • Instagram credentials and session data are never exposed via the API
  • credentials.json is mounted read-only inside the container
  • Pre-commit hooks block accidental commits of private keys (via detect-private-key)
  • sessions/session.json and .env are listed in .gitignore

🗺️ Roadmap

  • Phase 1 — PostgreSQL migration (replace Google Sheets)
  • Phase 2 — Sentry integration for error tracking
  • Phase 3 — LLM-based reply classification (replace keyword matching)
  • Phase 4 — Playwright fallback for API-blocked scenarios

🧪 Testing

The project ships with 82 tests across 9 modules and achieves 84% overall coverage.

Run the full test suite with coverage report:

poetry run pytest --cov=app --cov-report=term-missing

Latest results (Python 3.13.11):

tests/test_fastapi.py 11 passed
tests/test_instagram_client.py 17 passed
tests/test_notification_service.py 3 passed
tests/test_outreach_engine.py 13 passed
tests/test_pause_manager.py 6 passed
tests/test_proxy_rotator.py 11 passed
tests/test_reply_tracker.py 5 passed
tests/test_sheets_client.py 11 passed
tests/test_warmup_manager.py 5 passed
─────────────────────────────────────────────
82 passed in 2.72s

Coverage summary:

 Name Stmts Miss Cover
-----------------------------------------------------------
+app/config.py 30 0 100%+app/services/notification_service.py 20 0 100%+app/services/proxy_rotator.py 88 0 100%+app/services/reply_tracker.py 63 1 98%+app/services/warmup_manager.py 56 1 98%+app/services/pause_manager.py 67 5 93%
app/routers/health.py 20 2 90%
app/services/outreach_engine.py 140 18 87%
app/services/sheets_client.py 134 19 86%
app/routers/outreach.py 59 10 83%
app/dependencies.py 43 9 79%
app/routers/tracking.py 19 5 74%
-app/services/instagram_client.py 220 72 67%-app/utils/delay.py 25 10 60%-app/main.py 29 13 55%
-----------------------------------------------------------
TOTAL 1028 165 84%

instagram_client.py (67%) and main.py (55%) have lower coverage due to live Instagram API calls and app-startup side effects that require integration-level testing.


🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Install pre-commit hooks: pre-commit install
  4. Make changes and ensure linting passes: ruff check . && ruff format .
  5. Submit a pull request with a clear description

📄 License

[INSERT LICENSE TYPE]

About

Automated Instagram profile assistant and lead tracking pipeline built with FastAPI, n8n, and Docker.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages