【问题标题】:Why is Twilio and Firebase not working cohesively using Node.js?为什么 Twilio 和 Firebase 不能使用 Node.js 协同工作?
【发布时间】:2018-10-15 09:08:05
【问题描述】:

为什么 twiml.message() 在一个地方工作,但在另一个地方不工作?

我想从 firebase 读取并使用 twiml/Twilio 通过 SMS 文本发送结果。代码工作的地方和不工作的地方用箭头注释。

输出应该是:“Zoey 最后一次出现在(地点)于(时间)。”

const accountSid = '**********************************';
const authToken = '*********************************;

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const bodyParser = require('body-parser');
var firebase = require('firebase');
var admin = require("firebase-admin");
var message = "N/A";

// setting the configurations for firebase
var config = {
  apiKey: "***************************************",
  authDomain: "*************.firebaseapp.com",
  databaseURL: "https://**********.firebaseio.com",
};

firebase.initializeApp(config);

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/reply', (req, res) => {
  const twiml = new MessagingResponse();
  console.log("sending: " + message);
  twiml.message(message);
});

app.post('/', (req, res) => {
  const twiml = new MessagingResponse();
  app.use(bodyParser());
  if(req.body.Body == 'Zoey') {
    // Send the message back with last known location.
    var body = 'Zoey was last seen in ';

    var databaseRef = firebase.database().ref();
    databaseRef.once('value').then(function(snap) {
      // Get the location
      var lastLocation = snap.val().lastLocation;
      console.log("last location:" + lastLocation);
      body += lastLocation;

      body += ' at ';

      // Get the timestamp
      var timestamp = snap.val().timestamp;
      console.log("at " + timestamp);
      body += timestamp;
      console.log(body);
      message = body;
      twiml.message(body); //<---------------This doesn't work
    });
  } else {
    // Bad text message. Send the error message.
    var errorMessage = 'Please type Zoey and try again!';
    twiml.message(errorMessage);
  }
  twiml.message("This Works");//<----------------This Works!
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
}).listen(process.env.PORT || 5000);

http.createServer(app).listen(1337, () => {
console.log('Server starting! Express server listening on port 1337');
});

【问题讨论】:

  • “不起作用”是什么意思。不是被调用了吗?是否被调用但抛出错误?非工作呼叫正上方的console.log(body); 是否有效?
  • 当我向 Twilio 号码发送短信时,它不会发送带有 lastLocation 和时间戳的消息正文。
  • 欢迎来到 Stack Overflow!请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
  • 好的,我很抱歉。
  • 无论您是否发送Zoey,这是否都会发送“This Works”?在您使用 twiml.toString() 响应之前,调用 twiml.message() 可能只是用最后一次调用覆盖之前的调用。

标签: javascript node.js firebase heroku twilio


【解决方案1】:

我无法测试,但在 app.post('/', ... 部分试试这个


app.post('/', (req, res) => {

    const twiml = new MessagingResponse();

    app.use(bodyParser());

    if (req.body.Body == 'Zoey') {
        // Send the message back with last known location.
        var body = 'Zoey was last seen in ';

        var databaseRef = firebase.database().ref();

        databaseRef.once('value')
            .then(function (snap) {
                // Get the location
                var lastLocation = snap.val().lastLocation;
                body += lastLocation;
                body += ' at ';

                // Get the timestamp
                var timestamp = snap.val().timestamp;
                console.log("at " + timestamp);
                body += timestamp;

                return body;
            })
            .then(body => {
                twiml.message(body);
                res.writeHead(200, { 'Content-Type': 'text/xml' });
                res.end(twiml.toString());

            });

    } else {
        // Bad text message. Send the error message.
        var errorMessage = 'Please type Zoey and try again!';
        twiml.message(errorMessage);
        res.writeHead(200, { 'Content-Type': 'text/xml' });
        res.end(twiml.toString());

    }

}).listen(process.env.PORT || 5000);

更新:解释

如果您查看原始代码,您会发现 if/else 语句用于为 Twilio 设置消息。在 if/else 之后,您有发送响应的代码。

if (req.body.Body == 'Zoey') {
  // go to Firebase
  // use data from Firebase to include in message
  // it will take some time to receive the response from Firebase
  // somewhere in here set the message for Twilio

} else {
  // don't go anywhere
  // occurring at the same time
  // somewhere in here set the message for Twilio

}

// respond to Twilio  
// executed immediately 
// it does not wait for Firebase to respond
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());

在不等待 Firebase 响应的情况下将响应发送到 Twilio 是个问题,所以...,让我们看看“Firebase 部分”。

var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(
    // execute a function when we get the response from Firebase
    // somewhere in here set the message for Twilio
);

我们能做的是

var databaseRef = firebase.database().ref();
databaseRef.once('value')
.then(
    // execute a function when we get the response from Firebase
    // return the message for Twilio
)
.then(
    // set the message for Twilio, using the argument 
    // passed by the return of the previous ".then()"
    // respond to Twilio
);

所以,代码变成:

if (req.body.Body == 'Zoey') {
    // go to Firebase
    // use data from Firebase to include in message

    var databaseRef = firebase.database().ref();
    databaseRef.once('value')
        .then(function (snap) {
            // execute code when we get the response from Firebase

            // return the message for Twilio
            // "theMessage" will be passed to the next ".then()"
            return theMessage;
        })
        .then(function (theArgument) {
            // execute code when we get the return from the previous ".then()"
            // set the message for Twilio, using the argument 
            twiml.message(theArgument);

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

} else {
    // don't go anywhere, set the message for Twilio
    twiml.message("Please type Zoey and try again!");

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

}

我确信这 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 比我更能解释承诺。


注意:如果将// respond to Twilio 代码向上移动到第一个.then() 的末尾,则可以去掉第二个.then()。

【讨论】:

    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 2014-01-20
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多