I have created a couple of functions that work fine by themselves.
Function # 1 - SMS to email. This sends an email upon receipt of SMS at Twilio 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 => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};
Function # 2 - Forward SMS. This forwards incoming SMS received at Twilio number to two mobile phone numbers:
exports.handler = function (context, event, callback) {
const twiml = new Twilio.twiml.MessagingResponse();
twiml.message(`From: ${event.From}. Body: ${event.Body}`, {
to: context.ASDA_PHONE_NUMBER,
});
twiml.message(`From: ${event.From}. Body: ${event.Body}``, {
to: context.MY_PHONE_NUMBER,
});
callback(null, twiml);
};
Both functions are working fine when linked directly to the number individually as the only service or function responding to incoming SMS.
However, when I use these functions in a Studio Flow with Run Function widgets they do not work as expected. Function #1 does not work at all. Function #2 works partially, but it seems the event.From and event.Body variables are undefined and the text of the SMS message received by the mobile phones reads "From: undefined. Body: undefined".
This is the structure of the Studio Flow with the two Run Function widgets:
Structure of the Studio Flow with a Run Function widget for each function
It seems context data, like context.MY_PHONE_NUMBER is accesible to the functions. Otherwise the second function would not be able to forward SMS. However it appears event data, like event.From, is not accessible to the functions.
I am guessing the "event" parameter in function(context, event, callback) is not being passed to the functions by the Studio Flow and I need to pass this information as parameters, but I have not found a way to do this.
CodePudding user response:
In the Run Function widget, you can add parameters. These are what will show up on your event
object in the Function.
You can use Liquid template syntax for the values to expected keys in your Run Function widget
CodePudding user response:
Twilio support helped me solve this. I added the following function parameters to each function:
Key: Body
Value: {{trigger.message.Body}}
Key: From
Value: {{trigger.message.From}}
With that, both functions work perfectly within the flow.