# 查询事件

按主题查询历史事件，支持游标翻页与断线补拉。

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

`GET https://api.tokenearly.com/v1/events`

默认返回最新的事件（按时间倒序）。带 `after` 时改为正序，返回该事件之后的所有事件，适合断线补拉；带 `before` 时向更早翻页。`has_more` 为 true 时，把 `next_cursor` 原样放进 `cursor_param` 指明的参数里继续请求。响应里的 `access` 列出本次请求的主题中哪些有权限（granted）、哪些没有（denied）、哪些不存在（unknown）。可查询的时间范围由套餐的历史天数决定。

**需要 API Key**

## 参数

| 参数 | 位置 | 类型 | 必填 | 说明 |
|---|---|---|---|---|
| `topics` | query | string |  | 逗号分隔，可以任意组合（例如 `announcement.binance,news.*`），每一项是主题或通配：`announcement.binance`、`announcement.*`、`news.*`、`signal.*`、`twitter.*`、`*`。省略 = Key 可用的全部主题。 |
| `after` | query | string |  | 返回比该事件 ID 更新的事件，按时间正序。用于断线后补拉。 |
| `before` | query | string |  | 返回比该事件 ID 更早的事件，按时间倒序。用于向前翻页。 |
| `updated_after` | query | integer |  | 返回在这个时间（Unix 秒）之后产生了新修订版的事件（事件本身可以更早），按事件 ID 正序；用来补齐断线期间旧事件的更新。翻页时 updated_after 保持不变，把上一页的 next_cursor 作为 after 传入。不能与 before 同时用。不传或传 0 表示不使用这个参数（此时按普通列表返回，最新在前）。 |
| `limit` | query | integer |  | 每页条数，1–200，默认 50。 |
| `listings_only` | query | boolean |  | 设为 true 时只返回判定为上新的交易所公告（`data.listing.is_listing = true`），其他类型的主题一律不返回；可与 `after` / `before` / `updated_after` 一起用。因为是按判定结果筛选，一页可能少于 `limit` 条而 `has_more` 仍为 true：继续用 `next_cursor` 翻页，直到 `has_more = false`。 |

## 请求示例

**cURL**

```bash
curl "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5" \
  -H "Authorization: Bearer $TOKENEARLY_API_KEY"
```

**Python**

```python
import os, requests

resp = requests.get(
    "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5",
    headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"},
    timeout=10,
)
resp.raise_for_status()
print(resp.json())
```

**Node.js**

