How to Integrate Brainfish API with WhatsApp for Automatic Responses
Overview
Use the WhatsApp Business API and Brainfish API together to automatically respond to incoming WhatsApp messages with context-sensitive answers.
When to Use This Guide
- Use this guide if you want business automation: customers message a WhatsApp Business number and a server replies using Brainfish.
- If the goal is setting up a personal WhatsApp account, this guide does not apply (install the WhatsApp app and verify a phone number instead).
High-Level Setup (Quick Summary)
- Set up a small web service environment (example uses Node.js) and install dependencies (e.g.,
express,axios). - Generate a Brainfish API token.
- Set up WhatsApp Business API in Meta (Business account, phone number, templates as needed).
- Create a webhook server that:
- Receives inbound WhatsApp webhook events
- Extracts the user message
- Calls the Brainfish API
- Sends Brainfish’s response back via the WhatsApp Business API
- Configure the webhook callback URL in the Meta Developer Dashboard and complete webhook verification.
- Test end-to-end by messaging the WhatsApp number.
This guide will teach you to create a system that automatically responds to WhatsApp messages using the Brainfish API. We’ll cover setting up a server, configuring WhatsApp Business API, and writing code to bridge Brainfish and WhatsApp.
Prerequisites
- Brainfish API Access: You’ll need an API token from Brainfish.
- WhatsApp Business API Account: Set up via Meta for business use cases.
- Node.js & npm: Install these to run a server.
Step 1: Setting Up Your Development Environment
- Install Node.js: Download and install Node.js, which includes npm (Node Package Manager).
- Set Up a New Project:
-
Open a terminal.
-
Create a project directory and initialize it with npm:
bashCopy code
mkdir whatsapp-brainfish-integration cd whatsapp-brainfish-integration npm init -y
-
- Install Required Packages:
-
We’ll use express for handling HTTP requests and axios for making API calls.
bashCopy code
npm install express axios
-
Step 2: Generate a Brainfish API Token
- Go to Brainfish Settings → Advanced → API Tokens: Brainfish API Token Page.
- Click "Create New Token", name it (e.g., "WhatsApp Integration"), and copy the token.
⚠️ Important: Keep this token safe—it should be used only on secure servers.
Step 3: Set Up WhatsApp Business API
To send automated messages on WhatsApp, you need a WhatsApp Business API account.
- Sign up on Meta for WhatsApp Business API: Visit WhatsApp Business API Getting Started.
- Get a Phone Number and Approve Message Templates:
- Register a phone number dedicated to your WhatsApp API.
- Submit and approve message templates (e.g., "Hello! Thank you for reaching out. We'll get back shortly.").
- Set Up Webhook:
- In your Meta Developer Dashboard, under Webhooks, configure the webhook URL (we’ll create it next) where incoming messages will be sent.
Step 4: Create the Server to Handle WhatsApp and Brainfish API Calls
Let’s create an Express server to handle incoming WhatsApp messages and make requests to the Brainfish API.
-
Create a new file server.js in your project directory.
-
Paste the following code:
javascriptCopy code
const express = require('express'); const axios = require('axios'); const app = express(); app.use(express.json()); // Step 4.1: Webhook endpoint for WhatsApp app.post('/webhook', async (req, res) => { try { // Step 4.2: Extract incoming message and sender details const incomingMessage = req.body.text; const senderPhone = req.body.from; // Step 4.3: Query Brainfish API with incoming message const brainfishResponse = await axios.post( 'https://app.brainfi.sh/api/articles.contextual.search', { query: incomingMessage }, { headers: { 'Authorization': 'Bearer YOUR_BRAINFISH_ACCESS_TOKEN', 'Content-Type': 'application/json', 'Accept': 'application/json' } } ); const answerText = brainfishResponse.data.data.suggestedAnswerText; // Step 4.4: Send response back to WhatsApp await axios.post( `https://graph.facebook.com/v11.0/YOUR_PHONE_NUMBER_ID/messages`, { messaging_product: 'whatsapp', to: senderPhone, type: 'text', text: { body: answerText } }, { headers: { 'Authorization': 'Bearer YOUR_WHATSAPP_TOKEN', 'Content-Type': 'application/json' } } ); res.sendStatus(200); // Acknowledge receipt of the message } catch (error) { console.error('Error handling message:', error); res.sendStatus(500); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });-
Replace
YOUR_BRAINFISH_ACCESS_TOKENwith the token from Brainfish.
-
Replace
YOUR_PHONE_NUMBER_IDand
YOUR_WHATSAPP_TOKENwith details from your WhatsApp API setup.
-
-
Start Your Server:
-
In the terminal, run:
bashCopy code
node server.js -
Your server should now be running and listening for incoming WhatsApp messages.
-
Step 5: Configure Webhook on Meta Developer Dashboard
-
Go to your WhatsApp Webhooks section on the Meta Developer Dashboard.
-
Set the Callback URL to your server’s URL (e.g.,
https://yourdomain.com/webhook).
-
Verify the Webhook:
- You may need to respond with a verification token; add this to your code if needed.
-
Save your changes.
Step 6: Test the Integration
- Send a WhatsApp Message to your registered phone number (from Step 3).
- Observe the Response:
- Your server should receive the message, send it to Brainfish, and return an answer to WhatsApp.
Sample Interaction: Consumer Use Case
- Customer: “What is Generative Language Models?”
- Response: “A Generative Language Model (GLLM) is a sophisticated AI model designed to generate coherent and contextually relevant text...”
Additional Configuration Tips
-
Logging: Use console logs or a logging service to monitor requests and troubleshoot errors.
-
Error Handling: Update the
catchblock in
server.jsto handle specific errors (e.g., expired tokens).
-
Testing on Localhost: Use tools like ngrok to expose your local server to the internet for testing webhooks.
Troubleshooting & Best Practices
- Token Management: Brainfish and WhatsApp tokens may expire. Keep track of expiry and renew tokens as needed.
- WhatsApp Message Limits: Check WhatsApp’s message rate limits to avoid restrictions.
- Compliance: Ensure responses comply with WhatsApp's guidelines.
Following these steps will set up an automatic response system for WhatsApp using Brainfish API from scratch, enhancing customer engagement with accurate, context-sensitive answers. For more support, reach out to support@brainfi.sh.
