0
votes

I would like to pass along the Twilio phone number's Friendly Name when I forward the SMS message to another phone number. (The Friendly Name is a property assigned to a Twilio number when it is purchased.)

This is not the same as "Send Branded SMS Messages Using Twilio Alphanumeric Sender ID" described here and here.

I am operating in the USA where the above is not supported, and I am OK including the "Friendly Name" in the body of the forwarded message (or the subject line of the email). Also, The "Friendly Name" is not associated with the original sender of the message as in the above examples, but instead is associated with my Twilio numbers. Hope that's all clear.

I am using this example code:

Forwarding SMS messages to another phone number – Twilio Support

Three parameters are passed into the function:

exports.handler = function(context, event, callback) {

context includes environment variables I configure. callback isn't relevant to this question. And for the event parameter, we have these properties:

AccountSid
ApiVersion
Body
From
FromCity
FromCountry
FromState
FromZip
MessageSid
NumMedia
NumSegments
SmsMessageSid
SmsSid
SmsStatus
To
ToCity
ToCountry
ToState
ToZip

Using Twilio Functions, I want to obtain Friendly Name, which is not a property of event. Is it possible to obtain the Friendly Name through one of the other properties? If so, how?

UPDATE: from this Twilio doc I see a clue that I can possibly get Friendly Name from AccountSid.something.outgoing_caller_id.friendlyName

I can't quite understand how to do that in a Twilio function. I tried using:

context.getTwilioClient();

The docs say that "will return an initialized REST client that you can use to make calls to the Twilio REST API." However, it returns an empty httpClient object along with strings for username, password and accountSID. I was expecting a populated object from which I could obtain the phone number's Friendly Name.

As an aside, I would like to ask what objects get passed into the event parameter. In what circumstances would the event parameter contain different properties from those I listed above?

1

1 Answers

2
votes

You are well on the right path! Excellent research. In fact, context.getTwilioClient() is part of it. Once you have the Twilio REST API client initialized, you can use another Twilio API to determine what the FriendlyName is from the event.To. I found that here, Filter IncomingPhoneNumbers with exact match.

Below is one way, there certainly may may be others.

const got = require('got');

// async function to deal with async REST API call

exports.handler = async function(context, event, callback) {

  const client = context.getTwilioClient();

  // await an async response
  await client.incomingPhoneNumbers
    .list({phoneNumber: event.To, limit: 1})
    .then(incomingPhoneNumbers => event.friendlyName = incomingPhoneNumbers[0].friendlyName)
    .catch(err => console.log(err));

  const requestBody = {
    personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
    from: { email: context.FROM_EMAIL_ADDRESS },
    subject: `New SMS message from: ${event.From}`,
    content: [
      {
        type: 'text/plain',
        value: `${event.Body} - ${event.friendlyName}`
      }
    ]
  };

  got
    .post('https://api.sendgrid.com/v3/mail/send', {
      headers: {
        Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
        "Content-Type": 'application/json'
      },
      body: JSON.stringify(requestBody)
    })
    .then(response => {
      console.log(response);
      let twiml = new Twilio.twiml.MessagingResponse();
      twiml.message({to: '+1555xxxxxxx'}, `You Message: ${event.Body} - ${event.friendlyName}`);
      callback(null, twiml);
    })
    .catch(err => {
      console.log(err);
      callback(err);
    });
};

Specific to the key's associated with the event object, this is a handy one to use.

Object.keys(event).forEach( thisKey => console.log(`${thisKey}: ${event[thisKey]}`));