```javascript
// Node 18+ (built-in fetch)
async function main() {
  const resp = await fetch("https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5", {
    headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` },
  });
  const body = await resp.json();
  if (!resp.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
  console.log(body);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	req, _ := http.NewRequest("GET", "https://api.tokenearly.com/v1/events?topics=announcement.*,news.odaily&limit=5", nil)
	req.Header.Set("Authorization", "Bearer "+os.Getenv("TOKENEARLY_API_KEY"))
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	fmt.Println(resp.Status, string(body))
}
```

## 示例响应

```json
{
  "events": [
    {
      "spec_version": "1.0",
      "id": "6b150c67e70ade1bb493e0e2",
      "revision": 1,
      "action": "created",
      "topic": "twitter.44196397",
      "type": "twitter",
      "source": {
        "id": "44196397",
        "name": "@elonmusk (Elon Musk)"
      },
      "published_at": 1796541539,
      "published_at_ms": 1796541539136,
      "detected_at_ms": 1796541543941,
      "data": {
        "kind": "quote",
        "tweet_id": "2129475674222317961",
        "author": {
          "id": "44196397",
          "screen_name": "elonmusk",
          "name": "Elon Musk"
        },
        "text": "Yeah",
        "lang": "en",
        "url": "https://x.com/elonmusk/status/2129475674222317961",
        "referenced_tweet_id": "2129371437043483081",
        "conversation_id": null,
        "media": [],
        "complete": true
      }
    },
    {
      "spec_version": "1.0",
      "id": "6b150bf2d0e4e92d8481211f",
      "revision": 3,
      "action": "updated",
      "topic": "news.panews",
      "type": "news",
      "source": {
        "id": "panews",
        "name": "PANews"
      },
      "published_at": 1796541408,
      "published_at_ms": 1796541408000,
      "detected_at_ms": 1796541426000,
      "data": {
        "titles": {
          "zh": "DWF Labs合伙人：比特币已挺过风暴，若Strategy没有崩盘，市场或已触底",
          "en": "DWF Labs Partner: Bitcoin Has Weathered the Storm; If Strategy Hasn't Collapsed, the Market May Have Bottomed",
          "ko": "DWF Labs 파트너: 비트코인은 폭풍을 견뎌냈으며, 만약 Strategy가 붕괴되지 않았다면 시장은 이미 바닥에 도달했을 수 있다"
        },
        "original_lang": "zh",
        "translated_langs": [
          "ko"
        ],
        "summary": "PANews 12月6日消息，DWF Labs 合伙人 Andrei Grachev 发文预测，比特币已经受住这轮市场风暴，如果 Strategy 没有崩盘，那么市场可能已经触底。",
        "url": "https://www.panewslab.com/zh/articles/01a24a36-6342-7407-b95e-475df0dce169"
      }
    },
    {
      "spec_version": "1.0",
      "id": "6b0ff643d0e4e92d84810499",
      "revision": 3,
      "action": "updated",
      "topic": "announcement.gate",
      "type": "announcement",
      "source": {
        "id": "gate",
        "name": "Gate.io"
      },
      "published_at": 1796208195,
      "published_at_ms": 1796208195000,
      "detected_at_ms": 1796208195896,
      "data": {
        "titles": {
          "zh": "Gate 已上线 RITUAL 合约交易、杠杆借贷交易、交易机器人、跟单、闪兑、定投功能",
          "en": "Gate Now Supports RITUAL for Futures Trading, Margin Loans, Bots, Copy, Convert, and Auto-Invest",
          "ko": "Gate는 RITUAL 계약 거래, 레버리지 대출 거래, 트레이딩 봇, 팔로우 트레이딩, 스왑, 정기 투자 기능을 출시했습니다."
        },
        "original_lang": "zh",
        "translated_langs": [
          "ko"
        ],
        "url": "https://www.gate.io/article/103112",
        "exchange_category": "listing",
        "listing": {
          "is_listing": true,
          "market": "futures"
        },
        "symbols": []
      }
    },
    {
      "spec_version": "1.0",
      "id": "6b055216d0e4e92d8480d1e5",
      "revision": 1,
      "action": "created",
      "topic": "signal.binance_alpha",
      "type": "signal",
      "source": {
        "id": "binance_alpha",
        "name": "Binance Alpha"
      },
      "published_at": 1795510800,
      "published_at_ms": 1795510800000,
      "detected_at_ms": 1795510806000,
      "data": {
        "signal_type": "binance_alpha",
        "level": "info",
        "titles": {
          "zh": "🆕 Binance Alpha 新币上线: SHARE (BSC)",
          "en": "🆕 Binance Alpha New Token: SHARE (BSC)",
          "ko": "🆕 바이낸스 알파 신규 토큰: SHARE (BSC)"
        },
        "contents": {
          "zh": "代币: SHARE (ShareX)\n链: BSC\n价格: $0.0572\n合约: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\n持有者: 61649\n市值: $56.19M",
          "en": "Token: SHARE (ShareX)\nChain: BSC\nPrice: $0.0572\nContract: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\nHolders: 61649\nMarket Cap: $56.19M",
          "ko": "토큰: SHARE (ShareX)\n체인: BSC\n가격: $0.0572\n컨트랙트: 0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34\nAlpha ID: ALPHA_1287\n보유자: 61649\n시가총액: $56.19M"
        },
        "url": "https://www.binance.com/en/alpha/bsc/0xe5e5e1d77125fc910d8f39cdd55b7a24ec69ce34",
        "symbols": [
          "SHARE"
        ],
        "tags": [
          "new_listing",
          "bsc"
        ]
      }
    }
  ],
  "has_more": true,
  "next_cursor": "6b055216d0e4e92d8480d1e5",
  "cursor_param": "before",
  "access": {
    "granted": [
      "announcement.gate",
      "news.panews",
      "signal.binance_alpha",
      "twitter.44196397"
    ],
    "denied": [],
    "unknown": []
  }
}
```

## 错误

| 错误码 | HTTP | 说明 |
|---|---|---|
| `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer <Key>。 |
| `invalid_api_key` | 401 | Key 不存在，或已被重置 / 吊销。 |
| `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key，或开通后创建正式 Key。 |
| `plan_required` | 403 | 当前套餐不含开发者 API，或不含该项能力。 |
| `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单，请求来源 IP 不在其中。 |
| `invalid_cursor` | 400 | after / before 不是合法的 ID（查事件时是事件 ID，查我的推送时是推送 ID），两者同时出现，或（仅查事件）updated_after 与 before 同时使用。 |
| `invalid_parameter` | 400 | 参数类型或取值不合法（例如 limit 超出范围）。 |
| `rate_limited` | 429 | 超过这把 Key 的请求频率（REST 与 MCP 合计，间隔见 `/v1/me` 的 `limits.rest_interval_seconds`）；按 Retry-After 头等待后重试。 |

