I'm writing a program in Node.js to create a WhatsApp chatbot that sends a List messages based on the different information to users. This is the desired Output:
I'm trying to find a way where I don't need to hard code the row titles for different list messages every time and the method should automatically generate this part
{"title":"row 1 title"}, {"title":"row 2 title"} .... {"title":"row n title"}
I wrote a method that takes an array of title values as an argument and generates a list based on that. But the message is not sent and I don't see any errors. I'm using WATI API as my whatsapp provider.
https://docs.wati.io/reference/post_api-v1-sendinteractivelistmessage
https://developers.facebook.com/docs/whatsapp/guides/interactive-messages/
server.js
// packages
const express = require('express');
require('dotenv').config("./env");
const WA = require('./whatsapp.js');
const cors = require('cors');
const webApp = express();
webApp.use(express.json());
webApp.use(cors());
// Route for WhatsApp
webApp.post('/whatsapp', async (req, res) => {
var data = ['row 1', 'row 2']
WA.sendListInteractive(data, whatsapp_number)
res.end();
}
);
webApp.listen(process.env.PORT, () => {
console.log(`Server is up and running at ${process.env.PORT}`);
});
whatsapp.js
const sendListInteractive = async (data, senderID) => {
data = []
var options = {
'method': 'POST',
'url': 'https://' + process.env.URL + '/api/v1/sendInteractiveListMessage?whatsappNumber=' + senderID,
'headers': {
'Authorization': process.env.API,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"header": "", //optional
"body": "Body",
"footer": "", //optional
"buttonText": "Button Text",
"sections": [
{
"title": "string",
"rows": [
data.forEach(
e => {
{
"title :" + e
}
}
)
]
}
]
})
};
request(options, function (error, response) {
if (error) console.log(error);
console.log(response.body);
});
}
Any help or advice is appreciated!.
Refer to this answer How do I create dynamic list using WhatsApp API? Create the genJSON() function as suggested.
This is just an example, you can invoke the function as per your requirement
method.js
const WA = require("./whatsapp")
function genJSON() {
var arr = ['row 1', 'row 2', 'row3']
try {
let d = []
for (const row of arr) {
d.push({
title: row
})
}
console.log(d)
WA.sendListInteractive (d, whatsapp_number)
} catch (e) {
console.log(e)
}
}
genJSON()
modified whatsapp.js
const sendListInteractive = async (jsonData, senderID) => {
data = []
var options = {
'method': 'POST',
'url': 'https://' + process.env.URL + '/api/v1/sendInteractiveListMessage?whatsappNumber=' + senderID,
'headers': {
'Authorization': process.env.API,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"header": "", //optional
"body": "Body",
"footer": "", //optional
"buttonText": "Button Text",
"sections": [
{
"title": "string",
"rows": jsonData //changes
}
]
})
};
request(options, function (error, response) {
if (error) console.log(error);
console.log(response.body);
});
}