Send a SMS message via Twilio

Template
Function
1
Template
Function
by
Zoran Slamkov

This function sends an SMS message to a specified phone number using Twilio's messaging service.

Created:

Heading

Voiceflow APIs used:

Channels
No items found.
Created By
Zoran Slamkov
This is some text inside of a div block.
Overview
This is some text inside of a div block.
by
This is some text inside of a div block.

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5
Heading 6

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Block quote

Ordered list

  1. Item 1
  2. Item 2
  3. Item 3

Unordered list

  • Item A
  • Item B
  • Item C

Text link

Bold text

Emphasis

Superscript

Subscript

Heading
Based in
This is some text inside of a div block.
Heading

Function Code Snippet


export default async function main(args) {
// Extract necessary variables from args
const { phoneNumber, messageBody, twilioAccountSid, twilioAuthToken, twilioNumber } = args.inputVars;

// Custom Base64 encoding
function base64Encode(str) {
// Define the character set for Base64 encoding
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let base64 = '';

for (let i = 0; i < str.length; i += 3) {
const byte1 = str.charCodeAt(i);
const byte2 = str.charCodeAt(i + 1) || 0;
const byte3 = str.charCodeAt(i + 2) || 0;

const enc1 = byte1 >> 2;
const enc2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
const enc3 = i + 1 < str.length ? ((byte2 & 0x0f) << 2) | (byte3 >> 6) : 64;
const enc4 = i + 2 < str.length ? (byte3 & 0x3f) : 64;

base64 += charSet.charAt(enc1) + charSet.charAt(enc2) + charSet.charAt(enc3) + charSet.charAt(enc4);
}

return base64;
}

// Construct the POST data string for the Twilio API request
const postData = `To=${encodeURIComponent(phoneNumber)}&From=${encodeURIComponent(twilioNumber)}&Body=${encodeURIComponent(messageBody)}`;

// Twilio API endpoint for sending SMS
const twilioUrl = `https://api.twilio.com/2010-04-01/Accounts/${twilioAccountSid}/Messages.json`;

// Prepare the authorization header using the custom base64 encoding function
const encodedCredentials = base64Encode(`${twilioAccountSid}:${twilioAuthToken}`);

// Set up the headers for the Twilio API request
const headers = {
'Authorization': `Basic ${encodedCredentials}`,
'Content-Type': 'application/x-www-form-urlencoded'
};

// Send the SMS message using Twilio's API
try {
const response = await fetch(twilioUrl, {
method: 'POST',
headers: headers,
body: postData
});

// Access the response directly (Voiceflow's modification to the standard Fetch API)
const jsonResponse = response.json; // Accessing the JSON response

// Handle the Twilio response here
if (jsonResponse && jsonResponse.sid) {
// Message sent successfully
return {
next: {
path: 'success'
},
trace: [{
type: 'text',
payload: {
message: `Message sent successfully to ${phoneNumber}`
}
}]
};
} else {
// Message failed to send
return {
next: {
path: 'fail'
},
trace: [{
type: 'text',
payload: {
message: `Failed to send message: ${jsonResponse.message}`
}
}]
};
}
} catch (error) {
// Handle fetch errors
return {
next: {
path: 'fail'
},
trace: [{
type: 'text',
payload: {
message: `Error sending message: ${error.message}`
}
}]
};
}
}
copy-icon

Explore More Templates

Build and submit a Template to have it featured in the community.

ghraphic
No items found.
No items found.