DEV Community

Cover image for Build a WhatsApp Chatbot with OpenAI, Twilio and Airtable
Ali Farhat
Ali Farhat Subscriber

Posted on • Originally published at scalevise.com

Build a WhatsApp Chatbot with OpenAI, Twilio and Airtable

Looking to automate customer conversations on WhatsApp using OpenAI?

Want to log every message in Airtable and trigger workflows based on what users say?

In this post, I’ll walk you through how to build a WhatsApp chatbot powered by GPT complete with real-time replies, data storage in Airtable, and an option to embed it into your website for instant interaction.

You don't need a giant team or deep backend skills. Just the right stack and this roadmap.


🧠 Why This Setup?

This bot is built with a clear goal: fast response, smart answers, and full data visibility. It’s ideal for:

Here’s the architecture:

  • WhatsApp via Twilio or 360dialog
  • Webhook (Node.js) that handles messages
  • OpenAI GPT for generating replies
  • Airtable for logging conversations and analytics
  • Optional site widget for click-to-chat

🔧 Step 1: Set Up WhatsApp Access

Use Twilio Sandbox (Test Mode)

  1. Create a Twilio account
  2. Activate the WhatsApp sandbox
  3. Link your phone to the number
  4. Note the webhook URL you’ll attach in your Twilio console

For Production: 360dialog

If you're using WhatsApp Business officially, use 360dialog.

They connect directly to Meta’s API, ideal for higher message volumes and template support.


🖥️ Step 2: Create Your Webhook Server

Spin up a Node.js server using Express. Your webhook will:

  • Receive incoming WhatsApp messages
  • Send the message to OpenAI
  • Capture the response
  • Log both message and reply to Airtable
  • Respond to the user via Twilio
// /api/whatsapp-webhook.js
const express = require('express');
const axios = require('axios');
const router = express.Router();
require('dotenv').config();

router.post('/', async (req, res) => {
  const message = req.body.Body;
  const userNumber = req.body.From;

  // Send to OpenAI
  const openaiRes = await axios.post(
    'https://api.openai.com/v1/chat/completions',
    {
      model: 'gpt-4',
      messages: [{ role: 'user', content: message }]
    },
    {
      headers: {
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
      }
    }
  );

  const reply = openaiRes.data.choices[0].message.content;

  // Save to Airtable
  await axios.post(
    'https://api.airtable.com/v0/YOUR_BASE_ID/Conversations',
    {
      fields: {
        Phone: userNumber,
        Message: message,
        Reply: reply,
        Timestamp: new Date().toISOString()
      }
    },
    {
      headers: {
        Authorization: `Bearer ${process.env.AIRTABLE_API_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  // Respond to Twilio
  res.set('Content-Type', 'text/xml');
  res.send(
    `<?xml version="1.0" encoding="UTF-8"?><Response><Message>${reply}</Message></Response>`
  );
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

🧩 Step 3: Integrate with OpenAI

Once you receive a WhatsApp message via the webhook, send the content to OpenAI:

  • Use the chat/completions endpoint (GPT-4 or GPT-3.5)
  • Format a basic prompt
  • Optional: add memory or context for smarter replies
  • Return the result
const openaiRes = await axios.post(
  'https://api.openai.com/v1/chat/completions',
  {
    model: 'gpt-4',
    messages: [{ role: 'user', content: message }]
  },
  {
    headers: {
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`
    }
  }
);

const reply = openaiRes.data.choices[0].message.content;
Enter fullscreen mode Exit fullscreen mode

Bonus: Add temperature control and max tokens to keep answers tight and clear.


📊 Step 4: Log Everything in Airtable

Create a base called Conversations. Each record should include:

  • Phone
  • User Message
  • AI Reply
  • Timestamp
  • Category (optional)

Use Airtable’s REST API to POST each interaction into a row.

await axios.post(
  'https://api.airtable.com/v0/YOUR_BASE_ID/Conversations',
  {
    fields: {
      Phone: userNumber,
      Message: message,
      Reply: reply,
      Timestamp: new Date().toISOString()
    }
  },
  {
    headers: {
      Authorization: `Bearer ${process.env.AIRTABLE_API_KEY}`,
      'Content-Type': 'application/json'
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

Then use Airtable Interfaces to visualize:

  • Conversations per user
  • Most asked questions
  • Time between replies
  • Agent confidence scores

🌐 Step 5: Embed on Your Website

Want users to start a WhatsApp chat from your site?

Here are two options:

✅ Option 1: Basic Link/Button

<a href="https://wa.me/31612345678?text=Hi!" target="_blank" rel="noopener">
  <button style="background-color:#25D366;color:white;padding:10px 15px;border:none;border-radius:5px;">
    Chat with us on WhatsApp
  </button>
</a>
Enter fullscreen mode Exit fullscreen mode

✅ Option 2: Use a Widget

Use services like GetButton.io or build your own floating button with JavaScript and Tailwind. Connect it to wa.me or the WhatsApp API and track conversions.


🔁 Bonus: Trigger Logic Based on Message Content

With OpenAI, you can go beyond answering questions. Try:

  • Extracting intent using function calling
  • Branching flows (booking, support, pricing)
  • Logging structured objects into Airtable
  • Following up with WhatsApp message templates

Use Redis or session tokens to keep chat memory between steps.


🚀 Deploy & Scale

Deploy your backend to:

  • Vercel
  • Railway
  • Render
  • AWS Lambda (for serverless)

Make sure to:

  • Store keys securely (.env)
  • Add rate limiting
  • Validate incoming payloads
  • Monitor logs and OpenAI usage
// index.js
const express = require('express');
const bodyParser = require('body-parser');
const webhook = require('./api/whatsapp-webhook');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use('/api/whatsapp-webhook', webhook);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

✅ Final Thoughts

You now have everything you need to build a smart, fast, data-rich WhatsApp chatbot. This isn’t just automation this is AI-powered conversation that drives results.

📦 Built once but scales with every message.


📣 Want This Built for You?

At Scalevise, we help companies implement smart automation stacks, from AI agents to WhatsApp integrations.

👉 Contact us

👉 Or explore our automation case studies

Let’s scale smarter and automate the conversations that slow you down.

Top comments (5)

Collapse
 
rolf_w_efbaf3d0bd30cd258a profile image
Rolf W

Thank you!

Collapse
 
vadym_info_polus profile image
Vadym

Thank you for such a deep dive into the topic!

Collapse
 
alifar profile image
Ali Farhat

You're welcome @vadym_info_polus

Collapse
 
dev-rashedin profile image
Rashedin | FullStack Developer

Wow, your article made it all look so simple!

Collapse
 
alifar profile image
Ali Farhat

It is brother! 😁