# Webhooks 自动化

Webhooks 允许你监听 Hugging Face 上特定仓库或存储桶的新变更，或监听属于特定用户/组织集合的所有仓库（不仅限于你自己的仓库，而是任意仓库）上的变更。

在 `huggingface_hub` Python 客户端中使用 `create_webhook` 创建一个 webhook，当 Hugging Face 仓库中发生更改时触发 Job：

```python
from huggingface_hub import create_webhook

# Example: Creating a webhook that triggers a Job
webhook = create_webhook(
    job_id=job_id,
    watched=[{"type": "user", "name": "your-username"}, {"type": "org", "name": "your-org-name"}],
    domains=["repo", "discussion"],
    secret="your-secret"
)
```

当 [bucket](./storage-buckets) 中有文件被添加或删除时，要运行 Job，请监视该 bucket：

```python
webhook = create_webhook(
    job_id=job_id,
    watched=[{"type": "bucket", "name": "your-username/your-bucket"}],
    domains=["repo"],
    secrets={"HF_TOKEN": "hf_***"},
)
```

完整示例请参见 [使用 Jobs 处理存储桶中的新文件](./webhooks-guide-bucket-jobs)。

Webhook 使用以下环境变量触发 Job：

- `WEBHOOK_PAYLOAD`：完整的 webhook 负载，以 JSON 字符串形式表示
- `WEBHOOK_REPO_ID`：仓库或存储桶名称（例如 `user/repo-name`）
- `WEBHOOK_REPO_TYPE`：仓库类型（`model`、`dataset`、`space` 或 `bucket`）
- `WEBHOOK_SECRET`：如果已配置，则为 webhook 密钥
- `WEBHOOK_ID`：投递的唯一标识符，在该次投递的重试过程中保持稳定

> [!WARNING]
> Webhook 运行不会保留 Job 的卷或密钥。请在 `create_webhook` 中通过 `secrets=` 传入 Job 所需的密钥，例如 `HF_TOKEN`。若要通过 Webhook 运行 UV 脚本，请使用 `hf jobs run <image> uv run <url>` 定义您的 Job，否则 `hf jobs uv run` 会将脚本上传到卷中，而 Webhook 运行并不具备该卷。

Webhook 负载包含多个字段，以下是一些有用的字段：

```
- event:
  - action: one of "create", "delete", "move", "update"
  - scope: string
- repo:
  - owner: string
  - headSha: string (not sent for buckets)
  - name: string
  - type: one of "dataset", "model", "space", "bucket"
- updatedFiles: for bucket file changes, the list of added and deleted files
```

您可以在 [`huggingface_hub` Webhooks 文档](https://huggingface.co/docs/huggingface_hub/en/guides/webhooks) 中查找有关 Webhooks 的更多信息。

