# Substack Scraper - Posts, Newsletters, Leaderboards & RAG (`infinite_seascape/substack-rag-monitor`) Actor

Substack posts + category leaderboards in one run. Markdown/text, RAG-ready chunks, only-new monitoring, engagement stats. Paywall-safe, no login. From $1 / 1,000 posts.

- **URL**: https://apify.com/infinite_seascape/substack-rag-monitor.md
- **Developed by:** [John Huang](https://apify.com/infinite_seascape) (community)
- **Categories:** AI, News, Social media
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 80.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 post (metadata)s

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Substack Scraper - Posts, Leaderboards & RAG

Turn any Substack newsletter — or the **top newsletters of any category leaderboard** — into clean, **AI-ready** data: engagement stats, full **Markdown / text** for free posts, **RAG chunks with token estimates**, and **only-new-since-last-run** monitoring.

No login. **Paywall-safe:** paid posts get metadata + public preview only — full content is never fetched.

**Pay-per-event (when enabled by the owner):**
| Event | What you pay for | Price |
|---|---|---|
| `post-metadata` (primary) | One post: title, date, reactions, restacks, comments, paywall flag, preview | **$1.00 / 1,000** |
| `post-full-content` | Free post with Markdown/text (+ optional RAG chunks). Instead of metadata, never both | **$2.00 / 1,000** |
| `leaderboard-publication` | One leaderboard publication row (rank, author, public subscriber labels) | **$2.00 / 1,000** |
| `apify-actor-start` | Run start (default) | $0.00005 |

Respects **Max cost per run**. Do not keep `apify-default-dataset-item` enabled (would double-charge).

### Why this Actor

| Capability | This Actor |
|---|---|
| Leaderboard discovery → posts in one run | ✅ paid / trending boards + newest posts |
| Only new posts since last run | ✅ `onlyNew` + `stateKey` |
| RAG-ready chunks + estimated tokens | ✅ `chunkForRag`, `tokensEst` |
| Markdown, plain text, HTML | ✅ `contentFormats` |
| Paywall flag / free-only filter | ✅ paid content never fetched |
| Engagement & reading time | ✅ reactions, restacks, comments, word count |
| Custom domains | ✅ e.g. `www.lennysnewsletter.com` |

### Use cases

AI / RAG knowledge bases · scheduled newsletter alerts · creator & market research · content benchmarking.

### Input examples

Monitor publications (only new, Markdown + chunks):

```json
{ "publications": ["www.lennysnewsletter.com", "astralcodexten"], "maxPostsPerPublication": 20, "chunkForRag": true, "onlyNew": true, "stateKey": "my-ai-feeds" }
```

Top rising Technology newsletters + latest free posts:

```json
{ "leaderboardCategories": ["4"], "leaderboardType": "trending", "leaderboardTop": 10, "maxPostsPerPublication": 3, "onlyFree": true }
```

Category IDs (examples): `4` Technology, `62` Business, `96` Culture — full list: https://substack.com/api/v1/categories

### Output

Two `recordType` values: `post` and `publication`. Dataset views: **Posts**, **Leaderboard publications**, **RAG content**. Run counters in KV `RUN_STATS`. See `sample-output.json`.

### Responsible use

Public `/api/v1/` endpoints only (not disallowed by Substack robots.txt). No login, no paid content, no comment authors, no emails. Default 400 ms delay. Token counts are estimates (~4 chars/token). Not affiliated with Substack Inc. Article copyright stays with authors.

### Run locally

`npm install && npm start` (input: `storage/key_value_stores/default/INPUT.json`) or `apify run`.

### Tutorial: feed Substack newsletters into your RAG app (and keep it fresh)

**Goal:** turn a set of Substack newsletters into Markdown chunks ready for embeddings, then pull only new posts every day.

Actor: **Substack Scraper - Posts, Leaderboards & RAG** (`infinite_seascape/substack-rag-monitor`). Pricing: $1 / 1,000 posts (metadata), $2 / 1,000 free posts with full content, $2 / 1,000 leaderboard rows, + $0.00005 per run start.

#### 1. Pick your sources

Any of these work in `publications`: `lenny`, `@astralcodexten`, `https://name.substack.com`, a custom domain like `www.lennysnewsletter.com`, a `/p/` post link, or `substack.com/@handle`.

Don't know which newsletters to follow? Discover them:

```json
{ "leaderboardCategories": ["4"], "leaderboardType": "trending", "leaderboardTop": 10, "maxPostsPerPublication": 0 }
```

→ the 10 rising Technology newsletters with rank and public subscriber labels (category IDs: https://substack.com/api/v1/categories).

#### 2. Get RAG-ready content

```json
{
  "publications": ["www.lennysnewsletter.com", "@astralcodexten"],
  "maxPostsPerPublication": 30,
  "onlyFree": true,
  "contentFormats": ["markdown"],
  "chunkForRag": true,
  "chunkTokens": 500
}
```

Each free post includes `markdown`, `tokensEst` and `chunks: [{ index, text, tokensEst }]`. Paid posts are never fetched in full — with `onlyFree: true` they're skipped; otherwise you get metadata + public preview only.

#### 3. Load into a vector DB (Python sketch)

```python
from apify_client import ApifyClient
client = ApifyClient("<YOUR_TOKEN>")
run = client.actor("infinite_seascape/substack-rag-monitor").call(run_input={...})
for post in client.dataset(run["defaultDatasetId"]).iterate_items():
    if post["recordType"] != "post" or not post.get("chunks"):
        continue
    for c in post["chunks"]:
        upsert(id=f'{post["postId"]}-{c["index"]}', text=c["text"],
               metadata={"url": post["url"], "title": post["title"], "date": post["postDate"]})
```

(`upsert` = your Pinecone / Qdrant / pgvector / Chroma call.)

#### 4. Keep it fresh

Add `"onlyNew": true, "stateKey": "my-kb"` and schedule daily (Console → Schedules, cron `0 6 * * *`). Each run returns only posts not seen before for that `stateKey`, so you embed — and pay for — new content only.

#### 5. Control spend

Set **Max cost per run**. The Actor stops cleanly at the limit and, if there's budget for metadata but not full content, it falls back to the cheaper metadata row.

#### Notes

- Uses public Substack JSON endpoints not disallowed by robots.txt; no login, no comments' author data, no emails.
- Token counts are estimates (~4 characters per token).
- Respect authors' copyright when reusing content. Not affiliated with Substack Inc.

# Actor input Schema

## `publications` (type: `array`):

Substack subdomains (e.g. 'lenny'), URLs or custom domains (e.g. 'www.lennysnewsletter.com'). Also accepts @handle, substack.com/@handle and /p/ post links.

## `leaderboardCategories` (type: `array`):

Substack category IDs to discover top newsletters, e.g. 4 = Technology, 62 = Business, 96 = Culture. Leave empty to skip.

## `leaderboardType` (type: `string`):

'paid' = bestsellers, 'trending' = rising.

## `leaderboardTop` (type: `integer`):

How many publications to take from each leaderboard.

## `includePublicationRows` (type: `boolean`):

Push one row per leaderboard publication (rank, subscriber labels).

## `maxPostsPerPublication` (type: `integer`):

Newest posts per publication. 0 = publications only.

## `since` (type: `string`):

Optional, YYYY-MM-DD.

## `onlyFree` (type: `boolean`):

Skip paywalled posts entirely (paywalled posts are otherwise listed with metadata + public preview only).

## `includeContent` (type: `boolean`):

Fetch full body for public posts. Paid content is never fetched.

## `contentFormats` (type: `array`):

Any of: markdown, text, html.

## `chunkForRag` (type: `boolean`):

Split markdown into chunks with estimated token counts, ready for embeddings.

## `chunkTokens` (type: `integer`):

Target chunk size; tokens estimated as chars/4.

## `onlyNew` (type: `boolean`):

Remember posts already returned (per state key) and output only new ones. Ideal with Schedules.

## `stateKey` (type: `string`):

Separate 'only new' memory for different monitors.

## `requestDelayMs` (type: `integer`):

Politeness delay.

## Actor input object example

```json
{
  "publications": [
    "www.lennysnewsletter.com",
    "@astralcodexten"
  ],
  "leaderboardCategories": [
    "4"
  ],
  "leaderboardType": "paid",
  "leaderboardTop": 5,
  "includePublicationRows": true,
  "maxPostsPerPublication": 5,
  "onlyFree": false,
  "includeContent": true,
  "contentFormats": [
    "markdown",
    "text"
  ],
  "chunkForRag": false,
  "chunkTokens": 500,
  "onlyNew": false,
  "stateKey": "default",
  "requestDelayMs": 400
}
```

# Actor output Schema

## `results` (type: `string`):

Posts and leaderboard publications in the default dataset (Posts view selected).

## `runStats` (type: `string`):

Counts of posts, publications, skipped and paywalled items.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "publications": [
        "www.lennysnewsletter.com",
        "@astralcodexten"
    ],
    "leaderboardCategories": [
        "4"
    ],
    "leaderboardTop": 5,
    "maxPostsPerPublication": 5,
    "contentFormats": [
        "markdown",
        "text"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("infinite_seascape/substack-rag-monitor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "publications": [
        "www.lennysnewsletter.com",
        "@astralcodexten",
    ],
    "leaderboardCategories": ["4"],
    "leaderboardTop": 5,
    "maxPostsPerPublication": 5,
    "contentFormats": [
        "markdown",
        "text",
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("infinite_seascape/substack-rag-monitor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "publications": [
    "www.lennysnewsletter.com",
    "@astralcodexten"
  ],
  "leaderboardCategories": [
    "4"
  ],
  "leaderboardTop": 5,
  "maxPostsPerPublication": 5,
  "contentFormats": [
    "markdown",
    "text"
  ]
}' |
apify call infinite_seascape/substack-rag-monitor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,infinite_seascape/substack-rag-monitor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/2jwWnBaixf6hejXMd/builds/D3pV7ei3caeFESymE/openapi.json
