In this article, we will be exploring how to integrate the Twilio WhatsApp API with a Node.js application. Twilio provides an easy-to-use API for integrating messaging services such as WhatsApp into your applications. By the end of this tutorial, you’ll have a functioning Node.js application that can send and receive messages using the Twilio WhatsApp API.
Before we begin, ensure that you have the following installed on your system:
To start using the Twilio API, you need to create an account on their platform. Visit the Twilio website and sign up for a free account. After signing up, follow the instructions to enable the WhatsApp Sandbox. Note down the following details:
You’ll need these to authenticate your application with Twilio.
Create a new directory for your Node.js application and navigate to it in your terminal. Run the following command to initialize a new Node.js project:
npm init -y
Next, install the Twilio SDK by running:
npm install twilio
Create a new file called sendWhatsAppMessage.js and open it in your code editor. First, import the Twilio module and initialize a Twilio client using your Account SID and Auth Token:
const twilio = require('twilio');
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = new twilio(accountSid, authToken);
Replace ‘your_account_sid’ and ‘your_auth_token’ with the respective values from your Twilio account.
Now, create a function to send WhatsApp messages using the Twilio client:
async function sendWhatsAppMessage(to, message) {
try {
const response = await client.messages.create({
body: message,
from: 'whatsapp:+14155238886', // Your Twilio Sandbox Number
to: `whatsapp:${to}`,
});
console.log(`Message sent to ${to}: ${response.sid}`);
} catch (error) {
console.error(`Failed to send message: ${error}`);
}
}
sendWhatsAppMessage('+1234567890', 'Hello from Twilio WhatsApp API!'); // Replace with your phone number
Replace +1234567890 with your own phone number, including the country code, and run the script:
node sendWhatsAppMessage.js
You should receive a WhatsApp message from the Twilio Sandbox number.
To receive WhatsApp messages, you need to set up a webhook for incoming messages. We’ll use the express framework for our web server and ngrok to expose our local server to the internet. Install the required packages:
npm install express ngrok
Create a new file called receiveWhatsAppMessage.js and open it in your code editor. Set up a basic express server
const express = require('express');
const app = express();
const port = 3000;
app.use(express.urlencoded({ extended: false }));
app.post('/incoming', (req, res) => {
const message = req.body;
console.log(Received message from ${message.From}: ${message.Body});
res.status(200).send('OK');
});
app.listen(port, () => {
console.log(Server running on http://localhost:${port});
});
In this code, we create an Express server and define a route for incoming messages at `/incoming`. When a message is received, we log the sender’s phone number and message content to the console. Next, expose your local server to the internet using `ngrok`.
Create a new file called `start.js` and add the following code:
const ngrok = require('ngrok');
const { spawn } = require('child_process');
(async () => {
const url = await ngrok.connect(3000);
console.log(`ngrok tunnel opened at ${url}`);
const receiveWhatsAppMessageProcess = spawn('node', ['receiveWhatsAppMessage.js'], { stdio: 'inherit', });
process.on('SIGINT', async () => {
console.log('Shutting down…');
await ngrok.kill();
receiveWhatsAppMessage
Process.kill('SIGINT');
process.exit(0);
});
})();
This script starts the ngrok tunnel and runs our receiveWhatsAppMessage.js script as a child process. When the script is terminated, it will close the ngrok tunnel and child process.
Run the start.js script:
node start.js
You should see the ngrok tunnel URL in your console. Copy this URL and add /incoming to the end of it. Update the webhook URL for your Twilio Sandbox number by going to your Twilio Console, selecting your Sandbox number, and pasting the ngrok URL into the “A MESSAGE COMES IN” field. Save the changes.
Now, send a message to your Twilio Sandbox number, and you should see the message details logged in your console.
As a practical example, let’s create a simple echo bot that replies to incoming messages. Update the /incoming route in your receiveWhatsAppMessage.js file:
const MessagingResponse = require('twilio').twiml.MessagingResponse;
app.post('/incoming', (req, res) => {
const message = req.body;
console.log(`Received message from ${message.From}: ${message.Body}`);
const twiml = new MessagingResponse();
twiml.message(`You said: ${message.Body}`);
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
This code creates a TwiML response using the Twilio SDK’s MessagingResponse class. The response contains a new message with the original message’s content. When Twilio receives the response, it will send the reply to the sender.
Restart your start.js script, and send another message to your Twilio Sandbox number. You should receive a reply with the message content.
In this article, we’ve shown you how to integrate the Twilio WhatsApp API with a Node.js application. You learned how to send and receive messages using the Twilio API, and we demonstrated a simple echo bot example. With these building blocks, you can now create more complex chatbots and integrate WhatsApp messaging into your applications using Node.js and Twilio, In the next article, I’ll explain how to integrate WhatsApp API with ChatGPT.
Integrating Twilio WhatsApp API with a Node.js Application was originally published in Chatbots Life on Medium, where people are continuing the conversation by highlighting and responding to this story.
Neural contextual biasing allows speech recognition models to leverage contextually relevant information, leading to improved…
Today we are announcing the general availability of Amazon Bedrock Prompt Management, with new features…
The rise of Natural Language Processing (NLP) combined with traditional Structured Query Language (SQL) has…
Through his wealth and cultural influence, Elon Musk undoubtedly strengthened the Trump campaign. WIRED unpacks…
The growing use of artificial intelligence (AI)-based models is placing greater demands on the electronics…
This post is co-written with Steven Craig from Hearst. To maintain their competitive edge, organizations…