DEV Community

Cover image for Automating Your Form Workflows: From HTML to Slack, Notion, and Telegram
Alen | SmartForm AI
Alen | SmartForm AI

Posted on Originally published at usesmartform.com AI-assisted

Automating Your Form Workflows: From HTML to Slack, Notion, and Telegram

The moment a contact form goes live, someone has to watch the inbox for it. For a while that's fine. Then submissions arrive at 11pm, or three arrive at once and two get answered and one doesn't, or the founder who used to personally reply to every lead moves on to something else and the form quietly becomes a black hole.

Email is a queue with no delivery guarantee and no structure. A webhook gives you structure: a signed JSON payload that lands in code you control, routed to whatever system already does the work.

✅ The setup in three steps

  1. Create a form in the SmartForm AI dashboard and set its Webhook URL to your endpoint.
  2. Verify the X-SmartForm-Signature header so only real submissions get through.
  3. In that handler, fan the submission out to Slack, Notion, Telegram — anything with an HTTP API.

The webhook form backend payload you'll receive

SmartForm AI signs every webhook request with an HMAC-SHA256 of the raw request body and sends the digest in the X-SmartForm-Signature header, prefixed with sha256=.

{
  "event": "submission.created",
  "submitted_at": "2026-10-27T14:22:08.117Z",
  "form": {
    "id": "a1b2c3d4",
    "form_id": "kX9mN2pQ",
    "name": "Pricing page — enterprise demo"
  },
  "submission": {
    "id": "9f2c1a8e4b",
    "data": {
      "name": "Dana Whitfield",
      "email": "dana@acme.io",
      "company": "Acme",
      "team_size": "50-200",
      "message": "We're evaluating form backends. Can we talk about volume pricing?"
    },
    "is_spam": false,
    "spam_confidence": 0.03,
    "intent_label": "sales",
    "intent_confidence": 0.94,
    "is_high_value": true,
    "ai_summary": "Mid-size SaaS team (50-200) asking about volume pricing for a form backend evaluation.",
    "ip_address": "203.0.113.42",
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ..."
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice what's in there beyond the raw fields: intent_label (sales, support, general, feedback, other), is_high_value, and ai_summary. That means your routing logic can be a one-liner instead of a keyword regex.

Verifying the signature (do this first)

The whole point of signing is so you know the request came from your form backend and not from someone who found your endpoint URL. The verification is a handful of lines in any language.

Node.js / Express

const express = require("express");
const crypto = require("crypto");
const app = express();

const SECRET = process.env.SMARTFORM_WEBHOOK_SECRET;

function verify(rawBody, header) {
  const provided = (header || "").replace(/^sha256=/, "");
  const expected = crypto
    .createHmac("sha256", SECRET)
    .update(rawBody)
    .digest("hex");

  // timingSafeEqual throws if lengths differ — check first.
  if (provided.length !== expected.length) return false;
  return crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected));
}

app.post("/webhooks/smartform",
  express.raw({ type: "application/json" }),  // raw bytes, not parsed JSON
  (req, res) => {
    if (!verify(req.body, req.get("X-SmartForm-Signature"))) {
      return res.status(401).json({ error: "invalid signature" });
    }

    const event = JSON.parse(req.body.toString("utf8"));
    route(event);
    res.status(200).json({ received: true });
  }
);
Enter fullscreen mode Exit fullscreen mode

The express.raw() bit matters. If a global express.json() middleware parses the body first, the bytes are re-serialized and the digest no longer matches. Mount the raw parser on this route before the JSON parser, or scope your JSON parser to exclude /webhooks.

Python (Flask or Django)

import os
import hmac
import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)
SECRET = os.environ["SMARTFORM_WEBHOOK_SECRET"].encode("utf-8")

def verify(raw_body: bytes, header: str) -> bool:
    provided = (header or "").removeprefix("sha256=")
    expected = hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(provided, expected)

