exports.handler = async function(context, event, callback) {
console.log(event.FlowSid + event.ExecutionSid)
const twiml = new Twilio.twiml.VoiceResponse();
const numberBlock = [context.PHONE_NUMBER]; // I added the phone number as env variable to be easier to test by changing it, otherwise need to re-build the function
isBlocked = (numberBlock.indexOf(event.Caller) !== -1) ? true : false
if(isBlocked){
twiml.reject()
console.log("reject")
const client = context.getTwilioClient()
await client.studio.v2.flows(event.FlowSid)
.executions(event.ExecutionSid)
.update({status: 'ended'})
}
else{
twiml.say("returning to Studio")
const STUDIO_URL =
twiml.redirect(STUDIO_URL)
console.log("return")
}
return callback(null, twiml)
}
Important parts:
- We pass in both FlowSid and Execution Sid (apart from the Caller). FlowSid is used in both rejection and non-rejection.
ExecutionSid is used in order to terminate the flow execution when we reject the call (otherwise the Flow will hang/keep running)
- If number is blocked we reject the call and terminate the flow execution. This uses the Execution API. Note:
---> It's async operation. So I have made the whole function "async" so I can use "await" to wait for the API to finish. You can use whatever async method you want
---> I use getTwilioClient() to initialise the client itself
- If the number is not blocked, we need to return to Studio as per this:
So we construct the URL of Studio. I prefer to do it dynamically because then you can apply this Function to any flow, without having to mess with env variables
============================================================
So now, all you need in your Studio Flow is a Twiml Redirect widget
The URL that this widget will point , is the Function URL, along with passing the parameters you need, for example: