javascript - 使用 Twilio Node 模块接收文本消息并用文本消息响应

标签 javascript node.js twilio

var http = require('http');
var twilio = require('twilio')(ACCOUNT_SID, AUTH_TOKEN);
var qs = require('querystring');

http.createServer(function (req, res) {
  var body = '';
  req.setEncoding('utf8');

  req.on('data', function(data) {
    body += data;
  });

  req.on('end', function() {
    var data = qs.parse(body);
    var jsonString = JSON.stringify(data);
    var jsonDataObject = JSON.parse(jsonString);

    // log the received message
    console.log(jsonDataObject.Body);


      twilio.messages.create({
      to:'MY_PHONE_NUMBER',
      from:'TWILIO_NUMBER',
      body:'Hello World'
      }, function(error, message) {
        if (error) {
          console.log('There was an error.')
          console.log(error.message);
        }
      });

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

}).listen(1337, '127.0.0.1');

console.log('TwiML servin\' server running at http://127.0.0.1:1337/');

I'm trying to use the Twilio node module to receive a text message and in turn respond to that text message once received. There seems to be no problem receiving the message as I'm able to log the body. But, I get a 401 Authenticate error when I try and respond to that message. I'm using ngrok to expose my localhost so I can hook it into Twilio's API. Please see below:

我哪里出错了?

Twilio Dashboard

最佳答案

这里是 Twilio 开发者布道者。

实际上,您不需要使用 REST API 来回复发送到 Twilio 号码的传入消息。事实上,您可以使用描述响应消息的 TwiML 响应传入的 HTTP 请求。

为此,您需要使用 <Message> verb 。在您的应用程序中,这看起来像:

首先,只需要 twilio 模块,无需帐户凭据:

var twilio = require("twilio");

然后,使用 TwiML 响应传入请求,如下所示:

  req.on('end', function() {
    var data = qs.parse(body);
    var jsonString = JSON.stringify(data);
    var jsonDataObject = JSON.parse(jsonString);

    // log the received message
    console.log(jsonDataObject.Body);

    var twiml = new twilio.TwimlResponse();
    twiml.message("Hello world");

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

请告诉我这是否有帮助。

关于javascript - 使用 Twilio Node 模块接收文本消息并用文本消息响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528455/

相关文章:

javascript - setState 调用后不会更新所有状态属性

javascript - websocket send(...) 是否保证消费?

java - 我如何获得 Twilio SID?

python - 如何向python脚本发送短信?

javascript - 如何在簇中制作不同颜色的标记

java - javascript中的加密和java中的解密

javascript - 回调方法不是必须在node.js中有定义吗?

node.js - 对字符串数组进行 Sequelize Op.overlap

twilio - 状态回调示例

javascript - System JS一次调用加载多个依赖