Home > Enterprise >  How do I create dynamic list using WhatsApp API?
How do I create dynamic list using WhatsApp API?

Time:06-21

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.

  1. Output when the program is executed

    Any help or advice is appreciated!.

    CodePudding user response:

    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);
            });
        }
    
  • Related