Skip to content

Instantly share code, notes, and snippets.

@caruizdiaz
Last active August 9, 2023 21:36
Show Gist options
  • Save caruizdiaz/aa042c04be32a5cfc7c808b5a93e96f7 to your computer and use it in GitHub Desktop.
Save caruizdiaz/aa042c04be32a5cfc7c808b5a93e96f7 to your computer and use it in GitHub Desktop.
Send WhatsApp message to each Google Forms submitter
//
// Part of 2Chat.co
// Learn more about how to use this code at: https://blog.2chat.co/send-a-whatsapp-message-for-each-google-form-response/
//
//
// Paste the URL you copied from the flow you created on 2Chat
//
// ❗ Replace everything inside the quotation marks with the URL generated by 2Chat ❗
//
const ENDPOINT_URL = "PASTE YOUR WEBHOOK URL HERE";
//
// The following fields can be changed at your will and depending on
// the data you are collecting with your form.
// In our case, we use the first name and the phone number of the
// person submitting the form.
//
const PHONE_NUMBER_FIELD_TITLE = "Your WhatsApp number"; // ❗ Change this value to the title you used in your form ❗
const FIRST_NAME_FIELD_TITLE = "First name"; // ❗ Change this value to the title you used in your form ❗
function onSubmit(e) {
var form = FormApp.getActiveForm();
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var response = latestResponse.getItemResponses();
var responses = {};
var formattedResponses = "";
for (var i = 0; i < response.length; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
responses[question] = answer;
//
// We group all questions and answers into a single variable, and use WhatsApp formatting
// to make it more readable to the recipient
//
// 📙 Learn more about WhatsApp formatting: https://2chat.co/tools/whatsapp-text-formatter
//
formattedResponses += `*${question}*:\n_${answer}_\n\n`;
}
//
// We build the payload to send the form submission to 2Chat
//
// The only mandatory field here is `to_number`, which is the intended recipient of our message
//
// 📙 Learn more about flows here: https://help.2chat.io/en/collections/4808619-flows
//
const payload = {
"to_number": responses[PHONE_NUMBER_FIELD_TITLE], // number of the person submitting the form
"variables": {
"firstName": responses[FIRST_NAME_FIELD_TITLE],
"responses": formattedResponses
}
}
console.log("Sending message to:", responses[PHONE_NUMBER_FIELD_TITLE]);
var options = {
"method": "POST",
"contentType": "application/json",
"payload": JSON.stringify(payload)
};
UrlFetchApp.fetch(ENDPOINT_URL, options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment