{
  "name": "WhatSync: group message alert",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsync-group",
        "responseMode": "onReceived",
        "options": {
          "rawBody": true
        }
      },
      "name": "WhatsApp event",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "id": "267b7c27-a4b8-42b6-ad06-2463842b0564",
      "webhookId": "whatsync-whatsync-group",
      "notes": "Answers WhatSync at once (it waits at most 10 seconds). Raw Body must stay on: the signature is checked on the exact bytes."
    },
    {
      "parameters": {
        "jsCode": "// Checks that the request really came from WhatSync before anything else runs.\n// WhatSync signs every event (Standard Webhooks): HMAC-SHA256 of \"id.timestamp.body\" with your signing secret.\n// Paste the signing secret of your webhook below. It starts with whsec_ and is shown when you add the webhook.\nconst SECRET = 'whsec_PASTE_YOUR_SIGNING_SECRET';\n\nconst item = $input.first();\nconst headers = item.json.headers || {};\nconst id = String(headers['webhook-id'] || '');\nconst timestamp = String(headers['webhook-timestamp'] || '');\nif (SECRET.includes('PASTE_YOUR')) throw new Error('Paste your WhatSync signing secret into the \"Verify signature\" node.');\nif (!id || !/^\\d+$/.test(timestamp)) throw new Error('Rejected: the WhatSync signature headers are missing.');\nif (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error('Rejected: this event is more than 5 minutes old.');\n\n// The exact bytes WhatSync sent. Needs \"Raw Body\" switched on in the Webhook node's options.\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data');\n\n// SHA-256 and HMAC in plain JavaScript: the Code node cannot load Node's crypto module unless the server allows it.\nconst K = [], H0 = [];\nfor (let n = 2; K.length < 64; n++) {\n  let prime = true;\n  for (let d = 2; d * d <= n; d++) if (n % d === 0) { prime = false; break; }\n  if (!prime) continue;\n  if (H0.length < 8) H0.push(Math.floor((Math.sqrt(n) % 1) * 4294967296) | 0);\n  K.push(Math.floor((Math.cbrt(n) % 1) * 4294967296) | 0);\n}\nfunction sha256(bytes) {\n  const length = bytes.length;\n  const padded = Buffer.alloc(((length + 72) >> 6) << 6);\n  Buffer.from(bytes).copy(padded);\n  padded[length] = 0x80;\n  padded.writeUInt32BE(Math.floor(length / 0x20000000), padded.length - 8);\n  padded.writeUInt32BE((length << 3) >>> 0, padded.length - 4);\n  const h = H0.slice(), w = new Array(64);\n  const rotr = (x, n) => (x >>> n) | (x << (32 - n));\n  for (let offset = 0; offset < padded.length; offset += 64) {\n    for (let t = 0; t < 16; t++) w[t] = padded.readInt32BE(offset + t * 4);\n    for (let t = 16; t < 64; t++) {\n      const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3);\n      const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10);\n      w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;\n    }\n    let [a, b, c, d, e, f, g, hh] = h;\n    for (let t = 0; t < 64; t++) {\n      const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;\n      const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n      hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n    }\n    [a, b, c, d, e, f, g, hh].forEach((value, i) => { h[i] = (h[i] + value) | 0; });\n  }\n  const out = Buffer.alloc(32);\n  h.forEach((value, i) => out.writeInt32BE(value, i * 4));\n  return out;\n}\nfunction hmacSha256(key, message) {\n  if (key.length > 64) key = sha256(key);\n  const inner = Buffer.alloc(64, 0x36), outer = Buffer.alloc(64, 0x5c);\n  for (let i = 0; i < key.length; i++) { inner[i] ^= key[i]; outer[i] ^= key[i]; }\n  return sha256(Buffer.concat([outer, sha256(Buffer.concat([inner, message]))]));\n}\n\nconst key = Buffer.from(SECRET.replace(/^whsec_/, ''), 'base64');\nconst expected = hmacSha256(key, Buffer.concat([Buffer.from(id + '.' + timestamp + '.'), raw]));\n// While a secret is being rotated WhatSync sends two signatures, separated by a space. Either may match.\nconst valid = String(headers['webhook-signature'] || '').split(' ').some((entry) => {\n  const [version, encoded] = entry.split(',');\n  const actual = Buffer.from(encoded || '', 'base64');\n  if (version !== 'v1' || actual.length !== expected.length) return false;\n  let difference = 0;\n  for (let i = 0; i < expected.length; i++) difference |= actual[i] ^ expected[i];\n  return difference === 0;\n});\nif (!valid) throw new Error('Rejected: the WhatSync signature does not match. Check the signing secret.');\n\n// From here on the item is the event itself: id, type, created_at, data.\nreturn [{ json: item.json.body }];\n"
      },
      "name": "Verify signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "id": "bd646f8d-8505-42db-aca1-ffc61fa9479a"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "fd6d7546-de46-4a4c-a30f-03b89e5ef555",
              "name": "whatsyncUrl",
              "value": "https://whatsync.app",
              "type": "string"
            },
            {
              "id": "06e34b19-3946-43cf-a332-851557025a81",
              "name": "alertUrl",
              "value": "https://hooks.slack.com/services/REPLACE/WITH/YOURS",
              "type": "string"
            },
            {
              "id": "6b5945b0-1a63-49f5-aee5-b8ad5dea9d35",
              "name": "groupId",
              "value": "",
              "type": "string"
            },
            {
              "id": "358d9e0f-ca1c-417b-ade6-5f864e03d61f",
              "name": "replyText",
              "value": "Received",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        440,
        0
      ],
      "id": "3be1bc30-0c25-4c9e-a757-58e084e6f4d4",
      "notes": "groupId: one group's id from list_groups (ends in @g.us), or empty for every saved group. replyText: empty to post nothing in the group."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "08305bf6-4f75-492a-a6c6-b197d2e6a7dc",
              "leftValue": "={{ $json.type }}",
              "rightValue": "message.received",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "24345795-e7d5-4f74-ae37-12f8b8f0a954",
              "leftValue": "={{ $json.data.message.chat_type }}",
              "rightValue": "group",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            },
            {
              "id": "42695cbb-3269-4af2-a7d7-e5c2b6010117",
              "leftValue": "={{ $json.data.message.from_me }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            },
            {
              "id": "ce5aed63-30c9-44ea-a5b6-7031b09b4e2b",
              "leftValue": "={{ $json.data.message.text }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            },
            {
              "id": "a0ab01a8-8872-40a6-a119-c6a516b60f7c",
              "leftValue": "={{ !$json.groupId || $json.data.message.group.id === $json.groupId }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "From the group?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        660,
        0
      ],
      "id": "efa42482-28d0-49c5-ad21-4734f50e4b85"
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "logic": "removeItemsWithAlreadySeenKeyValues",
        "dedupeValue": "={{ $json.id }}",
        "options": {
          "scope": "workflow",
          "historySize": 10000
        }
      },
      "name": "Skip repeats",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        880,
        0
      ],
      "id": "7221ae22-98e6-4f48-aadd-e561345620d1",
      "notes": "Remembers the last 10,000 event ids across runs and drops an event it has already seen."
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings').first().json.alertUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: '[' + ($json.data.message.group.name || 'WhatsApp group') + '] ' + ($json.data.message.from.name || '+' + $json.data.message.from.phone) + ': ' + $json.data.message.text }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "name": "Tell the team",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        -120
      ],
      "id": "ca797821-40c5-4577-a219-df985cc6cb7a",
      "notes": "Works as is with a Slack incoming webhook. Swap this node for Email, Telegram or anything else that reaches a person."
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "f019d3ea-feaf-4d83-aa6b-18c805cb1201",
              "leftValue": "={{ $json.replyText }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Reply in the group?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        100
      ],
      "id": "59d55529-3880-48cb-ad8f-b91887c48692"
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "PICK_THE_SAFE_SEND_WORKFLOW",
          "mode": "list",
          "cachedResultName": "WhatSync: safe send"
        },
        "workflowInputs": {
          "mappingMode": "defineBelow",
          "value": {
            "tool": "send_group_message",
            "body": "={{ { \"jid\": $json.data.message.group.id, \"text\": $json.replyText + ': \"' + $json.data.message.text.replace(/\\s+/g, ' ').slice(0, 80) + '\"' } }}",
            "idempotencyKey": "={{ $json.id }}"
          },
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true,
          "schema": [
            {
              "id": "tool",
              "displayName": "tool",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "string"
            },
            {
              "id": "body",
              "displayName": "body",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "object"
            },
            {
              "id": "idempotencyKey",
              "displayName": "idempotencyKey",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "string"
            }
          ]
        },
        "mode": "each",
        "options": {
          "waitForSubWorkflow": true
        }
      },
      "name": "Send group reply",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        1320,
        100
      ],
      "id": "cd7cbba0-e175-49d2-a7e5-89ce9c9f1f0e"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "3200c0ca-63bf-4225-a6b4-ab4e1c8e9083",
              "leftValue": "={{ $json.ok }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Reply failed?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1540,
        100
      ],
      "id": "f861619a-16e3-4fe1-a8bb-5313638dce43"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings').first().json.alertUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'A WhatsApp group reply did NOT go out (' + $json.outcome + ', ' + $json.code + '). ' + ($json.message || '') + ($json.outcome === 'unknown' ? ' It may have been sent. Check WhatsApp before sending it by hand.' : '') }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "name": "Alert: reply not sent",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1760,
        100
      ],
      "id": "7e55a025-8fd0-4834-a64c-6964f48ada1b",
      "notes": "Works as is with a Slack incoming webhook. Swap this node for Email, Telegram or anything else that reaches a person."
    },
    {
      "parameters": {
        "content": "## WhatsApp group message: tell the team and answer \"Received\"\nWhen someone posts in a group, the team gets the message in Slack or email and the group gets a short \"Received\" that quotes the message.\n\n**Set up**\n1. Import **WhatSync: safe send** first and publish it. Pick it in **Send group reply**.\n2. Paste your webhook signing secret into **Verify signature**.\n3. Fill in **Settings**: alert URL, and the group id if you want one group only.\n4. Publish. Add the production webhook URL in WhatSync > Developers with the event message.received.\n\nThe reply quotes the message because WhatSync refuses the same text to the same group twice within an hour.\nGuide: https://whatsync.app/docs/guides/group-message-alert",
        "height": 290,
        "width": 600,
        "color": 4
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -370
      ],
      "id": "877e9033-afe5-421f-a8b8-5bda209ed68a"
    }
  ],
  "connections": {
    "WhatsApp event": {
      "main": [
        [
          {
            "node": "Verify signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify signature": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "From the group?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "From the group?": {
      "main": [
        [
          {
            "node": "Skip repeats",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip repeats": {
      "main": [
        [
          {
            "node": "Tell the team",
            "type": "main",
            "index": 0
          },
          {
            "node": "Reply in the group?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply in the group?": {
      "main": [
        [
          {
            "node": "Send group reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send group reply": {
      "main": [
        [
          {
            "node": "Reply failed?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Reply failed?": {
      "main": [
        [
          {
            "node": "Alert: reply not sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
