# 내 알림 스트림

토픽별 전체 이벤트와 별도로, **실제로 나에게 보내진** 알림을 그대로 받을 수 있습니다. 웹에서 설정한 Bark·위챗 워크 등 채널이 받는 것과 같으며 소스·키워드·알림 언어로 필터링됩니다. 우리 알림을 직접 만든 봇이나 워크플로에 연결할 때 쓰세요.

> Source: https://tokenearly.com/ko/developers/my-alerts · Docs index: https://tokenearly.com/ko/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json

## 두 가지 데이터

|  | 토픽 이벤트(일반 스트림) | 내 알림(이 페이지) |
|---|---|---|
| 내용 | 구독 토픽의 **모든** 메시지, 개인 설정과 무관 | **나에게 보내진** 것만: 웹에서 설정한 소스 스위치, 키워드, 알림 언어, 플랜 지연으로 필터링 |
| 채널과의 관계 | 무관 | Bark·위챗 워크 등 채널이 받는 것과 한 건씩 동일 |
| 형식 | 구조화 이벤트, `op = "event"`([이벤트 형식](https://tokenearly.com/ko/developers/events) 참고) | 푸시 텍스트 + 일부 구조화 필드, `op = "alert"` |
| 언어 | 한 이벤트에 중·영·한 제목, 보완되면 새 리비전으로 다시 푸시 | 알림 언어 기준: 원문이 다른 언어면 원문을 먼저(`label = "original"`), 번역이 오면 추가로 한 건(`followup = true`) |
| 구독 방법 | `topics=announcement.binance,news.*` 등(쉼표로 구분, 자유롭게 조합) | `topics=my_alerts`(특수 토픽, `*`에 포함되지 않음) |
| 끊긴 뒤 | `after`로 재연결하면 서버가 재전송 | 스트림은 재전송하지 않음, `GET /v1/alerts?after=`로 따라잡기 |
| 보관 | 플랜의 기록 일수 | 최근 7일 |

> 한 WebSocket 연결에서 함께 구독할 수 있으며(`topics=my_alerts,announcement.*`) `op`로 구분합니다: `event`는 토픽 이벤트, `alert`은 내 알림. 같은 공지가 이벤트와 내 알림으로 모두 올 수 있으며 ID가 다르고 `ref.event_id`가 해당 이벤트를 가리킵니다.

## 켜기

1. 웹의 전역 알림 관리 → 알림 채널에서 「개발자 API」를 켭니다. 꺼져 있으면 새 내 알림이 생성되지 않습니다(`welcome.my_alerts.channel_enabled`와 REST 응답의 `channel_enabled`로 확인).
2. 웹에서 평소처럼 소스, 키워드, 알림 언어를 설정합니다. 내 알림은 이 설정을 그대로 따르며 소스마다 「개발자 API」를 체크할 필요가 없습니다: 나에게 푸시가 한 건 가면 API도 같은 것을 받습니다.
3. 아무 API 키로 `wss://api.tokenearly.com/v1/stream?topics=my_alerts`에 연결하거나 [GET /v1/alerts](https://tokenearly.com/ko/developers/rest/alerts)를 호출합니다. 같은 계정의 모든 키가 같은 내 알림을 봅니다. `my_alerts`는 스트림에서만 특수 토픽이며, REST의 `GET /v1/events?topics=my_alerts`는 이를 없는 토픽으로 보고 `access.unknown`에 넣으므로 `GET /v1/alerts`를 쓰세요.

> 내 알림은 계정의 플랜 지연을 따릅니다: 유료는 실시간, 무료는 다른 채널과 같이 지연 전송.

## 메시지 형식

스트림에서는 `{"op": "alert", "alert": {...}}`, REST는 `{"alerts": [...]}`이며 객체는 같습니다.

| 필드 | 설명 |
|---|---|
| `id` | 내 알림 ID(24자리 16진수, 시간순 증가). `after` / `before` 커서로 사용하며 이벤트 ID와는 다릅니다. |
| `category` | 알림 종류: `announcement` 공지, `news` 뉴스, `twitter` X, `signal` 시그널, `price_alert` 가격 알림, `contract_movement` 선물 급변동. |
| `source` | `{id, name}`: 소스 ID(예: `binance`, `odaily`, X 계정 숫자 ID)와 표시 이름. |
| `followup` | `true` = 이미 받은 알림의 추가 전송(예: 원문 뒤의 번역). |
| `lang` | `text`의 언어(`zh` / `en` / `ko`), 공지·뉴스만 있고 그 외는 `null`. |
| `label` | `original` = 원문이 설정한 알림 언어가 아니어서 원문을 먼저 보냄(이후 번역이 옴), `translation` = 기계 번역, `official_translation` = 출처(거래소 또는 뉴스 매체)가 나중에 공개한 해당 언어 공식판, `null` = 보낼 때 이미 내 언어(출처 원문이 그 언어이거나, 알림 전에 출처가 그 언어 공식판을 이미 공개한 경우)이거나 해당 없음(예: 가격 알림). `text` 첫 줄을 파싱하지 말고 `label`과 `lang` 필드로 판단하세요. 그 줄의 문구는 알림 언어에 따라 달라지고, 과거 알림은 이전 문구를 씁니다. |
| `title` | 채널에 표시되는 제목으로 알림 언어를 따릅니다. 중국어는 `【币安(BINANCE)】`, 영어·한국어는 `[BINANCE]`, `[WallStreetCN]` 형식입니다. |
| `text` | Bark·위챗 워크가 받은 본문과 같은 일반 텍스트(줄바꿈과 원문 / 번역 표시 줄 포함). 제목만 번역되며 뉴스 요약은 소스의 원문 언어로 남습니다(소스가 해당 언어판을 직접 게시한 경우 제외). |
| `url` | 알림의 링크. 공지·뉴스는 `lang` 언어의 공식 페이지. |
| `titles` | 전송 시점의 언어별 제목(공지·뉴스), 그 외 `null`. |
| `ref` | 이 알림에 해당하는 토픽 이벤트 `{type, topic, event_id}`(공지·뉴스). 구조화 데이터는 `GET /v1/events/{event_id}`로. 그 외 `null`. |
| `created_at` | 전송 시각(Unix 초). |

### 예시: 원문 먼저(알림 언어는 중국어, 공지 원문은 영어)

```json
{
  "op": "alert",
  "alert": {
    "id": "6af57201e1b0c95f3a7d2e41",
    "category": "announcement",
    "source": {
      "id": "binance",
      "name": "Binance"
    },
    "followup": false,
    "lang": "en",
    "label": "original",
    "title": "【币安(BINANCE)】",
    "text": "【原文·英文】\nBinance Will List Fooken (FOO) with Seed Tag Applied\n— — — — — — — — — —\nhttps://www.binance.com/en/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)",
    "url": "https://www.binance.com/en/support/announcement/detail/abc123",
    "titles": {
      "en": "Binance Will List Fooken (FOO) with Seed Tag Applied"
    },
    "ref": {
      "type": "announcement",
      "topic": "announcement.binance",
      "event_id": "6af57200e1b0c95f3a7d2e40"
    },
    "created_at": 1794470401
  }
}
```

### 예시: 번역 추가 전송(같은 공지)

```json
{
  "op": "alert",
  "alert": {
    "id": "6af57203e1b0c95f3a7d2e47",
    "category": "announcement",
    "source": {
      "id": "binance",
      "name": "Binance"
    },
    "followup": true,
    "lang": "zh",
    "label": "translation",
    "title": "【币安(BINANCE)】",
    "text": "【译文】\n币安将上线 Fooken (FOO) 并添加种子标签\n— — — — — — — — — —\nhttps://www.binance.com/zh-CN/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)",
    "url": "https://www.binance.com/zh-CN/support/announcement/detail/abc123",
    "titles": {
      "en": "Binance Will List Fooken (FOO) with Seed Tag Applied",
      "zh": "币安将上线 Fooken (FOO) 并添加种子标签",
      "ko": "바이낸스, 시드 태그가 적용된 Fooken(FOO) 상장"
    },
    "ref": {
      "type": "announcement",
      "topic": "announcement.binance",
      "event_id": "6af57200e1b0c95f3a7d2e40"
    },
    "created_at": 1794470403
  }
}
```

같은 공지의 원문과 번역은 내 알림 두 건(`id` 다름)이며 `ref.event_id`는 같습니다. 언어별로 최대 한 번만 추가 전송하며, 번역이 실패하면 추가 전송이 없습니다(원문은 이미 받음). 원문이 이미 알림 언어라면 한 건뿐이고 `label = null`입니다.

### 예시: REST 응답

**GET /v1/alerts?limit=2**

```json
{
  "alerts": [
    {
      "id": "6af57203e1b0c95f3a7d2e47",
      "category": "announcement",
      "source": {
        "id": "binance",
        "name": "Binance"
      },
      "followup": true,
      "lang": "zh",
      "label": "translation",
      "title": "【币安(BINANCE)】",
      "text": "【译文】\n币安将上线 Fooken (FOO) 并添加种子标签\n— — — — — — — — — —\nhttps://www.binance.com/zh-CN/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)",
      "url": "https://www.binance.com/zh-CN/support/announcement/detail/abc123",
      "titles": {
        "en": "Binance Will List Fooken (FOO) with Seed Tag Applied",
        "zh": "币安将上线 Fooken (FOO) 并添加种子标签",
        "ko": "바이낸스, 시드 태그가 적용된 Fooken(FOO) 상장"
      },
      "ref": {
        "type": "announcement",
        "topic": "announcement.binance",
        "event_id": "6af57200e1b0c95f3a7d2e40"
      },
      "created_at": 1794470403
    },
    {
      "id": "6af57201e1b0c95f3a7d2e41",
      "category": "announcement",
      "source": {
        "id": "binance",
        "name": "Binance"
      },
      "followup": false,
      "lang": "en",
      "label": "original",
      "title": "【币安(BINANCE)】",
      "text": "【原文·英文】\nBinance Will List Fooken (FOO) with Seed Tag Applied\n— — — — — — — — — —\nhttps://www.binance.com/en/support/announcement/detail/abc123\n— — — — — — — — — —\n2026-11-12 16:00:00 (UTC+8)",
      "url": "https://www.binance.com/en/support/announcement/detail/abc123",
      "titles": {
        "en": "Binance Will List Fooken (FOO) with Seed Tag Applied"
      },
      "ref": {
        "type": "announcement",
        "topic": "announcement.binance",
        "event_id": "6af57200e1b0c95f3a7d2e40"
      },
      "created_at": 1794470401
    }
  ],
  "has_more": false,
  "next_cursor": null,
  "cursor_param": "before",
  "channel_enabled": true
}
```

## 끊긴 뒤 따라잡기

1. 처리한 내 알림의 `id`를 저장합니다.
2. 재연결 후 `welcome`을 받으면 `GET /v1/alerts?after=<마지막 id>`로 오래된 순으로 가져오고, `has_more = true`이면 마지막 `id`로 계속합니다.
3. 따라잡기와 실시간 푸시는 겹칠 수 있으니 `id`로 중복 제거하세요. 보관 기간은 7일이며 그보다 오래된 것은 가져올 수 없습니다.

## 구독과 해제

| 동작 | 방법 |
|---|---|
| 내 알림만 | `?topics=my_alerts` |
| 내 알림 + 토픽 이벤트 | `?topics=my_alerts,announcement.*,news.odaily` |
| 연결 후 구독 / 해제 | `{"op":"subscribe","topics":["my_alerts"]}` / `{"op":"unsubscribe","topics":["my_alerts"]}` |
| `unsubscribe` `["*"]` | 토픽 이벤트만 해제되고 내 알림은 유지(멈추려면 `my_alerts`를 명시적으로 해제) |

`subscribed` 응답의 `my_alerts.subscribed`가 이 연결의 현재 상태입니다.

## 전체 예제

**Python**

```python
import asyncio, json, os, time
import requests    # pip install requests
import websockets  # pip install websockets

KEY = os.environ["TOKENEARLY_API_KEY"]
H = {"Authorization": f"Bearer {KEY}"}
STREAM = "wss://api.tokenearly.com/v1/stream?topics=my_alerts"   # my alerts only; add topics (e.g. ",announcement.*") to also get events
ALERTS = "https://api.tokenearly.com/v1/alerts"
FATAL = {4001, 4003}                        # bad / expired key, no permission: fix it, do not retry

last_id = None                              # last alert id you processed (store it durably in production)
seen = set()                                # ids already handled: the REST catch-up and the stream can overlap

def handle(n):
    global last_id
    if n["id"] in seen:
        return
    seen.add(n["id"])
    if not last_id or n["id"] > last_id:    # ids grow with time; only move the cursor forward
        last_id = n["id"]
    # n["text"] is exactly what your Bark / WeCom received; n["label"] says original / translation
    print(n["category"], n["source"]["name"], n["label"], "follow-up" if n["followup"] else "first")
    print(n["text"])
    if n["ref"]:                            # announcements and news: the topic event behind this alert
        print("event:", n["ref"]["event_id"])   # GET /v1/events/{event_id} for the structured data

def catch_up():
    """Notifications sent while you were offline: the stream does not replay them."""
    if not last_id:
        return
    while True:
        r = requests.get(ALERTS, params={"after": last_id, "limit": 200}, headers=H, timeout=10)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "3")))
            continue
        r.raise_for_status()
        page = r.json()
        for n in page["alerts"]:     # oldest first when `after` is given
            handle(n)
        if not page["has_more"]:
            return
        time.sleep(int(r.headers.get("X-RateLimit-Reset", "3")))   # respect the per-key interval

async def main():
    delay = 1
    while True:
        try:
            async with websockets.connect(STREAM, additional_headers=H) as ws:
                async for raw in ws:
                    msg = json.loads(raw)
                    op = msg["op"]
                    if op == "welcome":
                        delay = 1
                        if not msg["my_alerts"]["channel_enabled"]:
                            print("Turn on the Developer API switch under Notification channels in the dashboard.")
                        await asyncio.to_thread(catch_up)   # blocking HTTP off the event loop
                    elif op == "alert":
                        handle(msg["alert"])
                    elif op == "error":
                        print("server error:", msg["code"], msg["message"])
        except websockets.ConnectionClosed as e:
            if e.rcvd and e.rcvd.code in FATAL:
                raise SystemExit(f"stopped: close code {e.rcvd.code}")
            if e.rcvd and e.rcvd.code == 4029:
                delay = max(delay, 5)       # slot not free yet
        except Exception as e:
            print("disconnected:", e)
        await asyncio.sleep(delay)
        delay = min(delay * 2, 60)          # exponential backoff

asyncio.run(main())
```

**Node.js**

```javascript
// npm install ws   (Node.js 18+ for fetch)
const WebSocket = require("ws");

const KEY = process.env.TOKENEARLY_API_KEY;
const H = { Authorization: `Bearer ${KEY}` };
const STREAM = "wss://api.tokenearly.com/v1/stream?topics=my_alerts";
const ALERTS = "https://api.tokenearly.com/v1/alerts";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

let lastId = null;          // last alert id processed (persist it in production)
const seen = new Set();     // REST catch-up and the stream can overlap

function handle(n) {
  if (seen.has(n.id)) return;
  seen.add(n.id);
  if (!lastId || n.id > lastId) lastId = n.id;
  console.log(n.category, n.source.name, n.label, n.followup ? "follow-up" : "first");
  console.log(n.text);      // exactly what your Bark / WeCom received
}

async function catchUp() {
  if (!lastId) return;      // the stream does not replay my alerts
  for (;;) {
    const r = await fetch(`${ALERTS}?after=${lastId}&limit=200`, { headers: H });
    if (r.status === 429) { await sleep(1000 * Number(r.headers.get("retry-after") || 3)); continue; }
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    const page = await r.json();
    page.alerts.forEach(handle);          // oldest first when `after` is given
    if (page.has_more) await sleep(1000 * Number(r.headers.get("x-ratelimit-reset") || 3));   // respect the per-key interval
    else return;
  }
}

function connect(delay = 1) {
  const ws = new WebSocket(STREAM, { headers: H });
  ws.on("message", (raw) => {
    const msg = JSON.parse(raw);
    if (msg.op === "welcome") {
      delay = 1;
      if (!msg.my_alerts.channel_enabled) console.log("Turn on the Developer API switch in the dashboard.");
      catchUp().catch((e) => console.error("catch-up failed:", e.message));   // runs alongside live messages; dedupe by id
    } else if (msg.op === "alert") {
      handle(msg.alert);
    } else if (msg.op === "error") {
      console.error("server error:", msg.code, msg.message);
    }
  });
  ws.on("close", (code) => {
    if (code === 4001 || code === 4003) return console.error("stopped: close code", code);   // fix the key / plan first
    const wait = code === 4029 ? Math.max(delay, 5) : delay;   // 4029: the slot may take a few seconds to free up
    setTimeout(() => connect(Math.min(wait * 2, 60)), wait * 1000);
  });
  ws.on("error", (e) => console.error("socket error:", e.message));
}

connect();
```
