This example shows a minimal WhatsApp bot using Twilio and Node.js.
- Node 18+ (or Node 16+)
- Twilio account with WhatsApp sandbox or WhatsApp-enabled number
- ngrok (for local webhook testing) or a public HTTPS server
-
Install dependencies:
npm install -
Copy
.env.exampleto.envand set values:TWILIO_ACCOUNT_SID,TWILIO_AUTH_TOKENfrom Twilio consoleTWILIO_WHATSAPP_FROMis your Twilio WhatsApp number (e.g.whatsapp:+14155238886)TO_NUMBERyour personal WhatsApp number (for testing)
-
Run server:
npm start -
Expose local server with ngrok (if testing locally):
ngrok http 3000Note the HTTPS forwarding URL (e.g.
https://abcd1234.ngrok.io). -
Set your Twilio webhook for incoming messages:
- In the Twilio Console, configure the WhatsApp number's "When a message comes in" URL to:
https://<your-ngrok>.ngrok.io/webhook - Use HTTP POST.
- In the Twilio Console, configure the WhatsApp number's "When a message comes in" URL to:
-
Test:
- Send a WhatsApp message from your phone to the Twilio WhatsApp number.
- The bot will reply (echo behavior). Send
help,hello, orping.
-
Send a proactive message (server-to-user):
npm run send
- For production, use a permanent HTTPS endpoint (no ngrok).
- Use WhatsApp Cloud API (Meta) for scale / direct integration without Twilio, or use Twilio for simpler setup.
- Add conversation state, message templates, DB integration, and webhook verification.
- Implement retry/backoff, logging, monitoring, and rate limiting.