# 我的推送

除了按主题订阅的全量事件，API 还能把**真正推给你的那一份**提醒原样给你：和你在网页上设置的 Bark、企业微信等渠道收到的完全相同，按你的来源、关键词、通知语言过滤。适合把我们的提醒接进你自己的机器人或工作流。

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

## 两种数据的区别

|  | 主题事件（通用数据流） | 我的推送（本页） |
|---|---|---|
| 内容 | 订阅主题下的**全部**消息，不经过任何个人设置 | 只有**推给你的**那些：按你在网页上设置的来源开关、关键词、通知语言、会员延迟过滤 |
| 和渠道的关系 | 无关 | 与 Bark、企业微信等渠道收到的是同一份，逐条一致 |
| 格式 | 结构化事件，`op = "event"`（字段见[事件格式](https://tokenearly.com/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 Key 连接 `wss://api.tokenearly.com/v1/stream?topics=my_alerts`，或调用 [GET /v1/alerts](https://tokenearly.com/developers/rest/alerts)。同一账号的所有 Key 看到的是同一份我的推送。`my_alerts` 只在实时流里是特殊主题；REST 的 `GET /v1/events?topics=my_alerts` 会把它当作不存在的主题放进 `access.unknown`，补拉请用 `GET /v1/alerts`。

> 我的推送遵循你账号的会员延迟：付费会员实时，免费账号与其他渠道一样延迟送达。

## 消息格式

实时流里每条推送是 `{"op": "alert", "alert": {...}}`；REST 返回 `{"alerts": [...]}`，里面的对象完全相同。

| 字段 | 说明 |
|---|---|
| `id` | 推送 ID（24 位十六进制，随时间递增）。`after` / `before` 游标用它；与事件 ID 不是一套。 |
| `category` | 类别：`announcement` 公告、`news` 新闻、`twitter` 推特、`signal` 信号、`price_alert` 价格提醒、`contract_movement` 合约异动。 |
| `source` | `{id, name}`：来源 ID（如 `binance`、`odaily`、推特账号数字 ID）与显示名。 |
| `followup` | `true` = 对一条已推给你的提醒的补推（例如先推原文、这条是译文）。 |
| `lang` | `text` 的语言（`zh` / `en` / `ko`），公告与新闻才有，其他类别为 `null`。 |
| `label` | `original` = 原文不是你设置的通知语言，先推原文（之后会补推译文）；`translation` = 译文（机器翻译）；`official_translation` = 来源（交易所或新闻媒体）后来发布的官方该语言版本；`null` = 推送时就已经是你的语言（来源原本就是这个语言，或推送前来源已经发布了这个语言的官方版本），或不适用（如价格提醒）。请按 `label` 和 `lang` 字段判断，不要解析 `text` 的第一行：标注行的写法会随推送语言变化，历史数据里也有旧写法。 |
| `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 天，离线超过 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();
```
