コンテンツにスキップ

Service Bindings でイベントを送る

同じCloudflareアカウントのWorkerからは、Service Bindingsで Intake エントリポイントを呼びます。送信元は props の送信元ID(送信元の画面の「送り方」タブに表示されます)で決まります。service には、デプロイしたPingluneのWorker名(既定は pinglune)を書きます。呼び出し側Workerの wrangler.jsonc に次のように書きます。

{
"services": [
{
"binding": "PINGLUNE",
"service": "pinglune",
"entrypoint": "Intake",
"props": { "source_id": "src_01JC9Z7H2K4M6N8P0Q2R4S6T8V" }
}
]
}
const result = await env.PINGLUNE.submit({
idempotency_key: "job-42",
type: "job.finished",
summary: "バッチ処理が完了しました",
labels: { env: "prod" },
body: { content_type: "text/plain", bytes: new TextEncoder().encode("ログ") },
attachments: [{ name: "result.json", content_type: "application/json", bytes: jsonBytes }],
});
if (!result.ok && result.error.retryable) {
// 一時的な失敗。同じ idempotency_key で再送する。
}

項目の制約はHTTPと同じですが、body は { content_type, bytes } のオブジェクト、attachments は { name, content_type, bytes } の配列で渡します(body_content_type はありません)。body と添付に未知のキーがあると unknown_field になります。本文は0バイトにできません(本文がなければ body を省略します)が、添付は0バイトでも受け付けます。bytes には Uint8Array か ArrayBuffer を渡します(ReadableStream は受け付けません)。

submit 自体は例外を投げず、成功なら { ok: true, event_id, duplicate }、失敗なら { ok: false, error: { code, message, retryable, fields? } } を返します。retryable は temporarily_unavailable のときだけ true です。props.source_id がない・正しくない・存在しない場合は unauthorized、無効にした送信元は source_disabled を返します。バインディングの設定誤りなど、RPCの呼び出しそのものが失敗した場合は、呼び出し側で例外になります。

受け付けたイベントが届くのは、管理画面の「Bot」でその送信元を受け取る送信元に選んだBotの配信先だけです。

同じバインディングの startConversation で、Botを指定して会話を始めることもできます(送信元ごとに許可が必要)。プログラムから会話を始めるを参照してください。