自动驾驶任务中使用的 Twilio 函数应该发送短信但是 returns "an application error has occured"

Twilio function used in autopilot task should send SMS but returns "an application error has occured"

(输入后的第 2 个更新版本 - 有进展 - 谢谢)我想使用 Twilio 功能在通话期间发送短信(以避免制作完整的外部应用程序)。 目标是在自动呼叫结束时发送确认短信(使用 Twilio 自动驾驶仪)。 如果用户说出正确的句子 ("I want a confirmation by SMS please"),自动驾驶仪会启动以下任务。

{
    "actions": [
        {
            "redirect": "https://my_domain_here.twil.io/my_url_here"
        }
    ]
}

那么我的函数有以下代码:

    exports.handler = function(context, event, callback) {
    var client = context.getTwilioClient();
/**to have some view on incoming request    */
    console.log("context : "+JSON.stringify(context));
    console.log("event : "+JSON.stringify(event));
//send the answer SMS
    console.log("sending SMS");
client.messages
  .create({
    body: 'test sms',
    from: '+32x_my_nbr_xx',
    to: '+32x_my_other_nbr_xx'//is hardcoded - just to test
  })
.then(message => console.log(message.sid))
.done();
//now create the Twiml to send back to autopilot the text to be spoken
    console.log("SMS sent, returning to autopilot");
    var action = {"actions": [{"say": "I understand that you want a confirmation. I will send you a summary by SMS. Goodbye" }]};
    callback(null, action);
}

但是当我打电话说 "I want a confirmation by SMS" 时,我听到‘我知道你想要确认。我将通过短信向您发送摘要。再见”。但是没有发送短信。 当我查看自动驾驶仪的日志时,触发了正确的意图。 该函数的日志不包含任何内容(只是常规日志但不包含 Msgid) 有人有想法吗?

我知道它会起作用,但真的没有办法避免编写和维护一个完整的后端来发送这条短信吗? 提前致谢。

这里是 Twilio 开发人员布道者。

我怀疑 Autopilot 发出的请求是语音请求,这意味着您将无法 return MessageResponse,因为它仅适用于来自传入 SMS 消息的请求。

要在该函数中发送文本,您需要使用 Node 帮助程序库调用 REST API:

client.messages
  .create({
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
    from: '+15017122661',
    to: '+15558675310'
  })
.then(message => console.log(message.sid))
.done();

希望对您有所帮助。

这里是另一位 Twilio 开发人员布道者。

使用 REST API 的更新应该有所帮助,但我认为现在的问题是您在 API 请求完成之前从函数返回。不要在 promise 解析后调用 callback,而应在 promise then 函数中调用它。

像这样:

exports.handler = function(context, event, callback) {
  var client = context.getTwilioClient();
  /**to have some view on incoming request    */
  console.log('context : ' + JSON.stringify(context));
  console.log('event : ' + JSON.stringify(event));
  //send the answer SMS
  console.log('sending SMS');
  client.messages
    .create({
      body: 'test sms',
      from: '+32x_my_nbr_xx',
      to: '+32x_my_other_nbr_xx' //is hardcoded - just to test
    })
    .then(message => {
      console.log('SMS sent, returning to autopilot');
      var action = {
        actions: [
          {
            say:
              'I understand that you want a confirmation. I will send you a summary by SMS. Goodbye'
          }
        ]
      };
      callback(null, action);
    })
};