微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

记录传入消息 twilio node.js

如何解决记录传入消息 twilio node.js

我有这个基本功能,可以将消息发送回给我的 Twilio 号码发送消息的用户

因此,如果号码 1234567890 向我的 twilio 号码发送消息,它会将消息发送回 1234567890。但是,我希望能够记录用户发送给我的内容。因此,如果他们向我发送 hi,那么我可以使用它来查询我的数据库并向他们发送消息。

这是我的功能

app.post('/sms',(req,res) => {
const twiml = new MessagingResponse();

twiml.message('The Robots are coming! Head for the hills!');

res.writeHead(200,{'Content-Type': 'text/xml'});
res.end(twiml.toString());
})

解决方法

这里是 Twilio 开发者布道者。

您似乎正在使用 Node.js 和 Express 来接收来自 Twilio 的传入 Webhook。 When Twilio sends this webhook it includes a number of parameters that describe the message you received。请求以 application/x-www-form-urlencoded 格式发出,因此您需要设置 Express 以解析请求正文中的这些参数。您可以使用内置的 Express urlencoded middleware:

const express = require('express');
const app = express();

app.use(express.urlencoded());

成功解析请求后,就可以从req.body中读出参数。例如,发送消息的号码为 req.body.From,消息正文为 req.body.Body。例如:

app.post('/sms',(req,res) => {
  const { Body,From } = request.body;
  console.log(`Message from: ${From}: ${Body}`);

  const twiml = new MessagingResponse();

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200,{'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。