@app.post("/webhooks/smartform")
def smartform_webhook():
    raw = request.get_data()          # raw bytes
    if not verify(raw, request.headers.get("X-SmartForm-Signature", "")):
        return jsonify({"error": "invalid signature"}), 401

    event = request.get_json()
    route(event)
    return jsonify({"received": True}), 200
Enter fullscreen mode Exit fullscreen mode

hmac.compare_digest is the constant-time comparison — it won't leak the secret through timing differences. The Node equivalent is crypto.timingSafeEqual.

Also: respond with 2xx fast. If you fan out to three downstream services, do it in the background. The dispatcher retries three times with exponential backoff and drops the event after that — it isn't a queue, it's a best-effort courier.

Form to Slack: pushing submissions to a channel

Slack's incoming webhook takes a JSON body and posts it to a channel. The channel URL looks like https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX.

async function postToSlack(event) {
  const { submission, form } = event;
  const d = submission.data;

  // Route by AI intent, not by a keyword regex.
  const icon = submission.intent_label === "support" ? ":rotating_light:" : ":rocket:";
  const heading =
    submission.intent_label === "sales"
      ? "New sales inquiry"
      : submission.intent_label === "support"
      ? "New support request"
      : `New ${submission.intent_label} submission`;

  const body = {
    text: `${heading} — ${form.name}`,
    blocks: [
      {
        type: "header",
        text: { type: "plain_text", text: `${icon} ${heading}` },
      },
      {
        type: "section",
        fields: [
          { type: "mrkdwn", text: `*From*\n${d.name || "—"}` },
          { type: "mrkdwn", text: `*Email*\n${d.email || "—"}` },
          { type: "mrkdwn", text: `*Intent*\n${submission.intent_label} (${Math.round(submission.intent_confidence * 100)}%)` },
          { type: "mrkdwn", text: `*Submitted*\n${event.submitted_at}` },
        ],
      },
      {
        type: "section",
        text: { type: "mrkdwn", text: `*Summary*\n${submission.ai_summary || "—"}` },
      },
      ...(d.message
        ? [{
            type: "section",
            text: { type: "mrkdwn", text: `>${d.message.slice(0, 500)}` },
          }]
        : []),
      {
        type: "context",
        elements: [
          {
            type: "mrkdwn",
            text: `Form: \`${form.form_id}\` · Submission: \`${submission.id}\``,
          },
        ],
      },
    ],
  };

  await fetch(process.env.SLACK_WEBHOOK_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
}
Enter fullscreen mode Exit fullscreen mode

blocks gives you a proper card layout. text is the fallback that shows in notifications and on clients that don't render blocks — keep it populated.

Form to Notion automation: writing to a database

Notion's API wants a page object, with the database's properties as keys.

async function postToNotion(event) {
  const { submission, form } = event;
  const d = submission.data;

  await fetch("https://api.notion.com/v1/pages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.NOTION_TOKEN}`,
      "Notion-Version": "2022-06-28",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      parent: { database_id: process.env.NOTION_DATABASE_ID },
      properties: {
        Name: {
          title: [{ text: { content: d.name || "Anonymous submission" } }],
        },
        Email: {
          email: d.email || null,
        },
        Intent: {
          select: { name: submission.intent_label },
        },
        HighValue: {
          checkbox: Boolean(submission.is_high_value),
        },
        Summary: {
          rich_text: [{ text: { content: (submission.ai_summary || "").slice(0, 1900) } }],
        },
        Status: {
          select: { name: "New" },
        },
      },
      children: [
        {
          object: "block",
          type: "paragraph",
          paragraph: {
            rich_text: [{ text: { content: d.message || "(no message)" } }],
          },
        },
      ],
    }),
  });
}
Enter fullscreen mode Exit fullscreen mode

Two Notion quirks that will bite you: property names must match the database columns exactly (case included), and rich text content caps at 2000 characters per block — hence the .slice(0, 1900) on the summary.

