google-apps-scriptwhatsapptwilio-api

Send Whatsapp message outside FreeForm hours


I use the following Google Apps Script code to send WhatsApp messages:

function sendTrial3WhatsAppMessages() {
  var accountSid = 'AC43136d9eda4f6c428fe8bf8eXXXX'; // Replace with your Account SID
  var authToken = '301cbac10a3e1749da28e98deffXXXXX'; // Replace with your Auth Token
  var messagingServiceSid = 'MG19bfda22e0254c0812b166d7XXXXX'; // Replace with your Messaging Service SID
  var templateName = 'shipment_reminder'; // Replace with your new template name

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var today = new Date();

  for (var i = 1; i < data.length; i++) {
    var commodity = data[i][0];
    var quantity = data[i][1];
    var deadline = new Date(data[i][2]);
    var border = data[i][3];
    var phoneNumber = data[i][4];
    var optInStatus = data[i][5];

    // Skip rows where the deadline has passed or the opt-in status is not "true"
    if (today > deadline || optInStatus.toString().toLowerCase() !== 'true') {
      continue;
    }

    // Calculate the number of days left until the deadline
    var daysLeft = Math.ceil((deadline.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));

    var url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages.json';
    var payload = {
      'To': 'whatsapp:' + phoneNumber, // Ensure correct format
      'MessagingServiceSid': messagingServiceSid,
      'Body': `Hi there! This is to remind you of the following upcoming order required by ${deadline.toDateString()} :\n` +
              `Commodity: ${commodity}\n` +
              `Quantity: ${quantity}\n` +
              `Border: ${border}\n` +
              `Please complete purchase within ${daysLeft} days.`
    };

    var options = {
      'method': 'post',
      'payload': payload,
      'headers': {
        'Authorization': 'Basic ' + Utilities.base64Encode(accountSid + ':' + authToken)
      }
    };

    try {
      var response = UrlFetchApp.fetch(url, options);
      Logger.log('Message sent successfully. Response: ' + response.getContentText());
    } catch (e) {
      Logger.log('Error sending message: ' + e.message);
      Logger.log('Full response: ' + e);
    }
  }
}

// Set up a daily trigger to run this function
function createDailyTrigger3() {
  ScriptApp.newTrigger('sendTrial3WhatsAppMessages')
    .timeBased()
    .everyDays(1)
    .atHour(12)
    .nearMinute(30)
    .create();
}

the table

This code successfully sends the message, but only after the recipient "opts in". A use can opt-in by sending a message like "Yes" or "OK" to my whatsapp sender, and this needs to be done every 24 hours. If I want to send a message to recipient without them having to opt in every day, I need to use an approved whatsapp template on twilio-- which I already have. I have used the template name & SID in this code, but the messages are still not sent without user opt-in. Do I need to make changes to this code?

Here is a screenshot of the approved template: enter image description here


Solution

  • It seems you use the wrong parameters to send the message. You use the regular messaging API with the body parameter whereas you need to specific the contentSid and, if needed, contentVariables as explained here:

    I'm not familiar with app scripts but I assume the code would look similar to this:

    var url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages.json';
    var payload = {
      'To': 'whatsapp:' + phoneNumber, // Ensure correct format
      'MessagingServiceSid': messagingServiceSid,
      'ContentSid': 'HXXXXXXXXX',
      'ContentVariables':  JSON.stringify({
           1: commodity,
           2: quantity,
           3: border
         }),
    };