smstwilio-twiml

Send two SMS with Twiml


I am using a Twilio phone number and I am trying to do this: Wherever some send a texto to my Twilio number, I want them to receive an automatic reply AND I want their SMS to be forwarded to another phone number.

I found this code for the auto-reply function

exports.handler = function (context, event, callback) {
  const twiml = new Twilio.twiml.MessagingResponse();
  twiml.message('Auto reply content');
  callback(null, twiml);
};

And I also found this for the forwarding part:

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

Now I wonder how I can make both of these actions at the same time.

I tried to mix both these codes but I receive the automatic-reply on the wrong phone number


Solution

  • You can use the following example to trigger an auto-replay and forward a message to another number.

    Using Twilio API

    exports.handler = async function (context, event, callback) {
      const { To, From, Body } = event;
    
      //   getting twilio client
      /** @type {import('twilio').Twilio} */
      const client = context.getTwilioClient();
    
      // sending a reply message to the sender
      await client.messages.create({
        to: From,
        from: To,
        body: 'Auto reply content',
      });
    
      // forwarding message to specific number
      await client.messages.create({
        to: 'TargetNumber',
        from: 'CompanyNumber',
        body: `${From}: ${Body}`,
      });
    
      return callback(null, 'OK');
    };
    
    

    Using Twiml

    exports.handler = async function (context, event, callback) {
      const { From, Body } = event;
    
      /** @type {import('twilio').TwimlInterface} */
      const twiml = Twilio.twiml;
    
      const messageTwiml = new twiml.MessagingResponse();
    
      // sending a reply message to the sender
      messageTwiml.message('Auto reply content');
    
      // forwarding message to specific number
      messageTwiml.message(
        {
          to: 'targetPhone',
        },
        `${From}: ${Body}`,
      );
    
      return callback(null, messageTwiml);
    };
    
    

    I hope that it can help you! :D