Connect Your AI Agent to Telegram and WhatsApp with Webhooks
Dev Tools & Workflow

Connect Your AI Agent to Telegram and WhatsApp with Webhooks

Z
Zahid Hasan Tonmoy
December 3, 2026
8 min read
🇧🇩 বাংলায় পড়ুন
|
0 views
Audio Overview & Podcast
~1 min quick overview
0%

Connect Your AI Agent to Telegram and WhatsApp with Webhooks

A user opens Telegram on the bus, types a question, and expects an answer before the next stop. Another user does the same on WhatsApp while waiting for tea. Neither wants to open a new website, create an account, or learn a new interface. They already live in these chat apps, and that is where your AI agent needs to meet them.

This post continues the AI agent series on this blog. The earlier posts built the agent itself in Next.js — streaming with SSE, rate limiting, and saving conversation history in Supabase. You can find the whole series in the AI agent series. Now we take that same agent out of the browser and put it inside Telegram and WhatsApp.

The short answer is this: you do not need a separate app for Telegram or WhatsApp. You expose one secure webhook endpoint from your Next.js app, register that URL with Telegram and with Meta, verify every incoming request with a secret, and forward the message to the agent you already built. The agent replies, and your endpoint sends that reply back through the same chat platform.

Why webhooks, not polling

There are two ways to receive messages. Polling means your server asks, over and over, "is there anything new?" Webhooks mean the platform tells your server when something arrives. For an agent that should feel instant, webhooks win.

Polling is simple on a laptop, but it wastes requests, adds delay, and breaks on a serverless platform like Vercel, where there is no always-on process to keep asking. A webhook does nothing until a message arrives. Vercel wakes your route, your route runs, and the function goes back to sleep. You pay for work, not for waiting.

A webhook also gives you one place to enforce security: one URL, one signature to check, and one log line. Keep the entry point small.

How Telegram sends updates

Telegram's Bot API is the friendlier of the two to start with. You create a bot with BotFather, get a token, and tell Telegram where to send updates with a single setWebhook call. From then on, every message arrives as a POST request to your URL, with a JSON body describing the chat, the sender, and the text.

Telegram does not sign requests the way Meta does. Instead, you set a secret_token when you register the webhook, and Telegram sends it back in the X-Telegram-Bot-Api-Secret-Token header on every request. Your route must compare that header with the value in your environment variables, using a constant-time comparison. If the header is missing or wrong, return 401 and do nothing else.

Telegram will retry a failed delivery, so answer quickly. Validate the request, queue the work, return 200, and do the slow agent work after that. If your route waits for a thirty-second model call before answering, Telegram assumes the delivery failed and sends the same message again. Your user then gets the same answer twice, and you pay for the model twice.

How WhatsApp sends updates

WhatsApp works through Meta's Cloud API, and the setup has more steps. You create a Meta app, add the WhatsApp product, get a phone number, and generate an access token. Then you register a webhook URL and a verify token of your own choosing in the Meta dashboard.

Meta verifies your endpoint before it sends any real message. It sends a GET request with hub.mode, hub.verify_token, and hub.challenge. Your route must check that the mode is subscribe and that the token matches your stored value. If both match, return the challenge string exactly, with no extra JSON around it. If they do not match, return 403. Most first setups fail here, usually because the route returns JSON instead of the plain challenge string.

Real WhatsApp messages arrive as POST requests. Meta signs each one with an X-Hub-Signature-256 header, computed with HMAC-SHA256 over the raw request body using your App Secret. Verify that signature against the raw bytes, not against a parsed and re-serialised object, because even one whitespace change breaks the signature.

The architecture

The flow is the same for both platforms, and that is the point. Telegram and WhatsApp are only the front door. The agent, the tools, and the history stay in one place.

📊 Architecture DiagramArchitecture Flow
Interactive diagram rendering...
flowchart LR
    U[User in Telegram / WhatsApp] --> P[Telegram / Meta platform]
    P --> W[Next.js webhook route]
    W --> V{Verify secret / signature}
    V -- Invalid --> R[Return 401 / 403]
    V -- Valid --> A[AI agent: tools, memory, Supabase]
    A --> W
    W --> P
    P --> U
System architecture specification and node flow: flowchart LR U[User in Telegram / WhatsApp] --> P[Telegram / Meta platform] P --> W[Next.js webhook route] W --> V{Verify secret / signature} V -- Invalid --> R[Return 401 / 403] V -- Valid --> A[AI agent: tools, memory, Supabase] A --> W W --> P P --> U

Flow summary: the user messages in Telegram or WhatsApp, the platform forwards the update to the Next.js webhook route, the route verifies the secret or signature, the verified message goes to the AI agent, and the reply travels back through the same route and platform to the user.

Build the webhook route in Next.js

Below is a working Telegram webhook route for the Next.js App Router. It checks the secret header, parses the update, extracts the chat id and text, calls the agent, and replies through the Telegram Bot API. It uses only the standard library and fetch.

ts
// app/api/webhooks/telegram/route.ts
import { timingSafeEqual } from "node:crypto";

function secretsMatch(received: string, expected: string) {
  const a = Buffer.from(received);
  const b = Buffer.from(expected);
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

export async function POST(req: Request) {
  const secret = req.headers.get("x-telegram-bot-api-secret-token") ?? "";
  if (!secretsMatch(secret, process.env.TELEGRAM_WEBHOOK_SECRET ?? "")) {
    return new Response("Unauthorized", { status: 401 });
  }
  const update = await req.json();
  const chatId = update?.message?.chat?.id;
  const text = update?.message?.text;
  if (!chatId || typeof text !== "string" || text.trim() === "") {
    return new Response("OK", { status: 200 });
  }
  const reply = await runAgent({ chatId: String(chatId), text });
  await fetch(`https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: chatId, text: reply }),
  });
  return new Response("OK", { status: 200 });
}

async function runAgent(input: { chatId: string; text: string }) {
  // Replace this with your real agent call from the earlier posts
  // in this series: the same streaming, tools, and Supabase history.
  return `You said: ${input.text}`;
}

The WhatsApp route follows the same shape. Its GET handler returns the hub.challenge string exactly when the verify token matches, and its POST handler checks X-Hub-Signature-256 against the raw body before parsing JSON. Keep the agent behind one function, runAgent, so you can swap in the real agent without rewriting the webhook. For the full Bot API reference, including setWebhook and sendMessage, see the official Telegram Bot API documentation.

A mistake I made in production

When I first wired the Telegram bot to my agent, I deployed the webhook, sent a test message, and got two identical replies. Then three. I assumed Telegram was broken. It was not. My route took twenty seconds to call the model before returning 200, so Telegram retried the delivery, and each retry started a new model call. The fix was small: validate, queue the work, return 200 immediately, and send the reply from the background task. I also added an idempotency check on the Telegram update_id, stored in Supabase for an hour, so a duplicate delivery is dropped before the agent ever sees it. That evening taught me more than the setup docs did: in a webhook system, a slow acknowledgement is a bug, not a delay.

Common mistakes

First, skipping signature verification in development and forgetting to add it back. Write the check first. Second, logging the full request body, including tokens and phone numbers. Log only the chat id and result. Third, replying with long walls of text. Keep replies short and split a long answer into two messages. Fourth, letting the agent run without a step or token budget. Reuse the budgets from the earlier posts. Fifth, testing only with your own account. Try an emoji-only message, a voice note, and the same message twice.

Frequently Asked Questions

Do I need a separate server for Telegram and WhatsApp?

No. One Next.js app can serve both, with one route for Telegram and one for WhatsApp. Both call the same agent function, so a fix in one place helps both channels.

Why does Meta reject my webhook verification?

The most common cause is returning JSON instead of the plain challenge string. Your GET handler must return the exact hub.challenge value as plain text. The second most common cause is a mismatched verify token, so check that the token in the Meta dashboard matches the one in your environment variables exactly.

Will Telegram or WhatsApp retry a message my route fails to handle?

Yes. Telegram retries when your route does not return 200 quickly, and Meta does the same for WhatsApp. Validate, return 200 promptly, and store the update id so a duplicate delivery is ignored instead of answered twice.

🟢 Available for Freelance & Contract Work

Need a High-Performance Web App or Custom AI Solution?

I help founders, businesses, and engineering teams build lightning-fast web applications, resilient backend architectures, and intelligent AI workflows. Have an idea in mind? Let’s bring it to life.

Fast MVP Launch (2–4 weeks)
AI Agent & LLM API Integration
100/100 Core Web Vitals & SEO
Production-Ready Clean Architecture

Found this article helpful?

Give some claps to support more in-depth engineering logs!

0 views
Z

Zahid Hasan Tonmoy

Author & Developer

MERN Full Stack Developer & AI Agent Developer based in Dhaka, Bangladesh. Writing about web development, React, PostgreSQL and my learning journey.

Related Articles

Stay Updated

Subscribe to get insights on full-stack architecture, AI agent engineering, and web development.