Help

Scripting Block - Send *Single* Message

Topic Labels: Extensions
Solved
Jump to Solution
4413 5
cancel
Showing results for 
Search instead for 
Did you mean: 
Ben_Peleg
5 - Automation Enthusiast
5 - Automation Enthusiast

Hi,

I’m trying to implement a very simple scripting block to send a single text message (as opposed to the “Send SMS” block, which we use for batches).

Here’s my code, as suggested by Twilio’s API -

const phone_number = await input.textAsync('Who are we texting today? (Phone #)');
const message_body = await input.textAsync('What do you wish to say to them?');

const accountSid = <<My Account SID>>;
const authToken = <<My Auth Token>>;
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
     body: message_body,
     from: <<My Twilio Number>>,
     to: phone_number
   })
  .then(message => console.log(message.sid));

But then I get this error -

ReferenceError: require is not defined
    at main on line 6

Any suggestion?

Thanks!

1 Solution

Accepted Solutions
Mike_Pennisi
7 - App Architect
7 - App Architect

Here’s a script that lets you send a single SMS to a provided telephone number
using the Twilio service.

script source code
/**
 * Copyright 2020 Bocoup
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Twilio send SMS script
 *
 * Send a single SMS to a provided telephone number using the Twilio service
 *
 * The Airtable "Send SMS" Block (available to customers with a "Pro" account)
 * is capable of sending many messages in batches based on the contents of the
 * Airtable Base in which it is installed.
 *
 * **Notes on adapting this script.**
 *
 * The script prompts for input every time it is run. For some users, one or
 * more of these values may be the same with every execution. To streamline
 * their workflow, these users may modify this script by defining the constant
 * values in the first few lines. The values should be expressed as JavaScript
 * strings in the object named `hardCoded`.
 */
'use strict';

/**
 * Users may provide values for any of the properties in the following object
 * to streamline the script's startup.
 */
const hardCoded = {
    twilioAccountSid: '',
    twilioSendingNumber: '',
    // Note: the code in Airtable scripts is visible to all users of the
    // Airtable base. By entering the Twilio Auth Token here, all users will
    // have access to that sensitive information.
    twilioAuthToken: ''
};

/**
 * Do not edit any code following this message.
 */
output.markdown(`# Send SMS Via Twilio`);

const twilioAccountSid =
    hardCoded.twilioAccountSid || (await input.textAsync('Twilio Account SID'));
const twilioSendingNumber =
    hardCoded.twilioSendingNumber || (await input.textAsync('Twilio sending telephone number'));
const twilioAuthToken = hardCoded.twilioAuthToken || (await input.textAsync('Twilio Auth Token'));

output.table([
    {property: 'Twilio Account SID', value: twilioAccountSid},
    {property: 'Twilio sending telephone number', value: twilioSendingNumber},
    {property: 'Twilio Auth Token', value: twilioAuthToken.replace(/./g, '*')}
]);

const receivingNumber = await input.textAsync('Receiving telephone number');
const messageBody = await input.textAsync('Message');

output.text('Sending SMS...');

const url = `https://api.twilio.com/2010-04-01/Accounts/${twilioAccountSid}/Messages.json`;
const headers = {
    // Format the "Authorization" header according to "HTTP Basic Auth"
    Authorization: `Basic ${  btoa(`${twilioAccountSid}:${twilioAuthToken}`)}`,
    // Twilio expects request data to be formatted as though it were submitted
    // via an HTML form
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
};
const body = new URLSearchParams({
    From: twilioSendingNumber,
    To: receivingNumber,
    Body: messageBody
});

let result;

try {
    let response = await fetch(url, {
        method: 'POST',
        headers,
        body
    });

    if (!response.ok) {
        result = `Error sending SMS: "${await response.text()}"`;
    } else {
        result = 'SMS sent successfully.';
    }
} catch (error) {
    result = `Error sending SMS: "${error}"`;
}

output.text(result);

As noted above, the Airtable “Send SMS” Block (available to customers with a
“Pro” account) is capable of sending many messages in batches based on the
contents of the Airtable Base in which it is installed.

Notes on adapting this script.

