{"title":"Tự động hóa Webhook","slug":"webhook-automation","category":"guides","summary":"Kích hoạt hệ thống bên ngoài khi bộ nhớ thay đổi — đồng bộ, thông báo, tự động hóa.","audience":["human","llm"],"tags":["guide","webhooks","automation","integration"],"difficulty":"intermediate","updated":"2026-06-27","word_count":400,"read_minutes":2,"lang":"vi","translated":true,"requested_lang":"vi","content_markdown":"\n# Tự động hóa Webhook\n\nWebhook cho phép bạn kích hoạt hệ thống bên ngoài khi sự kiện Synapse kích\nhoạt. Hướng dẫn này bao phủ mẫu tự động hóa phổ biến.\n\n## Mẫu phổ biến\n\n### Mẫu 1: Thông báo khi bộ nhớ Critical\n\nGửi tin nhắn Slack khi bộ nhớ critical được lưu:\n\n```python\n# Webhook handler (your server)\n@app.post(\"/webhook\")\nasync def handle(request):\n    payload = await request.json()\n    \n    # Verify signature\n    if not verify_signature(payload, request.headers):\n        return 401\n    \n    if payload[\"event\"] == \"memory.store\":\n        memory = payload[\"data\"]\n        if memory.get(\"priority\") == \"critical\":\n            # Send Slack notification\n            await slack.post(\n                f\"🚨 Critical memory stored: {memory['key']}\\n{memory['content'][:200]}\"\n            )\n    \n    return 200\n```\n\nĐăng ký webhook:\n\n```bash\ncurl -X POST https://synapse.schaefer.zone/webhooks \\\n  -H \"Authorization: Bearer YOUR_MIND_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"url\": \"https://my-app.com/webhook\",\n    \"events\": \"memory.store\",\n    \"secret\": \"my-hmac-secret\"\n  }'\n```\n\n### Mẫu 2: Đồng bộ với hệ thống bên ngoài\n\nĐồng bộ bộ nhớ với Notion, Obsidian hoặc bất kỳ KB bên ngoài:\n\n```python\n@app.post(\"/webhook\")\nasync def sync_to_notion(request):\n    payload = await request.json()\n    \n    if payload[\"event\"] == \"memory.store\":\n        memory = payload[\"data\"]\n        # Create Notion page\n        await notion.create_page(\n            title=memory[\"key\"],\n            content=memory[\"content\"],\n            tags=memory.get(\"tags\", [])\n        )\n    \n    elif payload[\"event\"] == \"memory.delete\":\n        # Delete from Notion\n        await notion.delete_page(memory_id=payload[\"data\"][\"id\"])\n    \n    return 200\n```\n\n### Mẫu 3: Kích hoạt CI/CD\n\nKích hoạt triển khai khi một bộ nhớ \"release\" được lưu:\n\n```python\n@app.post(\"/webhook\")\nasync def trigger_deploy(request):\n    payload = await request.json()\n    \n    if payload[\"event\"] == \"memory.store\":\n        memory = payload[\"data\"]\n        if memory.get(\"key\", \"\").startswith(\"release_\"):\n            # Trigger GitLab pipeline\n            await gitlab.trigger_pipeline(\n                project=\"synapse\",\n                ref=\"main\",\n                variables={\"RELEASE_MEMORY_ID\": memory[\"id\"]}\n            )\n    \n    return 200\n```\n\n### Mẫu 4: Đánh thức Agent khi tin nhắn con người\n\nKích hoạt chạy LLM agent khi con người gửi tin nhắn chat:\n\n```python\n@app.post(\"/webhook\")\nasync def wake_agent(request):\n    payload = await request.json()\n    \n    if payload[\"event\"] == \"chat.message_received\":\n        message = payload[\"data\"]\n        # Queue agent processing job\n        await job_queue.enqueue(\n            \"process_message\",\n            message_id=message[\"id\"],\n            content=message[\"content\"]\n        )\n    \n    return 200\n```\n\n### Mẫu 5: Tổng hợp chỉ số\n\nTheo dõi tăng trưởng bộ nhớ, hoạt động chat, hoàn thành tác vụ:\n\n```python\n@app.post(\"/webhook\")\nasync def track_metrics(request):\n    payload = await request.json()\n    event = payload[\"event\"]\n    \n    metrics = {\n        \"memory.store\": \"memories_stored_total\",\n        \"memory.delete\": \"memories_deleted_total\",\n        \"chat.message_received\": \"messages_received_total\",\n        \"task.created\": \"tasks_created_total\",\n        \"task.completed\": \"tasks_completed_total\",\n    }\n    \n    if event in metrics:\n        await prometheus.increment(metrics[event])\n    \n    return 200\n```\n\n## Xác minh chữ ký\n\nLuôn xác minh chữ ký webhook để ngăn giả mạo:\n\n```python\nimport hmac\nimport hashlib\n\ndef verify_signature(payload_body: bytes, headers, secret: str) -> bool:\n    signature = headers.get(\"X-Synapse-Signature\", \"\")\n    if not signature.startswith(\"sha256=\"):\n        return False\n    \n    expected = hmac.new(\n        secret.encode(),\n        payload_body,\n        hashlib.sha256\n    ).hexdigest()\n    \n    return hmac.compare_digest(f\"sha256={expected}\", signature)\n```\n\n## Logic thử lại\n\nSynapse thử lại webhook thất bại với exponential backoff. Trình xử lý của bạn nên:\n\n1. **Trả 200 nhanh** — không làm công việc nặng đồng bộ\n2. **Xếp hàng công việc** — sử dụng hệ thống công việc nền\n3. **Idempotent** — cùng sự kiện có thể được gửi hai lần\n\n```python\n@app.post(\"/webhook\")\nasync def handle(request):\n    payload = await request.json()\n    # Queue for async processing\n    await job_queue.enqueue(\"process_webhook\", payload)\n    # Return immediately\n    return 200\n```\n\n## Gỡ lỗi Webhook\n\n### Kiểm tra lịch sử gửi\n\nViệc gửi webhook được ghi nhật ký. Kiểm tra gửi gần đây của webhook:\n\n```bash\n# Get webhook details including recent deliveries\ncurl -H \"Authorization: Bearer YOUR_MIND_KEY\" \\\n     https://synapse.schaefer.zone/webhooks/wh_001\n```\n\n### Kiểm tra webhook thủ công\n\n```bash\n# Trigger a test event\ncurl -X POST https://synapse.schaefer.zone/webhooks/wh_001/test \\\n  -H \"Authorization: Bearer YOUR_MIND_KEY\"\n```\n\n### Vấn đề phổ biến\n\n| Vấn đề | Khắc phục |\n|-------|-----|\n| Phản hồi 4xx | Kiểm tra trình xử lý trả 200 |\n| Phản hồi 5xx | Lỗi server — kiểm tra nhật ký ứng dụng |\n| Timeout | Trả 200 nhanh, xếp hàng công việc async |\n| Gửi trùng lặp | Làm trình xử lý idempotent |\n| Chữ ký không khớp | Xác minh secret chính xác |\n\n## Thực hành tốt nhất\n\n> [!TIP]\n> - **Luôn xác minh chữ ký** — không bao giờ bỏ qua\n> - **Trả 200 nhanh** — không chặn Synapse\n> - **Idempotent** — xử lý gửi trùng lặp\n> - **Sử dụng sự kiện cụ thể** — `memory.store` không phải `*`\n> - **Giám sát gửi thất bại** — thiết lập cảnh báo\n\n## Bước tiếp theo\n\n- [Webhooks API](/docs/api/webhooks)\n- [Cron & Scheduler](/docs/api/cron)\n- [LLM Agent cố định](/docs/guides/persistent-llm-agent)\n","content_html":"<h1>Tự động hóa Webhook</h1>\n<p>Webhook cho phép bạn kích hoạt hệ thống bên ngoài khi sự kiện Synapse kích\nhoạt. Hướng dẫn này bao phủ mẫu tự động hóa phổ biến.</p>\n<h2>Mẫu phổ biến</h2>\n<h3>Mẫu 1: Thông báo khi bộ nhớ Critical</h3>\n<p>Gửi tin nhắn Slack khi bộ nhớ critical được lưu:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-comment\"># Webhook handler (your server)</span>\n<span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    \n    <span class=\"hljs-comment\"># Verify signature</span>\n    <span class=\"hljs-keyword\">if</span> <span class=\"hljs-keyword\">not</span> verify_signature(payload, request.headers):\n        <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">401</span>\n    \n    <span class=\"hljs-keyword\">if</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;memory.store&quot;</span>:\n        memory = payload[<span class=\"hljs-string\">&quot;data&quot;</span>]\n        <span class=\"hljs-keyword\">if</span> memory.get(<span class=\"hljs-string\">&quot;priority&quot;</span>) == <span class=\"hljs-string\">&quot;critical&quot;</span>:\n            <span class=\"hljs-comment\"># Send Slack notification</span>\n            <span class=\"hljs-keyword\">await</span> slack.post(\n                <span class=\"hljs-string\">f&quot;🚨 Critical memory stored: <span class=\"hljs-subst\">{memory[<span class=\"hljs-string\">&#x27;key&#x27;</span>]}</span>\\n<span class=\"hljs-subst\">{memory[<span class=\"hljs-string\">&#x27;content&#x27;</span>][:<span class=\"hljs-number\">200</span>]}</span>&quot;</span>\n            )\n    \n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><p>Đăng ký webhook:</p>\n<pre><code class=\"hljs language-bash\">curl -X POST https://synapse.schaefer.zone/webhooks \\\n  -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span> \\\n  -H <span class=\"hljs-string\">&quot;Content-Type: application/json&quot;</span> \\\n  -d <span class=\"hljs-string\">&#x27;{\n    &quot;url&quot;: &quot;https://my-app.com/webhook&quot;,\n    &quot;events&quot;: &quot;memory.store&quot;,\n    &quot;secret&quot;: &quot;my-hmac-secret&quot;\n  }&#x27;</span></code></pre><h3>Mẫu 2: Đồng bộ với hệ thống bên ngoài</h3>\n<p>Đồng bộ bộ nhớ với Notion, Obsidian hoặc bất kỳ KB bên ngoài:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">sync_to_notion</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    \n    <span class=\"hljs-keyword\">if</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;memory.store&quot;</span>:\n        memory = payload[<span class=\"hljs-string\">&quot;data&quot;</span>]\n        <span class=\"hljs-comment\"># Create Notion page</span>\n        <span class=\"hljs-keyword\">await</span> notion.create_page(\n            title=memory[<span class=\"hljs-string\">&quot;key&quot;</span>],\n            content=memory[<span class=\"hljs-string\">&quot;content&quot;</span>],\n            tags=memory.get(<span class=\"hljs-string\">&quot;tags&quot;</span>, [])\n        )\n    \n    <span class=\"hljs-keyword\">elif</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;memory.delete&quot;</span>:\n        <span class=\"hljs-comment\"># Delete from Notion</span>\n        <span class=\"hljs-keyword\">await</span> notion.delete_page(memory_id=payload[<span class=\"hljs-string\">&quot;data&quot;</span>][<span class=\"hljs-string\">&quot;id&quot;</span>])\n    \n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h3>Mẫu 3: Kích hoạt CI/CD</h3>\n<p>Kích hoạt triển khai khi một bộ nhớ &quot;release&quot; được lưu:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">trigger_deploy</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    \n    <span class=\"hljs-keyword\">if</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;memory.store&quot;</span>:\n        memory = payload[<span class=\"hljs-string\">&quot;data&quot;</span>]\n        <span class=\"hljs-keyword\">if</span> memory.get(<span class=\"hljs-string\">&quot;key&quot;</span>, <span class=\"hljs-string\">&quot;&quot;</span>).startswith(<span class=\"hljs-string\">&quot;release_&quot;</span>):\n            <span class=\"hljs-comment\"># Trigger GitLab pipeline</span>\n            <span class=\"hljs-keyword\">await</span> gitlab.trigger_pipeline(\n                project=<span class=\"hljs-string\">&quot;synapse&quot;</span>,\n                ref=<span class=\"hljs-string\">&quot;main&quot;</span>,\n                variables={<span class=\"hljs-string\">&quot;RELEASE_MEMORY_ID&quot;</span>: memory[<span class=\"hljs-string\">&quot;id&quot;</span>]}\n            )\n    \n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h3>Mẫu 4: Đánh thức Agent khi tin nhắn con người</h3>\n<p>Kích hoạt chạy LLM agent khi con người gửi tin nhắn chat:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">wake_agent</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    \n    <span class=\"hljs-keyword\">if</span> payload[<span class=\"hljs-string\">&quot;event&quot;</span>] == <span class=\"hljs-string\">&quot;chat.message_received&quot;</span>:\n        message = payload[<span class=\"hljs-string\">&quot;data&quot;</span>]\n        <span class=\"hljs-comment\"># Queue agent processing job</span>\n        <span class=\"hljs-keyword\">await</span> job_queue.enqueue(\n            <span class=\"hljs-string\">&quot;process_message&quot;</span>,\n            message_id=message[<span class=\"hljs-string\">&quot;id&quot;</span>],\n            content=message[<span class=\"hljs-string\">&quot;content&quot;</span>]\n        )\n    \n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h3>Mẫu 5: Tổng hợp chỉ số</h3>\n<p>Theo dõi tăng trưởng bộ nhớ, hoạt động chat, hoàn thành tác vụ:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">track_metrics</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    event = payload[<span class=\"hljs-string\">&quot;event&quot;</span>]\n    \n    metrics = {\n        <span class=\"hljs-string\">&quot;memory.store&quot;</span>: <span class=\"hljs-string\">&quot;memories_stored_total&quot;</span>,\n        <span class=\"hljs-string\">&quot;memory.delete&quot;</span>: <span class=\"hljs-string\">&quot;memories_deleted_total&quot;</span>,\n        <span class=\"hljs-string\">&quot;chat.message_received&quot;</span>: <span class=\"hljs-string\">&quot;messages_received_total&quot;</span>,\n        <span class=\"hljs-string\">&quot;task.created&quot;</span>: <span class=\"hljs-string\">&quot;tasks_created_total&quot;</span>,\n        <span class=\"hljs-string\">&quot;task.completed&quot;</span>: <span class=\"hljs-string\">&quot;tasks_completed_total&quot;</span>,\n    }\n    \n    <span class=\"hljs-keyword\">if</span> event <span class=\"hljs-keyword\">in</span> metrics:\n        <span class=\"hljs-keyword\">await</span> prometheus.increment(metrics[event])\n    \n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h2>Xác minh chữ ký</h2>\n<p>Luôn xác minh chữ ký webhook để ngăn giả mạo:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import</span> hmac\n<span class=\"hljs-keyword\">import</span> hashlib\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">verify_signature</span>(<span class=\"hljs-params\">payload_body: <span class=\"hljs-built_in\">bytes</span>, headers, secret: <span class=\"hljs-built_in\">str</span></span>) -&gt; <span class=\"hljs-built_in\">bool</span>:\n    signature = headers.get(<span class=\"hljs-string\">&quot;X-Synapse-Signature&quot;</span>, <span class=\"hljs-string\">&quot;&quot;</span>)\n    <span class=\"hljs-keyword\">if</span> <span class=\"hljs-keyword\">not</span> signature.startswith(<span class=\"hljs-string\">&quot;sha256=&quot;</span>):\n        <span class=\"hljs-keyword\">return</span> <span class=\"hljs-literal\">False</span>\n    \n    expected = hmac.new(\n        secret.encode(),\n        payload_body,\n        hashlib.sha256\n    ).hexdigest()\n    \n    <span class=\"hljs-keyword\">return</span> hmac.compare_digest(<span class=\"hljs-string\">f&quot;sha256=<span class=\"hljs-subst\">{expected}</span>&quot;</span>, signature)</code></pre><h2>Logic thử lại</h2>\n<p>Synapse thử lại webhook thất bại với exponential backoff. Trình xử lý của bạn nên:</p>\n<ol>\n<li><strong>Trả 200 nhanh</strong> — không làm công việc nặng đồng bộ</li>\n<li><strong>Xếp hàng công việc</strong> — sử dụng hệ thống công việc nền</li>\n<li><strong>Idempotent</strong> — cùng sự kiện có thể được gửi hai lần</li>\n</ol>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-meta\">@app.post(<span class=\"hljs-params\"><span class=\"hljs-string\">&quot;/webhook&quot;</span></span>)</span>\n<span class=\"hljs-keyword\">async</span> <span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">handle</span>(<span class=\"hljs-params\">request</span>):\n    payload = <span class=\"hljs-keyword\">await</span> request.json()\n    <span class=\"hljs-comment\"># Queue for async processing</span>\n    <span class=\"hljs-keyword\">await</span> job_queue.enqueue(<span class=\"hljs-string\">&quot;process_webhook&quot;</span>, payload)\n    <span class=\"hljs-comment\"># Return immediately</span>\n    <span class=\"hljs-keyword\">return</span> <span class=\"hljs-number\">200</span></code></pre><h2>Gỡ lỗi Webhook</h2>\n<h3>Kiểm tra lịch sử gửi</h3>\n<p>Việc gửi webhook được ghi nhật ký. Kiểm tra gửi gần đây của webhook:</p>\n<pre><code class=\"hljs language-bash\"><span class=\"hljs-comment\"># Get webhook details including recent deliveries</span>\ncurl -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span> \\\n     https://synapse.schaefer.zone/webhooks/wh_001</code></pre><h3>Kiểm tra webhook thủ công</h3>\n<pre><code class=\"hljs language-bash\"><span class=\"hljs-comment\"># Trigger a test event</span>\ncurl -X POST https://synapse.schaefer.zone/webhooks/wh_001/test \\\n  -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span></code></pre><h3>Vấn đề phổ biến</h3>\n<table>\n<thead>\n<tr>\n<th>Vấn đề</th>\n<th>Khắc phục</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Phản hồi 4xx</td>\n<td>Kiểm tra trình xử lý trả 200</td>\n</tr>\n<tr>\n<td>Phản hồi 5xx</td>\n<td>Lỗi server — kiểm tra nhật ký ứng dụng</td>\n</tr>\n<tr>\n<td>Timeout</td>\n<td>Trả 200 nhanh, xếp hàng công việc async</td>\n</tr>\n<tr>\n<td>Gửi trùng lặp</td>\n<td>Làm trình xử lý idempotent</td>\n</tr>\n<tr>\n<td>Chữ ký không khớp</td>\n<td>Xác minh secret chính xác</td>\n</tr>\n</tbody></table>\n<h2>Thực hành tốt nhất</h2>\n<div class=\"callout callout-ok\"></div><h2>Bước tiếp theo</h2>\n<ul>\n<li><a href=\"/docs/api/webhooks\">Webhooks API</a></li>\n<li><a href=\"/docs/api/cron\">Cron &amp; Scheduler</a></li>\n<li><a href=\"/docs/guides/persistent-llm-agent\">LLM Agent cố định</a></li>\n</ul>\n","urls":{"html":"/docs/guides/webhook-automation","text":"/docs/guides/webhook-automation?format=text","json":"/docs/guides/webhook-automation?format=json","llm":"/docs/guides/webhook-automation?format=llm"},"translations_available":["en","zh","hi","es","fr","ar","pt","ru","ja","de","it","ko","nl","pl","tr","sv","vi","th","id","uk"]}