## 可以查询哪些主题

`topics` 参数填下表里的主题 ID，或用 `announcement.*`、`news.*`、`signal.*`、`twitter.*`、`*` 通配。能否读取由套餐决定：响应里的 `access` 会逐个告诉你——`granted` 有权限并已返回，`denied` 没有权限，`unknown` 主题不存在。

**示例：请求 topics=announcement.binance,announcement.upbit,announcement.nope**

```json
{
  "access": {
    "granted": [
      "announcement.binance"
    ],
    "denied": [
      "announcement.upbit"
    ],
    "unknown": [
      "announcement.nope"
    ]
  }
}
```

| 主题 ID | 名称 | 类型 |
|---|---|---|
| `announcement.binance` | 币安 | 交易所公告 |
| `announcement.okx` | 欧易 | 交易所公告 |
| `announcement.mexc` | 抹茶 | 交易所公告 |
| `announcement.bitget` | Bitget | 交易所公告 |
| `announcement.gate` | Gate.io | 交易所公告 |
| `announcement.huobi` | 火币 | 交易所公告 |
| `announcement.bybit` | Bybit | 交易所公告 |
| `announcement.kucoin` | KuCoin | 交易所公告 |
| `announcement.upbit` | Upbit | 交易所公告 |
| `announcement.bithumb` | Bithumb | 交易所公告 |
| `news.odaily` | Odaily | 新闻快讯 |
| `news.jinse` | 金色财经 | 新闻快讯 |
| `news.theblockbeats` | 律动 | 新闻快讯 |
| `news.foresight` | Foresight News | 新闻快讯 |
| `news.panews` | PANews | 新闻快讯 |
| `news.coinmarketcap` | CoinMarketCap | 新闻快讯 |
| `news.wallstreetcn` | 华尔街见闻 | 新闻快讯 |
| `news.theblock` | The Block | 新闻快讯 |
| `signal.binance_alpha` | Binance Alpha | 信号 |
| `twitter.44196397` | @elonmusk (Elon Musk) | 推特 KOL 推文 |
| `twitter.902926941413453824` | @cz_binance (CZ 🔶 BNB) | 推特 KOL 推文 |
| `twitter.574032254` | @coinbase (Coinbase 🛡️) | 推特 KOL 推文 |
| `twitter.1422537905885442055` | @CoinbaseAssets (Coinbase Assets 🛡️) | 推特 KOL 推文 |
| `twitter.720487892670410753` | @CoinbaseMarkets (Coinbase Markets 🛡️) | 推特 KOL 推文 |
| `twitter.877807935493033984` | @binance (Binance) | 推特 KOL 推文 |
| `twitter.295218901` | @VitalikButerin (vitalik.eth) | 推特 KOL 推文 |
| `twitter.1003840309166366721` | @heyibinance (Yi He) | 推特 KOL 推文 |
| `twitter.902839045356744704` | @justinsuntron (H.E. Justin Sun 👨‍🚀 🌞) | 推特 KOL 推文 |
| `twitter.900935123968737281` | @hebi555 (何币) | 推特 KOL 推文 |
| `twitter.1403881130802225152` | @BTCdayu (大宇) | 推特 KOL 推文 |
| `twitter.2985599460` | @star_okx (Star_OKX) | 推特 KOL 推文 |
| `twitter.1533037218444476416` | @xincctnnq (币圈女菩萨｜Pizza披萨🍕) | 推特 KOL 推文 |
| `twitter.25073877` | @realDonaldTrump (Donald J. Trump) | 推特 KOL 推文 |
| `twitter.1686901686185721857` | @TrumpDailyPosts (Commentary Trump Daily Posts) | 推特 KOL 推文 |
| `twitter.20736511` | @nayibbukele (Nayib Bukele) | 推特 KOL 推文 |
| `twitter.1844002277218242560` | @Plasma | 推特 KOL 推文 |
| `twitter.2414580907` | @pauliepunt (Paul) | 推特 KOL 推文 |
| `twitter.867617849208037377` | @okx (OKX) | 推特 KOL 推文 |
| `twitter.1138033434` | @Rewkang (Andrew Kang) | 推特 KOL 推文 |
| `twitter.1789908971953799168` | @Aster_DEX (Aster 🥷) | 推特 KOL 推文 |
| `twitter.1948234340556763136` | @zakk_okx (Zakk 🟪 OKX AI) | 推特 KOL 推文 |
| `twitter.357312062` | @Bitcoin | 推特 KOL 推文 |
| `twitter.973261472` | @blknoiz06 (Ansem 🐂🀄️) | 推特 KOL 推文 |
| `twitter.132749200` | @OxSunNFT (0xSun ❤️ Memecoin) | 推特 KOL 推文 |
| `twitter.844304603336232960` | @MustStopMurad (Murad 💹🧲) | 推特 KOL 推文 |
| `twitter.1195728139898376193` | @0xcryptowizard (0xWizard) | 推特 KOL 推文 |
| `twitter.992590209752629249` | @notEezzy (Eezzy 🧸) | 推特 KOL 推文 |
| `twitter.1800348208461205504` | @xiaomucrypto (新股神白毛股神) | 推特 KOL 推文 |
| `twitter.16228398` | @mcuban (Mark Cuban) | 推特 KOL 推文 |
| `twitter.1189381231198134272` | @CookerFlips (Cooker.hl \| 版本之子 \| (Theo Arc)) | 推特 KOL 推文 |
| `twitter.1279711663264894977` | @DekuKing1 (0x易经(刘彻版)) | 推特 KOL 推文 |
| `twitter.725984371946082304` | @XXAntiWar (XX) | 推特 KOL 推文 |
| `twitter.1462727797135216641` | @lookonchain (Lookonchain) | 推特 KOL 推文 |
| `twitter.1466673394649559040` | @huahuayjy (花花) | 推特 KOL 推文 |
| `twitter.1401718840535379970` | @hellosuoha (梭教授说) | 推特 KOL 推文 |
| `twitter.1453603581932687368` | @laofeiyyds (比特币老肥.btc（敏感肥）) | 推特 KOL 推文 |
| `twitter.1852674305517342720` | @aixbt_agent (aixbt) | 推特 KOL 推文 |
| `twitter.1279918106111025153` | @assetdash (Dash News) | 推特 KOL 推文 |
| `twitter.169686021` | @kanyewest (ye) | 推特 KOL 推文 |
| `twitter.1483495485889564674` | @bwenews (方程式新闻 BWEnews 🏎️) | 推特 KOL 推文 |
| `twitter.1052454006537314306` | @BNBCHAIN (BNB Chain) | 推特 KOL 推文 |
| `twitter.1451036242431262720` | @binancezh (币安Binance华语) | 推特 KOL 推文 |
| `twitter.1940360837547565056` | @aleabitoreddit (Serenity) | 推特 KOL 推文 |

