简体   繁体   中英

How to change reply of message based message sent from client in Twilio using Node.js?

I am trying to make an SMS conversation platform where a user would enter yes or no which will work as a boolean check and on true Twilio server will reply with 'response 1' and on false Twilio, the server will reply with 'response 2'? How will that work in Node.js? All the library just talk about basic sending and receiving but not about changing the reply based on the message which is received.

Twilio developer evangelist here.

When you receive a message to your Twilio number, Twilio makes an HTTP request (a webhook) to a URL you provide. On the end of that URL is your application which decides how to respond. The webhook sends all the details about the message, so you can use that to make your response.

For example, if you were using Express to respond to the webhook, then you're route might look like this:

const MessagingResponse = require('twilio').twiml.MessagingResponse;

app.post('/messages', (req, res) => {
  let message = req.body.Body;
  message = message.trim().toLowerCase();
  const twiml = new MessagingResponse();
  if (message === 'yes') {
    twiml.message('You said "yes"! Fantastic!');
  else if (message === 'no') {
    twiml.message('You said "no". That's a shame.');
  } else {
    twiml.message('Please reply with a "yes" or a "no". Thank you.');
  }
  res.header('Content-Type', 'application/xml');
  res.send(twiml.toString());
});

In this case, the Body property of the request body is the message that was sent to your Twilio number and you can use conditionals to reply depending on what it said.

Let me know if that helps at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM