I am creating some jobs with node-schedule that automatically send SMS's to the users of my application. The thing is that I want the users to reply to a text message with the word STOP if he/she wants to stop the job that is generating that text message.
In order of doing so, I am trying to set a job_id into the SMS's instance, so I can find the job that is linked to the corresponding message answered by the user.
This is the code I am using:
./jobs
const client = require('twilio')(twilioAccountSid, twilioAuthToken);
const phoneNumber = `${phone}`
const twilioPhoneNumber = `${twiPhone}`
const message = "message"
const alarmId = `${alarmID}`
client.messages.create(
{
to: phoneNumber,
from: twilioPhoneNumber,
body: message,
statusCallback: `${url}/api/system/sms/webhook/${alarmId}`
}
).then(response => {
return response.sid
}).catch(err => {
throw err
})
./routes
app.post(
'/sms/webhook/:id',
(req, res) => {
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const twiml = new MessagingResponse();
const alarmId = req.params.id
if (req.body.Body == 'pause') {
cancelJob(alarmId)
twiml.message(`Your alert has been deactivated`);
} else{
twiml.message(`Invalid option`);
}
res.type('text/xml').send(twiml.toString());
}
)
Route configured as webhook route in the Twilio Console:
<URL>/api/system/sms/webhook/{{id}}
Any ideas to resolve this?
I have tried altering the route, so I can access to the req.params and req.query objects but nothing seems to work. The main problem I have is at the time the user replies to the text message. It comes without any parameters in the route: '/sms/webhook/id'.
Why do you need to identify the user based on the conversation instead of the phone number?
I'd rather recommend storing all alarms in a database on your side, and then only comparing the sender's number with the subscribed numbers. If you don't want to store this data, you could also read it from the logs (as long as you never clear the logs).
PS: I'd also advise against using the word STOP as Twilio will handle this (and other) keywords for you. So, you won't be able to send a reply once a user unsubscribes.