twilio | twilio reminder | make a twilio call | Search

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.

Run example

npm run import -- "send a twilio message"

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;

What the code could have been:

// 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:

  1. Credentials:

  2. Twilio Library:

  3. Client Initialization:

  4. sendTwilio Function:

  5. Export:

Essentially, this code provides a reusable way to send text messages using your Twilio account.