This code defines a function sendTwilio
that uses your Twilio account credentials to send text messages to a specified phone number. It takes the recipient's phone number and the message content as input and returns the unique identifier of the sent message.
npm run import -- "send a twilio message"
var accountSid = 'SKb0edec7c2a729ae2cb2ae0561bc0ed33'; // Your Account SID from www.twilio.com/console
var authToken = 'V53NuXy1ZJcwBXwmo6or35E7X5gNPnSY'; // Your Auth Token from www.twilio.com/console
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
function sendTwilio(to, message) {
return client.messages.create({
body: message,
to: (!to.includes('+') ? '+1' : '') + to, // Text this number
from: '+18086701280' // From a valid Twilio number
}).then(message => message.sid);
}
module.exports = sendTwilio;
// Import required libraries
const Twilio = require('twilio');
// Define Twilio credentials (environment variables are recommended for security)
const accountSid = process.env.TWILIO_ACCOUNT_SID || 'SKb0edec7c2a729ae2cb2ae0561bc0ed33';
const authToken = process.env.TWILIO_AUTH_TOKEN || 'V53NuXy1ZJcwBXwmo6or35E7X5gNPnSY';
// Initialize Twilio client
const client = new Twilio(accountSid, authToken);
/**
* Sends a Twilio message to the specified recipient.
*
* @param {string} to The recipient's phone number (including international prefix).
* @param {string} message The message to be sent.
*
* @returns {Promise<string>} A promise resolving to the message SID.
*/
async function sendTwilio(to, message) {
// Validate phone number format (optional, but recommended for robustness)
if (!/^[\+]?[\d]{3,12}$/.test(to)) {
throw new Error('Invalid phone number format');
}
// Create the message
const messageOpts = {
body: message,
to: to.includes('+')? to : `+1${to}`, // Ensure the number starts with a '+' (if not already)
from: '+18086701280' // From a valid Twilio number
};
try {
// Send the message
const message = await client.messages.create(messageOpts);
return message.sid;
} catch (error) {
// Log and rethrow the error for handling in the calling code
console.error(`Error sending Twilio message: ${error}`);
throw error;
}
}
module.exports = sendTwilio;
This code sets up a function to send text messages using the Twilio API.
Here's a breakdown:
Credentials:
accountSid
and authToken
, which are your Twilio account credentials obtained from the Twilio console.Twilio Library:
twilio
library to interact with the Twilio API.Client Initialization:
twilio
client object using your credentials.sendTwilio
Function:
to
(phone number) and message
as input.+1
if needed), and a Twilio sender number.client.messages.create()
to send the message through the Twilio API.sid
(unique identifier) of the sent message.Export:
sendTwilio
function is exported, allowing other parts of the application to use it to send text messages.Essentially, this code provides a reusable way to send text messages using your Twilio account.