The script prompts for input every time it is run. For some users, one or
more of these values may be the same with every execution. To streamline
their workflow, these users may modify this script by defining the constant
values in the first few lines. The values should be expressed as JavaScript
strings in the object named hardCoded.

See Solution in Thread

5 Replies 5

The require keyword is not part of vanilla JavaScript. It is a node.js function that is used to load external modules/files. However, Scripting block cannot load external files.

There are very creative ways of storing external files in tables and other places, as in this script, but determining all the required files and dependencies might not be worth it.

Thanks, I’ll look into that!

KrisCarle
4 - Data Explorer
4 - Data Explorer

You may have trouble adapting the Twilio Node library to run in the browser. To get my script to work I had to make custom Browserify builds of some of the libraries. Twilio has a simple REST API, see the CURL examples at https://www.twilio.com/docs/usage/api You could maybe post to that using fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Mike_Pennisi
7 - App Architect
7 - App Architect

Here’s a script that lets you send a single SMS to a provided telephone number
using the Twilio service.

script source code
/**
 * Copyright 2020 Bocoup
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Twilio send SMS script
 *
 * Send a single SMS to a provided telephone number using the Twilio service
 *
 * The Airtable "Send SMS" Block (available to customers with a "Pro" account)
 * is capable of sending many messages in batches based on the contents of the
 * Airtable Base in which it is installed.
 *
 * **Notes on adapting this script.**
 *
 * The script prompts for input every time it is run. For some users, one or
 * more of these values may be the same with every execution. To streamline
 * their workflow, these users may modify this script by defining the constant
 * values in the first few lines. The values should be expressed as JavaScript
 * strings in the object named `hardCoded`.
 */
'use strict';

/**
 * Users may provide values for any of the properties in the following object
 * to streamline the script's startup.
 */
const hardCoded = {
    twilioAccountSid: '',
    twilioSendingNumber: '',
    // Note: the code in Airtable scripts is visible to all users of the
    // Airtable base. By entering the Twilio Auth Token here, all users will
    // have access to that sensitive information.
    twilioAuthToken: ''
};

/**
 * Do not edit any code following this message.
 */
output.markdown(`# Send SMS Via Twilio`);

const twilioAccountSid =
    hardCoded.twilioAccountSid || (await input.textAsync('Twilio Account SID'));
const twilioSendingNumber =
    hardCoded.twilioSendingNumber || (await input.textAsync('Twilio sending telephone number'));
const twilioAuthToken = hardCoded.twilioAuthToken || (await input.textAsync('Twilio Auth Token'));

output.table([
    {property: 'Twilio Account SID', value: twilioAccountSid},
    {property: 'Twilio sending telephone number', value: twilioSendingNumber},
    {property: 'Twilio Auth Token', value: twilioAuthToken.replace(/./g, '*')}
]);

const receivingNumber = await input.textAsync('Receiving telephone number');
const messageBody = await input.textAsync('Message');

output.text('Sending SMS...');

const url = `https://api.twilio.com/2010-04-01/Accounts/${twilioAccountSid}/Messages.json`;
const headers = {
    // Format the "Authorization" header according to "HTTP Basic Auth"
    Authorization: `Basic ${  btoa(`${twilioAccountSid}:${twilioAuthToken}`)}`,
    // Twilio expects request data to be formatted as though it were submitted
    // via an HTML form
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
};
const body = new URLSearchParams({
    From: twilioSendingNumber,
    To: receivingNumber,
    Body: messageBody
});

let result;

try {
    let response = await fetch(url, {
        method: 'POST',
        headers,
        body
    });

    if (!response.ok) {
        result = `Error sending SMS: "${await response.text()}"`;
    } else {
        result = 'SMS sent successfully.';
    }
} catch (error) {
    result = `Error sending SMS: "${error}"`;
}

output.text(result);

As noted above, the Airtable “Send SMS” Block (available to customers with a
“Pro” account) is capable of sending many messages in batches based on the
contents of the Airtable Base in which it is installed.

Notes on adapting this script.

The script prompts for input every time it is run. For some users, one or
more of these values may be the same with every execution. To streamline
their workflow, these users may modify this script by defining the constant
values in the first few lines. The values should be expressed as JavaScript
strings in the object named hardCoded.

This worked like magic!
Thank you :slightly_smiling_face: