# Webhook 设置

了解如何配置 Webhook 消息模板，从传入的 JSON 负载中提取数据。

## 消息模板语法

创建 Webhook 时，你需要定义一个消息模板，用来决定传入的 JSON 数据如何被格式化为通知。

### 基本模式

| 模式 | 说明 |
|---------|-------------|
| `*` | 输出整个 JSON 负载 |
| `%field%` | 提取顶层字段 |
| `%object.field%` | 提取嵌套字段 |
| `%array.0%` | 获取数组的第一个元素 |
| `%array.0.field%` | 获取数组元素中的字段 |
| `%%` | 字面量 `%`。仅在它紧挨着一个单词且后面还跟着另一个 `%` 时才需要使用，例如 `%cpu%%%`；`%` 后面跟空格的情况，例如 `90% on %host%`，保持原样即可 |

占位符中不会包含空格，因此普通文本中的百分号会被原样保留：`CPU over 90% on %host%` 会渲染为 `CPU over 90% on db-1`。

## 示例

### 示例 JSON 负载

以下是一个传入的 Webhook 负载：

```json
{
  "event": {
    "title": "New Order",
    "message": "A new order has been placed with ID 12345",
    "tags": ["order", "new"],
    "users": [
      {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
      {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
      {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
    ]
  }
}
```

### 模板配置

**Full JSON**

```text
*
```

**Extracted Fields**

```text
Title: %event.title%
Message: %event.message%
Tags: %event.tags%
Users: %event.users.0%
First user: %event.users.0.first% %event.users.0.last%
```

### 输出结果

```
Title: New Order
Message: A new order has been placed with ID 12345
Tags: ["order","new"]
Users: {"age":44,"first":"Dale","last":"Murphy","nets":["ig","fb","tw"]}
First user: Dale Murphy
```

## 常见集成

### GitHub Webhook

```text
🔔 %action%: %repository.full_name%
%sender.login%: %commits.0.message%
```

### Sentry 错误追踪

适用于作为告警操作（Issue 告警）使用的内部集成：

```text
🚨 %data.event.title%
%data.event.culprit%
Rule: %data.triggered_rule%
```

添加一个 `view` 按钮，使用 `%data.event.web_url%` 打开 Issue。旧版 Webhooks 插件发送的负载结构不同：此时请使用 `%project_name%: %event.title%` 和 `%url%`。

### Grafana 告警

```text
⚠️ %state%: %title%

%message%

Status: %status%
```

### Uptime Robot

```text
🔴 %monitorFriendlyName%
Status: %alertTypeFriendlyName%
Details: %alertDetails%
```

## 高级路径语法

对于复杂的 JSON 提取，我们使用 [GJSON 路径语法](https://github.com/tidwall/gjson/blob/master/SYNTAX.md)。

### 常用模式

| 模式 | 说明 |
|---------|-------------|
| `%users.#%` | 数组项的数量 |
| `%users.#.first%` | 所有 `first` 值组成的数组 |
| `%users.@reverse%` | 反转数组顺序 |
| `%data.@pretty%` | 格式化输出 JSON |

> **Tip: 了解更多**
>
> 完整文档：[GJSON 路径语法](https://github.com/tidwall/gjson/blob/master/SYNTAX.md)

## 优先级

传入的负载可以包含 `level` 字段，用来控制推送的送达方式：可以是名称（`silent`、`low`、`default`、`high`、`critical`），也可以是整数（`-2`..`2`）。参见[消息优先级](https://info.pocketalert.app/api/messages/create.md#priority-levels)。

解析顺序（首个匹配生效）：

1. 传入 JSON 负载中的 `level` 字段
2. Webhook 的 `default_level`（创建 Webhook 时设置）
3. 应用的默认级别
4. `default`（普通）

与直接调用 API 不同，Webhook 的输入是宽容的：无法识别的 `level` 值会被忽略（回退到默认值），而不会被拒绝，因此告警不会丢失。

## 操作按钮

Webhook 最多可以为其生成的每条通知附加 3 个操作按钮。创建或更新 Webhook 时，设置 `actions` 字段（一个 JSON 字符串）即可，参见[创建 Webhook → 操作按钮模板](https://info.pocketalert.app/api/webhooks/create.md#action-buttons-template)。

`label` 和 `value` 支持与消息模板相同的 `%field.path%` 占位符，因此按钮可以根据传入的负载动态构建：

```json
[
  { "type": "view", "label": "Open PR", "value": "%pull_request.html_url%" },
  { "type": "http", "label": "Merge", "value": "{\"url\":\"https://ci.example.com/merge/%pull_request.number%\",\"method\":\"POST\"}" }
]
```

替换占位符后，系统会校验每个按钮（`type` 须为 `view`/`http`/`copy` 之一，`view` 和 `http` 需要 `http(s)` URL）。与级别解析一样，这种校验是宽容的：无效的按钮会被单独丢弃，其余按钮和通知仍会正常送达。

操作按钮是付费功能。在免费套餐中，按钮会被移除，通知仍会送达，只是不带按钮。

创建 Webhook 后，你可以进行测试：

**cURL**

```bash
curl -X POST "https://p4a.me/wh/YOUR_WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d '{"event": {"title": "Test", "message": "Hello World"}}'
```

**JavaScript**

```javascript
await fetch('https://p4a.me/wh/YOUR_WEBHOOK_URL', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    event: { title: 'Test', message: 'Hello World' }
  })
});
```

**Python**

```python
import requests

requests.post(
    'https://p4a.me/wh/YOUR_WEBHOOK_URL',
    json={'event': {'title': 'Test', 'message': 'Hello World'}}
)
```

**PHP**

```php
Http::post('https://p4a.me/wh/YOUR_WEBHOOK_URL', [
    'event' => [
        'title' => 'Test',
        'message' => 'Hello World',
    ],
]);
```

这将使用你配置的消息模板，向你的设备发送一条测试通知。
