跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

发送 Slack 通知

最后更新 查看 MarkdownAgent 设置

当对选定应用程序端点的请求完成后,发送 Slack 通知。Worker 返回上游响应,并在后台发送通知。

配置 Worker

在 Worker 项目中,将 @cloudflare/zt-types ↗ 2026.10.1 或更高版本安装为开发依赖项:

npm i -D @cloudflare/zt-types

保留 src/index.ts 中 GatewayMiddlewareContext 和 GatewayMiddlewareNext 的 import type 声明。它们描述 Gateway 上下文和延续函数,并会在 TypeScript 编译时被移除。从 cloudflare:workers 导入运行时 WorkerEntrypoint 类。

为所选频道创建 Slack incoming webhook ↗。将其 URL 存储为名为 SLACK_WEBHOOK_URL 的 Worker secret:

npx wrangler secret put SLACK_WEBHOOK_URL

将以下脚本用作 src/index.ts:

src/index.jsjs
import { WorkerEntrypoint } from "cloudflare:workers";

export class GatewayMiddleware extends WorkerEntrypoint {
	async handle(request, context, next) {
		const response = await next(request);
		this.ctx.waitUntil(
			this.notify(
				`${request.method} ${context.host}: HTTP ${response.status}`,
			).catch(() => console.error("Slack notification failed")),
		);
		return response;
	}

	async notify(text) {
		const result = await fetch(this.env.SLACK_WEBHOOK_URL, {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				blocks: [{ type: "section", text: { type: "plain_text", text } }],
			}),
			signal: AbortSignal.timeout(10_000),
		});
		await result.body?.cancel();
		if (!result.ok) throw new Error("Webhook rejected notification");
	}
}
src/index.tsts
import { WorkerEntrypoint } from "cloudflare:workers";
import type {
	GatewayMiddlewareContext,
	GatewayMiddlewareNext,
} from "@cloudflare/zt-types";

interface Env {
	SLACK_WEBHOOK_URL: string;
}

export class GatewayMiddleware extends WorkerEntrypoint<Env> {
	async handle(
		request: Request,
		context: GatewayMiddlewareContext,
		next: GatewayMiddlewareNext,
	): Promise<Response> {
		const response = await next(request);
		this.ctx.waitUntil(
			this.notify(
				`${request.method} ${context.host}: HTTP ${response.status}`,
			).catch(() => console.error("Slack notification failed")),
		);
		return response;
	}

	async notify(text: string): Promise<void> {
		const result = await fetch(this.env.SLACK_WEBHOOK_URL, {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				blocks: [{ type: "section", text: { type: "plain_text", text } }],
			}),
			signal: AbortSignal.timeout(10_000),
		});
		await result.body?.cancel();
		if (!result.ok) throw new Error("Webhook rejected notification");
	}
}

该消息使用 Slack 的纯文本格式,以防止请求文本创建提及。它包含方法、主机和响应状态。它不会发送 Cookie、授权标头、请求体或 URL 查询参数。

转发并测试

部署 Worker 并创建 Forward 策略。匹配一个测试用户组和一个具体的应用程序事件,例如 Host(主机) 为 app.example.com、URL Path(URL 路径) 为 /signup、HTTP Method(HTTP 方法) 为 POST。

触发一次测试请求,确认其响应未发生变化,并且 Slack 中出现一条消息。过滤型 Block 策略会同时阻止上游请求和此通知。

此脚本会为每次调用发送通知,包括应用程序错误响应。若仅在成功时通知,请用 if (response.ok) 保护 waitUntil()。对于更高流量的策略,请添加采样或排队通知管道,并考虑 Slack 速率限制 ↗。宽泛的主机策略可能为每个页面资源生成一条消息。

这篇文档对您有帮助吗?