0
votes

My starting point is this answer about forwarding incoming SMS messages to email with node.js, sendgrid and Twilio Functions: https://stackoverflow.com/a/50728459/

I also looked at this tutorial: https://support.twilio.com/hc/en-us/articles/223134287-Forwarding-SMS-messages-to-another-phone-number

Can I combine both actions in one Twilio function? I prefer to combine them into one function because I don't see a method to configure a Twilio number to perform two separate "Messaging actions" in response to a message coming in. I can only pick one function to run.

I hope I simply need to add a few lines of code to the answer given above:

let twiml = new Twilio.twiml.MessagingResponse();
twiml.message(`${event.From}: ${event.Body}`, {
    to: '+13105555555'
});
callback(null, twiml);

In the function, I would like to forward the SMS to another phone number first, then forward the message to email.

The Twilio function environment variables are set up.

Here's my code:

const https = require('https');

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

    let sms_twiml = new Twilio.sms_twiml.MessagingResponse();
        sms_twiml.message(`${event.From}: ${event.Body}`, {
        to: context.TO_SMS_NUMBER
    });
    //executing a callback terminates the function
    //callback(null, sms_twiml); 

    let postData = JSON.stringify({
        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
        }]
    });

    let postOptions = {
        host: 'api.sendgrid.com',
        port: '443',
        path: '/v3/mail/send',
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ${context.SENDGRID_API_KEY}',
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(postData),
        }
    };

    let req = https.request(postOptions, function (res) {
        let email_twiml = new Twilio.email_twiml.MessagingResponse();
        callback(null, email_twiml);
    });

    req.write(postData);
    req.end();

};

I'm getting ERROR - 11200

HTTP retrieval failure There was a failure attempting to retrieve the contents of this URL. An 11200 error is an indicator of a connection failure between Twilio and your service.

1

1 Answers

4
votes

Try this code, it is one additional line from this this blog example.

(this line: twiml.message({to: '+1555xxxxxxx'}, event.Body); // Forward SMS to this Number)

const got = require('got');

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

  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
      }
    ]
  };

  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'}, event.Body); // Forward SMS to this Number
      callback(null, twiml);
    })
    .catch(err => {
      console.log(err);
      callback(err);
    });
};