如何使用 SID 获取短信的信息(例如来自 属性 的信息)?

How to fetch an SMS message's information (such as the from property) with its Sid?

我希望能够将 Sid 发送到一个号码,并让用于该号码的函数检索该 Sid 的信息。具体来说,我希望能够检索到该特定 SMS 消息的 'from' phone 号码(由 Sid 确定)。我似乎无法从 fetch 调用中获得除 AccountSid 和 Sid 之外的任何其他信息。

到目前为止我有什么(为简化这个问题而修改):

exports.handler = function(context, event, callback) {
  var Sid = event.Body;
   
  let client = context.getTwilioClient();
  // without the 'fetch()' it gets only the AccountSid and Sid, with the 'fetch()' it doesn't seem to get anything?  
  let promise = client.messages(`${Sid}`).fetch();
  var x;
  console.log(promise);
  // saw that it was returning a promise with the fetch so tried to use it here somehow, but nothing returned or worked
  promise.then(m => {
    x = m;
  });
  console.log(x);
  
  // do something, create a response message and send

  callback(null, twiml);
};

我做错了什么或需要做什么才能获得带有“sid”的消息的详细信息?

此处为 Twilio 开发人员布道师。

我认为您遇到的问题是竞争条件。针对 Twilio API 发出 API 请求是一个异步请求,您的代码指出这是一个承诺,但是在解决承诺之前,您已经调用了 callback 函数,该函数响应传入请求并终止函数,包括任何 运行 异步请求。

在调用 callback 之前,您需要等待 API 请求承诺解决。尝试这样的事情:

exports.handler = function(context, event, callback) {
  const sid = event.Body;
  const client = context.getTwilioClient();

  client.messages(sid).fetch()
    .then(message => {
      const twiml = new Twilio.twiml.MessagingResponse();
      twiml.message(`The message with sid ${sid} was sent by ${message.from}.`);
      callback(null, twiml);
    }).catch(error => {
      callback(error);
    });
};

在上面的代码中,callback 在 promise 解析或拒绝之前不会被调用。