想一次看清所有主题的权限：带上你的 Key 调用 [GET /v1/topics](https://tokenearly.com/developers/rest/topics)，每个主题都有 `accessible` 字段。

## 断线补拉

分两步：先用 `after=<最后的事件 id>` 一页页拉新事件到 `has_more = false`；再用 `updated_after=<断线时间>` 拉断线期间产生了新修订版的旧事件（`after` 只按事件 ID 往后找，拿不到旧事件的更新）。然后连回实时流。

```python
import os, time, requests

KEY = os.environ["TOKENEARLY_API_KEY"]
API = "https://api.tokenearly.com/v1/events"
TOPICS = "announcement.*,news.*,signal.*,twitter.*"
H = {"Authorization": f"Bearer {KEY}"}

def get(params):
    while True:
        r = requests.get(API, params=dict(params, topics=TOPICS, limit=200), headers=H, timeout=10)
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "3")))   # whole seconds
            continue
        r.raise_for_status()
        time.sleep(int(r.headers.get("X-RateLimit-Reset", "3")))   # respect the per-key interval
        return r.json()

cursor = load_last_event_id()          # the last event id you stored (None on the first run)
offline_since = load_last_seen_time()  # Unix seconds when you last had a live connection (0 on the first run)

# First run: nothing to catch up. Just connect to the stream and start storing ids and times.
if cursor and offline_since:
    # 1) new events after the cursor (oldest first, `cursor_param` is "after")
    while True:
        page = get({"after": cursor})
        for ev in page["events"]:
            handle(ev)
            cursor = ev["id"]
        if not page["has_more"]:
            break

    # 2) older events that got a new revision while you were away
    params = {"updated_after": offline_since}
    while True:
        page = get(params)
        for ev in page["events"]:
            handle(ev)                 # same (id, revision) dedupe as for live events
        if not page["has_more"]:
            break
        # always pass next_cursor under the name the response gives in `cursor_param`
        params = {"updated_after": offline_since, page["cursor_param"]: page["next_cursor"]}
    save_last_event_id(cursor)
```
