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 开发者布道者。
实际上,您不需要使用 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/