# 人工智能机器人流量跟踪 (https://talivia.com/zh-CN/docs/integrations/bot-traffic)



# 人工智能机器人流量跟踪 [#人工智能机器人流量跟踪]

机器人流量是 **Talivia Cloud** 的服务器端功能。已识别的爬虫请求会存入独立数据集，不会计入真人浏览量、访客、转化或收入。

记录请求只表示匹配的爬虫访问了某个 URL，并不能证明内容被引用、推荐、用于回答、身份经过密码学验证或产生收入影响。

## 1. 创建网站令牌 [#1-创建网站令牌]

打开**网站设置 → 机器人流量**，启用收集并生成令牌。每个令牌只属于一个网站。令牌只显示一次，请立即复制，并作为服务器端密钥保存。轮换令牌会立即撤销旧令牌。

```bash
pnpm add @talivia/bot-traffic
```

```bash
TALIVIA_BOT_TOKEN=<one-time-token>
```

## Next.js middleware 或 proxy [#nextjs-middleware-或-proxy]

Next middleware 在最终页面响应之前运行。请使用仅请求跟踪；`NextResponse.next()` 不是页面的最终状态码，不能作为最终状态上报。

```ts
import { NextResponse } from 'next/server';
import { trackBotRequestInBackground } from '@talivia/bot-traffic/next';

export function middleware(request, event) {
  trackBotRequestInBackground(
    request,
    { token: process.env.TALIVIA_BOT_TOKEN! },
    event,
  );
  return NextResponse.next();
}

export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'] };
```

## Express [#express]

Express 适配器会立即调用 `next()`，并在响应的 `finish` 事件后上报最终状态码。

```ts
import express from 'express';
import { createExpressBotMiddleware } from '@talivia/bot-traffic/express';

const app = express();
app.use(createExpressBotMiddleware({
  token: process.env.TALIVIA_BOT_TOKEN!,
}));
```

## Cloudflare Workers 和 Pages [#cloudflare-workers-和-pages]

```ts
import { withBotTracking } from '@talivia/bot-traffic/cloudflare';

export default {
  fetch: withBotTracking(
    (request, env) => env.ASSETS.fetch(request),
    { token: '<server-token>' },
  ),
};
```

对于 Pages Functions，先处理 `context.request`，然后使用最终状态码调用 `trackBotRequestInBackground`，并将 `context` 作为第三个参数传入，以便通过 `waitUntil` 完成后台发送。

## 任意 JavaScript 或 TypeScript 框架 [#任意-javascript-或-typescript-框架]

如果框架提供标准 `Request` 和 `Response`，则不需要专用适配器：

```ts
import { trackBotRequestInBackground } from '@talivia/bot-traffic';

export async function handle(request, context) {
  const response = await yourFrameworkHandler(request);
  trackBotRequestInBackground(
    request,
    { token: process.env.TALIVIA_BOT_TOKEN!, status: response.status },
    context,
  );
  return response;
}
```

如果只能获得传入请求，请省略 `status`。仅请求跟踪仍可记录爬虫尝试访问的页面。只有当 handler 返回最终 `Response` 时才使用 `withBotTracking`。该通用模式适用于 Hono、Bun、Deno、自定义 Node.js Fetch 服务和其他兼容 Fetch 的运行时。

## Docker、Cloud Run 和反向代理 [#dockercloud-run-和反向代理]

如果 `request.url` 使用内部主机名，例如 `http://app:3000/docs`，请设置真实的公开 origin：

```ts
{
  token: process.env.TALIVIA_BOT_TOKEN!,
  publicOrigin: 'https://example.com',
}
```

软件包只替换 origin，并保留请求路径。`publicOrigin` 必须是没有用户名、密码、路径、查询参数或 fragment 的 `http` 或 `https` origin。Talivia 仍会验证公开主机名是否属于该令牌对应的网站。

## PHP、Go、Ruby 和其他语言 [#phpgoruby-和其他语言]

JavaScript 软件包不是必需的。任何服务器语言都可以向固定 endpoint 发送最小事件：

```http
POST https://talivia.com/v1/bot-traffic
Authorization: Bearer <website-bot-token>
Content-Type: application/json

{
  "schemaVersion": 1,
  "hostname": "example.com",
  "path": "/docs/getting-started",
  "method": "GET",
  "userAgent": "GPTBot/1.0",
  "status": 200
}
```

`status` 是可选字段。Talivia Cloud 会自行确定 provider、bot、category 和 verification，不需要发送这些字段。

### PHP 示例 [#php-示例]

只能在应用已经发送用户响应之后调用此 helper。使用 PHP-FPM 时，如果可用，请先调用 `fastcgi_finish_request()`。

```php
function trackTaliviaBot(array $event, string $token): void {
    $ch = curl_init('https://talivia.com/v1/bot-traffic');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($event, JSON_UNESCAPED_SLASHES),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $token,
            'Content-Type: application/json',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT_MS => 1500,
    ]);
    curl_exec($ch);
    curl_close($ch);
}

// 框架生成并发送最终响应之后：
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}
trackTaliviaBot($event, getenv('TALIVIA_BOT_TOKEN'));
```

只对可能是爬虫的文档类 `GET` 或 `HEAD` 请求调用该 helper，并且必须在最终状态码已知且用户响应已经发送之后调用。`path` 只能发送 pathname，不应包含查询参数或 fragment。不要发送 Cookie、Authorization 请求头、请求正文、访客标识、referrer 或来源 IP。

## 自定义接入要求 [#自定义接入要求]

* Endpoint：`https://talivia.com/v1/bot-traffic`。
* 鉴权：`Authorization: Bearer <website-bot-token>`。
* Content type：`application/json`。
* 必填字段：`schemaVersion`、`hostname`、`path`、`method`、`userAgent`。
* 可选字段：`status`，范围为 `100` 到 `599`。
* 只处理文档类 `GET` 和 `HEAD` 请求。
* Payload 不超过 8 KiB，User-Agent 不超过 512 个字符。
* 从 `path` 中删除查询参数和 fragment。
* 使用短超时并保持 fail-open；遥测失败不得影响或延迟网站响应。
* User-Agent 不能证明真实身份。Talivia 会执行中央分类和网络验证。

部署后，可在详细报告中查看请求趋势、提供商、类别、页面、状态码、缺失页面以及基于证据的验证可信度。
