Is it possible to trigger a flow based on a condition within a function for SMS routing

Viewed 77

I have a simple flow that posts incoming SMS messages to slack. I also have a function that allows me to send SMS messages and receive them. (I.E if the SMS is from MY_NUMBER and the message starts with +12121212: then it will send the message to +12121212.

If the message is not from MY_NUMBER it will forward the SMS to MY_NUMBER)

I would like the function to trigger a flow instead of forwarding a message to MY_NUMBER.

I would like to trigger my flow after the function has run:

e.g

exports.handler = function(context, event, callback) {
    const MY_NUMBER = '+0000000000000';
         
    let twiml = new Twilio.twiml.MessagingResponse();
    if (event.From === MY_NUMBER) {
        const separatorPosition = event.Body.indexOf(':');
        if (separatorPosition < 1) {
            twiml.message('You need to specify a recipient number and a ":" before the message.');
        } else {
            const recipientNumber = event.Body.substr(0, separatorPosition).trim();
            const messageBody = event.Body.substr(separatorPosition + 1).trim();
            twiml.message({ to: recipientNumber }, messageBody);
        }
    } else {  ***MY FLOW SHOULD BE TRIGGERED HERE***
      // the above line should replace  `twiml.message({ to: MY_NUMBER }, `${event.From}: ${event.Body}`);`    
    }
    callback(null, twiml);
};
1 Answers

You can trigger Studio flows from Twilio Functions via the following code snippet:


exports.handler = function (context, event, callback) {
  const client = context.getTwilioClient();

  client.studio.v2.flows('<Flow ID>')
    .executions
    .create({ to: recipientNumber, from: MY_NUMBER })
    .then(execution => {
      return callback(null, "hello"); // You could return something else as well
    }
};

And you can find the ID of your flow in the console (or when you click on the root element and check the Flow Configuration): enter image description here

Related