# News monitoring

Watch a subject in the news and be told only about what is new. With a scheduled search, or more simply with Monitor.

The job: for a subject you care about, learn about new articles soon after they appear, and never be told about the same one twice. The first half of this guide does it with the Search API and your own scheduler; the second half lets a [Monitor](https://millionshort.com/docs/monitor) do the remembering.

## With a scheduled search

Run a `news` search on a schedule and remember the URLs you have already seen. Every `news` result carries a `published_date`, so `start_date` leaves out anything old, and `exclude_risky` leaves out sites that carry a risk label.

```python
import json
import os
import pathlib
from datetime import date, timedelta

from millionshort import MillionShort

client = MillionShort(api_key=os.environ["MILLIONSHORT_API_KEY"])

QUERY = "central bank interest rate decision"
STATE = pathlib.Path("seen-urls.json")


def check():
    seen = set(json.loads(STATE.read_text())) if STATE.exists() else set()
    since = (date.today() - timedelta(days=3)).isoformat()
    r = client.search(QUERY, sources=["news"], num_results=20, start_date=since, exclude_risky=True)
    fresh = [hit for hit in r.results if hit["url"] not in seen]
    STATE.write_text(json.dumps(sorted(seen | {hit["url"] for hit in r.results})))
    return fresh, r.usage.credits


fresh, credits = check()
for hit in fresh:
    print(hit["published_date"], hit["extra"].get("publisher"), hit["title"], hit["url"])
print(len(fresh), "new;", credits, "credits")
```

```ts
import { existsSync, readFileSync, writeFileSync } from 'node:fs';

import { MillionShort } from 'millionshort';

const client = new MillionShort({ apiKey: process.env.MILLIONSHORT_API_KEY });

const QUERY = 'central bank interest rate decision';
const STATE = 'seen-urls.json';

async function check() {
  const seen = new Set<string>(existsSync(STATE) ? JSON.parse(readFileSync(STATE, 'utf8')) : []);
  const since = new Date(Date.now() - 3 * 24 * 3600 * 1000).toISOString().slice(0, 10);
  const r = await client.search(QUERY, {
    sources: ['news'],
    numResults: 20,
    startDate: since,
    excludeRisky: true,
  });
  const fresh = r.results.filter((hit) => !seen.has(hit.url));
  for (const hit of r.results) seen.add(hit.url);
  writeFileSync(STATE, JSON.stringify([...seen].sort()));
  return { fresh, credits: r.usage?.credits };
}

const { fresh, credits } = await check();
for (const hit of fresh) {
  console.log(hit.published_date, hit.extra.publisher, hit.title, hit.url);
}
console.log(fresh.length, 'new;', credits, 'credits');
```

Run it from a scheduler of your choice, once an hour. The first run reports everything recent; later runs report only what is new.

Make it better:

- **Past the usual outlets.** `remove_top_sites: 1000` leaves out the largest news sites, which is where local and trade coverage shows up.
- **Reactions too.** Add `social` to `sources` for first-hand posts, and read `source` on each result to tell them apart. Each source is one more credit.
- **A beat, not a query.** Run several queries and share one `seen` set.
- **Only certain outlets.** `include_domains` limits the search to the sites you name.

What it costs: one search of `news` with 20 results is 1.5 credits. Hourly, that is 36 credits a day, about $0.04.

## With Monitor

A [query monitor](https://millionshort.com/docs/monitor/parameters) does the remembering for you. It runs the search on an interval and produces an event only when a result URL appears that it has not seen before. On `news` the shortest interval is one hour; on `social` and `hn` it is 15 minutes.

Create it once:

```bash
curl https://api.millionshort.com/v1/monitors \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "kind": "query",
    "name": "rate decisions",
    "query": "central bank interest rate decision",
    "source": "news",
    "top_n": 20,
    "interval_minutes": 60
  }'
```

```python
import os

import requests

r = requests.post(
    "https://api.millionshort.com/v1/monitors",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    json={
        "kind": "query",
        "name": "rate decisions",
        "query": "central bank interest rate decision",
        "source": "news",
        "top_n": 20,
        "interval_minutes": 60
    },
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch('https://api.millionshort.com/v1/monitors', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "kind": "query",
    "name": "rate decisions",
    "query": "central bank interest rate decision",
    "source": "news",
    "top_n": 20,
    "interval_minutes": 60
  }),
});
if (!res.ok) throw new Error(`POST /v1/monitors failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

Then either pull its events when it suits you:

```bash
curl "https://api.millionshort.com/v1/monitors/$MONITOR_ID/events?limit=50" \
  -H "Authorization: Bearer $MILLIONSHORT_API_KEY"
```

```python
import os

import requests

r = requests.get(
    f"https://api.millionshort.com/v1/monitors/{os.environ['MONITOR_ID']}/events?limit=50",
    headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"]},
    timeout=30,
)
r.raise_for_status()
print(r.json()["data"])
```

```ts
const res = await fetch(`https://api.millionshort.com/v1/monitors/${process.env.MONITOR_ID}/events?limit=50`, {
  headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
});
if (!res.ok) throw new Error(`GET /v1/monitors/…/events failed: ${res.status}`);
const { data } = (await res.json()) as { data: unknown };
console.log(data);
```

or register a [webhook](https://millionshort.com/docs/webhooks) and have each `monitor.changed` event delivered, signed, to your own endpoint. The event's `data.new_results` holds the new articles, with `title`, `url`, `site`, `snippet` and `published_date`.

Each check costs 1 credit, and a check that fails is free. An hourly monitor is 24 credits a day.

## Watching a page

News does not always arrive as an article. To watch one page, a press room or a regulator's notices, a `url` monitor reports when the page's text changes and shows what was added and removed. See [Monitor parameters](https://millionshort.com/docs/monitor/parameters).

## Related

- [Freshness and dates](https://millionshort.com/docs/search/freshness): which sources are current.
- The [News](https://millionshort.com/docs/search/sources/news) and [Social](https://millionshort.com/docs/search/sources/social) source pages.