Sharing the database with your integration is a separate step from creating the token: open the database in Notion, hit ⋯ → Connections, and add your integration. A valid token against a database you haven't shared returns a 404 that looks like a typo'd ID.

Form to Telegram: pinging a chat

Telegram's bot API is the simplest of the three. sendMessage with parse_mode: "MarkdownV2".

async function postToTelegram(event) {
  const { submission } = event;
  const d = submission.data;

  const chatId = process.env.TELEGRAM_CHAT_ID;
  const botToken = process.env.TELEGRAM_BOT_TOKEN;

  const text = [
    `*${submission.intent_label.toUpperCase()}* submission`,
    ``,
    `Name: ${d.name || "—"}`,
    `Email: ${d.email || "—"}`,
    `Summary: ${submission.ai_summary || "—"}`,
  ].join("\n");

  await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: chatId,
      text,
      parse_mode: "MarkdownV2",
      disable_web_page_preview: true,
    }),
  });
}
Enter fullscreen mode Exit fullscreen mode

MarkdownV2 is strict. Characters like ., -, (, ) and ! have to be escaped with a backslash or Telegram rejects the whole message with a 400. If you're formatting user-submitted text into the message body, escape it — a customer email containing Acme Inc. will otherwise break the send:

function escapeMarkdownV2(input = "") {
  return String(input).replace(/([_*[\]()~`>#+\-=|{}.!\\])/g, "\\$1");
}
Enter fullscreen mode Exit fullscreen mode

Use escapeMarkdownV2() on every user-supplied field before interpolating it into text.

Putting it together

app.post("/webhooks/smartform",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    if (!verify(req.body, req.get("X-SmartForm-Signature"))) {
      return res.status(401).end();
    }

    const event = JSON.parse(req.body.toString("utf8"));

    // Acknowledge immediately. Work happens after the response.
    res.status(200).json({ received: true });

    setImmediate(async () => {
      const jobs = [postToSlack(event), postToNotion(event), postToTelegram(event)];
      const results = await Promise.allSettled(jobs);
      results.forEach((r, i) => {
        if (r.status === "rejected") {
          console.error(`webhook fanout job ${i} failed:`, r.reason);
        }
      });
    });
  }
);
Enter fullscreen mode Exit fullscreen mode

Promise.allSettled over Promise.all matters: one failing destination shouldn't stop the other two from delivering.

Handling the spam branch

Your webhook receives spam submissions too — the AI filter has already made the call, and it hands you is_spam: true alongside a spam_confidence score. The useful move is to route on it:

if (submission.is_spam) {
  await db.insert({ type: "spam", payload: submission.data });
  return; // don't notify humans
}
Enter fullscreen mode Exit fullscreen mode

Quietly archive spam and keep your channels clean. A noisy Slack channel gets muted, and once it's muted you miss the real submissions too. This is also where the quota behavior of the underlying service matters: because spam submissions are filtered before they consume anything, you can run an aggressive filter without your bill reflecting the traffic — a bot hitting your form a thousand times doesn't cost you a thousand submissions.

Things that will bite you

Markdown escaping. Telegram's MarkdownV2 and Slack's mrkdwn both break on unescaped user input. Escape at the boundary, not by hand.

Rate limits on the destination. Notion allows roughly 3 requests per second per integration. If you ever route in a loop, batch it.

Missing environment variables. A missing NOTION_TOKEN throws a 401 that looks like a permissions problem. Log the destination name with the failure so you know which integration broke.

Retries. The dispatcher retries on non-2xx responses and on timeouts, up to three times with exponential backoff. Make your handler idempotent — key on submission.id — or a retry after a partial failure creates duplicates.

Testing. Fire a test submission through the playground and watch your endpoint receive it. That also lets you confirm the signature verification before real traffic arrives.

For the backend implementation of the receiving side in Python, I covered Django and Flask specifics in that guide. And if you'd rather not write any of this routing code yourself, the Node.js and Express guide covers the same ground from the JavaScript side.

Top comments (0)