# YouTube Comment Archive & Delta Feed (`mehdi_badawi/youtube-comment-archive`) Actor

Track YouTube comment additions, edits, and removals across repeated runs with stable identities. Seeded demo is synthetic; incomplete live results never prove deletion.

- **URL**: https://apify.com/mehdi\_badawi/youtube-comment-archive.md
- **Developed by:** [Mehdi Badawi](https://apify.com/mehdi_badawi) (community)
- **Categories:** Videos, Social media
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 useful archived comment deltas

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

## YouTube Comment Archive & Delta Feed

Track YouTube comment additions, edits, and removals across repeated runs with
stable comment identities. The result is an append-only change feed rather than
another one-time comment export.

### Start in 30 seconds

1. Select **Try for free** and run the seeded multi-cycle demo.
2. Switch to bounded live mode or supply your own comment observations.
3. Reuse the named state store to compare later runs.

**Price:** $0.0005 per useful live added, modified, or explicitly removed
comment, plus a $0.00005 start event. Unchanged, unavailable, failed, and demo
results are free.

Seeded mode is synthetic. Live HTML collection is experimental and incomplete
results never prove that a comment was deleted.

### Highlights

- **Append-Only Stable Identity**: Every comment receives a canonical composite key `youtube/<videoId>/<commentId>` that prevents duplicates and tracks historical appearance across cycles.
- **Deterministic Delta Engine**: Classifies every comment in relation to prior state:
  - `added`: Newly posted comment.
  - `modified`: Text edited or like/reply metrics updated.
  - `unchanged`: Verified active with identical text and metrics.
  - `removed`: Comment deleted or removed since prior successful check.
  - `unavailable`: External access to video failed; state is held without false modifications.
- **Honest Failure Semantics**: Network failures, private/removed videos, or disabled comments report explicit `unavailable` or `unknown` statuses—never false "unchanged" and never false "removed".
- **Credential-Free Seeded Demo**: Runs out of the box with zero credentials, zero network access, and writes a non-empty dataset in seconds.

### Quickstart

#### Run locally

To run the credential-free seeded demo:

```bash
npm start
```

This completes in under 5 seconds, loads multi-cycle seeded test fixtures, executes delta evaluation, and writes the results to the Apify dataset and KeyValueStore.

#### Run tests

All unit, behavioral, delta precision, and error-handling tests run with Node's native test runner:

```bash
npm test
```

### Input Configuration

See `.actor/input_schema.json` for full JSON schema definitions.

| Field | Type | Default | Description |
|---|---|---|---|
| `targetUrls` | array | `["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]` | Target YouTube video URLs or video IDs |
| `maxCommentsPerTarget` | integer | `100` | Maximum comments to inspect per video |
| `mode` | string | `"seeded"` | `"seeded"` for offline deterministic demo, `"live"` for bounded public fetches |
| `stateStoreName` | string | mode-specific | Named KeyValueStore for persistence (`null` disables persistence); seeded and live defaults are isolated |
| `emitAll` | boolean | `true` | When true, emits all comments; when false, emits only changed deltas |
| `priorState` | object | `null` | Optional explicit prior state object for replay/testing |

### Output Datasets and Storage

- **Dataset**: Formatted rows following `.actor/dataset_schema.json`. Each row contains `key`, `commentId`, `videoId`, `author`, `text`, `likeCount`, `replyCount`, `delta`, `status`, `targetStatus`, `firstSeenAt`, `lastSeenAt`, and `changes`.
- **KeyValueStore `OUTPUT`**: Run envelope detailing execution timestamp, run status (`ok`, `degraded`, `failed`), summary delta counts, and per-target health.
- **KeyValueStore `STATE`**: Durable state record persisted in the configured store for subsequent runs.

### Architecture

- `src/main.mjs`: Actor platform entrypoint and adapter.
- `src/core/identity.mjs`: Pure URL normalization and composite key generation.
- `src/core/archive.mjs`: Pure deterministic delta evaluator and state transitions.
- `src/fetcher/youtube.mjs`: Bounded read-only fetcher with explicit failure classification.
- `fixtures/seeded_corpus.json`: Curated multi-cycle golden fixtures for deterministic testing.

Public comments still contain author data. Set a retention period appropriate
to your use, honor deletion/data-rights requests, and delete the named store and
datasets when that period ends. Use one writer per target scope. No proxy,
cookies, login, or access-control bypass is included. Support owner: Mehdi
Badawi through the Apify Store support channel, with an initial-response target
of two business days.

# Actor input Schema

## `targetUrls` (type: `array`):

List of YouTube video URLs (e.g. https://www.youtube.com/watch?v=dQw4w9WgXcQ) or video IDs to archive comments from.

## `maxCommentsPerTarget` (type: `integer`):

Maximum number of comments to archive per target video in one run.

## `mode` (type: `string`):

Execution mode: 'seeded' for credential-free deterministic offline demo using curated comment snapshots; 'live' for bounded public read-only fetches.

## `stateStoreName` (type: `string`):

Named KeyValueStore used to persist longitudinal comment state across runs. By default, seeded and live runs use separate stores. Set to null to disable cross-run persistence.

## `emitAll` (type: `boolean`):

When true, emits all known comments for target videos (including unchanged). When false, emits only active deltas (added, modified, removed).

## `priorState` (type: `object`):

Optional prior archive state object for manual replay, testing, or pipeline debugging.

## Actor input object example

```json
{
  "targetUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ],
  "maxCommentsPerTarget": 100,
  "mode": "seeded",
  "emitAll": true
}
```

# Actor output Schema

## `comments` (type: `string`):

Normalized comment rows in the default dataset.

## `runOutput` (type: `string`):

Archive summary, target status, and delta counts.

## `state` (type: `string`):

Longitudinal comment archive state.

# 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 = {
    "targetUrls": [
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("mehdi_badawi/youtube-comment-archive").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 = { "targetUrls": ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"] }

# Run the Actor and wait for it to finish
run = client.actor("mehdi_badawi/youtube-comment-archive").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 '{
  "targetUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ]
}' |
apify call mehdi_badawi/youtube-comment-archive --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,mehdi_badawi/youtube-comment-archive"
        }
    }
}
```

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/XRe5kmSIaFfh3bjNi/builds/HW2kElVdJfiHNJ32t/openapi.json
