# 创建消息 (POST)

向你的设备发送推送通知。

## 端点

```
POST https://api.pocketalert.app/v1/messages
```

## 身份验证

> **Info: 必需**
>
> 在请求中添加以下任一请求头：
> - `Token: <your-api-key>` — 从 [API 密钥](https://pocketalert.app/account/apikeys) 页面获取
> - `Authorization: Bearer <jwt-token>` — 通过 [登录](https://info.pocketalert.app/api/user/login.md) 获取

## 请求

### 请求头

| 请求头 | 必需 | 说明 |
|--------|:--------:|-------------|
| `Content-Type` | ✅ | `application/json` |
| `Token` | ✅ | 你的 API 密钥 |
| `Authorization` | ✅ | `Bearer <jwt-token>` |

<small>* `Token` 或 `Authorization` 二者必需其一</small>

### 请求体参数

| 参数 | 类型 | 必需 | 说明 |
|-----------|------|:--------:|-------------|
| `title` | string | ✅ | 通知标题 |
| `message` | string | ✅ | 通知正文 |
| `application_id` | string | ❌ | 用于对消息分类的应用 TID |
| `device_id` | string | ❌ | 指定设备的 TID，省略则发送到所有设备 |
| `level` | string \| int | ❌ | 优先级，决定推送的投递方式。可使用名称或整数（`-2`..`2`）。`priority` 为同义参数。默认使用应用的默认级别，若未设置则为 `default`。 |
| `actions` | array | ❌ | 通知上显示的操作按钮，最多 3 个。参见 [操作按钮](#action-buttons)。 |
| `send_at` | string \| int | ❌ | 在指定时间发送，而非立即发送。支持 RFC3339、Unix 时间戳或 `YYYY-MM-DD HH:MM`。参见 [定时发送](#scheduled-delivery)。 |
| `delay` | string | ❌ | 延迟一段相对时间后发送，如 `30m`、`2h` 或纯秒数。与 `send_at` 互斥。 |

#### 操作按钮

每条通知最多可附带 **3** 个操作按钮。无论应用处于打开、后台还是关闭状态，按钮都可以使用。`actions` 是一个对象数组，经 JSON 编码后不得超过 2048 字节（它随推送一起传输，而推送上限为 4 KB；过长的 `message` 会被截短以腾出空间）：

| 字段 | 类型 | 必需 | 说明 |
|-------|------|:--------:|-------------|
| `type` | string | ✅ | `view`（打开 URL）、`http`（发起 HTTP 请求）或 `copy`（将文本复制到剪贴板） |
| `label` | string | ✅ | 按钮文字，在 Android 和 iOS 上原样显示 |
| `value` | string | ✅ | 取决于 `type`，详见下文 |

按类型区分的 `value`：

- **`view`** — 要打开的 URL，例如 `"https://pocketalert.app"`。
- **`http`** — 描述请求的 JSON 字符串：`{"url":"https://…","method":"POST","headers":{…},"body":"…"}`。仅 `url` 为必需，`method` 默认为 `GET`。请求在设备后台发起，无需打开应用，因此可以访问手机局域网内的主机。若请求失败（返回非 2xx/3xx 状态码或网络错误），会显示带有 **重试** 按钮的通知；一旦请求可能已到达服务器，系统便不会自动重试。
- **`copy`** — 放入剪贴板的原始文本。

> **Tip: 人工介入**
>
> 两个 `http` 操作（例如 **批准** / **拒绝**）即可组成一键控制面板，非常适合直接在通知中批准 LLM 智能体的操作。

> **Warning: 付费功能**
>
> 免费套餐会去除操作按钮：消息照常送达，但不包含按钮，且不会校验 `actions`。

有关限制、校验和 Webhook 模板，参见 [操作按钮](https://info.pocketalert.app/features/action-buttons.md)。

#### 优先级

| 级别 | 别名 | 行为 |
|-------|---------|----------|
| `silent` | `min`、`-2` | 仅投递到通知栏，无声音和振动 |
| `low` | `-1` | 安静，不打扰 |
| `default` | `normal`、`0`（或省略） | 标准横幅 + 声音 |
| `high` | `1` | 时效性通知，可突破专注模式 / 定时摘要 |
| `critical` | `max`、`urgent`、`2` | 即使开启静音开关或勿扰模式，也会唤醒设备。参见 [优先级](https://info.pocketalert.app/features/priority-levels.md) |

> **Warning**
>
> `critical` 为付费套餐功能。在免费套餐上会自动降级为 `high`。无效值（未知名称或超出范围的整数）将返回 `400`。

有关各级别在 iOS 和 Android 上的具体表现，参见 [优先级](https://info.pocketalert.app/features/priority-levels.md)。

#### 定时发送

添加 `send_at` 或 `delay`（二者不可同时使用），消息会加密存储，直至投递时间再发送，而不是立即发出。

| 参数 | 支持格式 | 示例 |
|-----------|---------|----------|
| `send_at` | RFC3339、Unix 时间戳或 `YYYY-MM-DD HH:MM` | `2026-08-15T09:00:00Z`、`1786867200` |
| `delay` | Go 风格时长或纯秒数 | `30m`、`2h`、`3600` |

不带时区偏移的时间按你的账户时区解析。最长可预约 30 天；早于当前时间的 `send_at` 将返回 `400`（允许 60 秒的时钟偏差）。

定时请求返回 `201`，响应中包含 `"scheduled": true`、`status`、`deliver_at` 和 `deliver_at_utc`，而非已送达的消息。可通过 `GET /v1/messages/scheduled` 列出，通过 `DELETE /v1/messages/scheduled/{tid}` 取消。参见 [定时发送](https://info.pocketalert.app/features/scheduled-delivery.md)。

> **Warning**
>
> 定时发送为付费套餐功能。免费套餐使用 `send_at` 或 `delay` 的请求将返回 `403`。

### 请求示例

**cURL**

```bash
curl -X POST "https://api.pocketalert.app/v1/messages" \
  -H "Token: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Server Alert",
    "message": "CPU usage exceeded 90%",
    "application_id": "qm47b9pzxzxg",
    "level": "critical",
    "actions": [
      { "type": "view", "label": "Dashboard", "value": "https://status.example.com" },
      { "type": "http", "label": "Restart", "value": "{\"url\":\"https://ops.example.com/restart\",\"method\":\"POST\"}" },
      { "type": "copy", "label": "Copy ID", "value": "incident-4821" }
    ]
  }'
```

**JavaScript**

```javascript
const response = await fetch('https://api.pocketalert.app/v1/messages', {
  method: 'POST',
  headers: {
    'Token': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Server Alert',
    message: 'CPU usage exceeded 90%',
    application_id: 'qm47b9pzxzxg'
  })
});

const data = await response.json();
console.log(data);
```

**Python**

```python
import requests

response = requests.post(
    'https://api.pocketalert.app/v1/messages',
    headers={
        'Token': 'your-api-key',
        'Content-Type': 'application/json'
    },
    json={
        'title': 'Server Alert',
        'message': 'CPU usage exceeded 90%',
        'application_id': 'qm47b9pzxzxg'
    }
)

print(response.json())
```

**PHP**

```php
$response = Http::withHeaders([
    'Token' => 'your-api-key',
])->post('https://api.pocketalert.app/v1/messages', [
    'title' => 'Server Alert',
    'message' => 'CPU usage exceeded 90%',
    'application_id' => 'qm47b9pzxzxg',
]);

return $response->json();
```

## 响应

### 成功响应

> **Tip: 201 Created**
>
> 消息创建成功

| 字段 | 类型 | 说明 |
|-------|------|-------------|
| `tid` | string | 消息的唯一标识符 |
| `title` | string | 消息标题 |
| `message` | string | 消息正文 |
| `application` | string | 应用名称（若已指定） |
| `device` | string | 目标设备名称 |
| `actions` | array | 原样返回的操作按钮（仅在提供时返回） |
| `created_at` | string | 创建时间戳 |

```json
{
  "tid": "jb4xw9elz28g",
  "title": "Server Alert",
  "message": "CPU usage exceeded 90%",
  "application": "Monitoring",
  "device": "iPhone",
  "actions": [
    { "type": "view", "label": "Dashboard", "value": "https://status.example.com" }
  ],
  "created_at": "18.01.2026 15:35:35"
}
```

### 配额响应头

响应会携带当日[每日上限](https://info.pocketalert.app/features/daily-limits.md)的使用情况（不限量套餐不返回）：

| 响应头 | 说明 |
|--------|-------------|
| `X-PA-Daily-Limit` | 你的套餐每日允许发送的消息数 |
| `X-PA-Daily-Remaining` | 包含本条在内，今日剩余可发送的消息数 |
| `X-PA-Daily-Reset` | 下次重置时间（00:00 UTC）的 Unix 时间戳（秒） |

### 错误响应

| 状态码 | 说明 |
|:------:|-------------|
| `400` | 请求错误 — 缺少 `title` 或 `message`、`level` 无效，或在付费套餐上 `actions` 无效 |
| `401` | 未授权 — 令牌无效或缺失 |
| `403` | 禁止访问 — 免费套餐使用了 `send_at` 或 `delay` |
| `404` | 未找到 — `application_id` 或 `device_id` 不存在 |
| `429` | 已达每日上限 — 消息未被存储或发送。请等待 `Retry-After` 秒后重试，或升级套餐。参见[每日消息上限](https://info.pocketalert.app/features/daily-limits.md)。 |

```json
{
  "error": "Validation failed",
  "details": {
    "title": ["The title field is required"]
  }
}
```

#### 已达每日上限

当今日配额用完后，消息会被直接拒绝（不会进入队列），直至 00:00 UTC。`Retry-After` 表示距离重置还剩的秒数。

```http
HTTP/1.1 429 Too Many Requests
Retry-After: 30142
X-PA-Daily-Limit: 50
X-PA-Daily-Remaining: 0
X-PA-Daily-Reset: 1790035200
```

```json
{
  "error": "Daily message limit reached (50/50). New messages are rejected until 00:00 UTC. Upgrade your plan to raise the limit.",
  "limit": 50,
  "used": 50,
  "resets_at": "2026-09-22T00:00:00Z",
  "upgrade_url": "https://pocketalert.app/pricing"
}
```

删除消息不会释放配额。可通过 [`GET /v1/messages/usage`](https://info.pocketalert.app/api/messages/usage.md) 查看今日使用情况。
