Twilio Functions : Trying to send incoming sms alert to handle STOP requests

274 views Asked by At

I am trying to send an alert SMS to an administrator phone number as well as replying to the original SMS with a local language version of the STOP response (we have turned off auto responses for this number).

The code below works for sending the response to the orignator - however, it does not send an alert SMS to the number we want (currently +447824636xxx).

I cannot find anything on the help docs, StackOverflow or Google Twilio dev group regarding how this might work in a Twilio Function.

Please advise how to get the highlighted code working.

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


console.log ("Incoming SMS")
console.log (event.From)
console.log (event.Body)

if (event.Body == "STOP" || event.Body == "Stop" || event.Body == "stop") {

console.log ("Received a STOP message")

// ***** BELOW CODE DOES NOT SEND SMS ****

// Send a warning message to Chloe
let client = context.getTwilioClient()

let c = client.messages.create({
      body: "We have a STOP message on Fresenius NO from ",
      to: "+447824636xxx",
      from: event.To
})

// ***** ABOVE CODE DOES NOT SEND ANYTHING *****

console.log ("Sent warning to Admin")

// Respond to the user/patient with STOP message in local language 
let twiml = new Twilio.twiml.MessagingResponse();
twiml.message("Du har nå meldt deg av MyFresubin og vil ikke motta flere meldinger fra dette nummeret.");
twiml.message.to = event.From
twiml.message.from = "+4759444xxx"
callback(null, twiml);
}

else {callback(null)}

}
1

There are 1 answers

0
Alex Baban On

Your code won't work because you are calling the callback function too soon and will terminate execution prior to the call to the Twilio API being able to complete.

Working code:

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

    let twiml = new Twilio.twiml.MessagingResponse();
    twiml.message("Du har nå meldt deg av MyFresubin og vil ikke motta flere ....");


    let client = context.getTwilioClient();

    // Send a warning message to Chloe
    client.messages
        .create({
            to: '+447824636xxx',
            from: event.To,
            body: "We have a STOP message on Fresenius NO from " + event.From
        })
        .then(message => {
            console.log(message.sid);

            // Respond to the user/patient with STOP message in local language
            callback(null, twiml);
        });
}

Of course, feel free to add the STOP conditional statements you have in your original code.