How to Auto-Reply on WhatsApp With AI Using Twilio
Connect a Twilio WhatsApp sandbox to an Express webhook that answers messages with AI.
Twilio's WhatsApp sandbox is the fastest way to prototype an AI auto-reply on WhatsApp without waiting for business verification. You join the sandbox from your phone, point Twilio at a webhook, and reply with TwiML. This guide gets you from zero to a working bot in about ten minutes.
What you need
- A free Twilio account
- A phone with WhatsApp installed
- Node 18+ and ngrok (or any public tunnel)
- An AI API key
Step 1: Join the WhatsApp sandbox
In the Twilio Console go to Messaging > Try it out > Send a WhatsApp message. You will see a sandbox number and a join code like join velvet-tiger. Send that exact phrase from your WhatsApp to the sandbox number to opt in.
Step 2: Build the webhook
Twilio sends an HTTP POST to your webhook for each inbound message, with the text in the Body field. You answer by returning TwiML. Install the dependencies and write a small Express server.
import "dotenv/config";
import express from "express";
import twilio from "twilio";
import OpenAI from "openai";
const ai = new OpenAI();
const app = express();
app.use(express.urlencoded({ extended: false }));
app.post("/whatsapp", async (req, res) => {
const incoming = req.body.Body;
const ai_res = await ai.chat.completions.create({
model: "gpt-5-mini",
messages: [{ role: "user", content: incoming }],
});
const twiml = new twilio.twiml.MessagingResponse();
twiml.message(ai_res.choices[0].message.content);
res.type("text/xml").send(twiml.toString());
});
app.listen(3000, () => console.log("Listening on :3000"));Step 3: Expose your server and connect it
Twilio cannot reach localhost, so open a tunnel with ngrok and paste the public URL into the sandbox webhook field, with /whatsapp on the end. Set the method to HTTP POST.
Step 4: Text your bot
Result
Messages sent to the sandbox number now come back answered by AI. When you are ready to launch, swap the sandbox for an approved WhatsApp sender and keep the same webhook code.
Watch related tutorials
5:42
24:16
33:42
41:18
28:05
3:12