Twilio 可编程 SMS 未在部署的 Lambda 函数中发送

Jod*_*ner 2 node.js twilio aws-lambda twilio-api serverless

我正在开发使用Twilio 可编程 SMS 的无服务器AWS 服务来传送文本消息。

当我在本地运行堆栈时(例如sls offline start),我的设置始终成功地传递消息,但在部署的环境中,我似乎甚至无法在Twilio 客户端上调用该方法上调用该方法。

消息传递的设置方式如下:

const twilio = require('twilio');

const twilioClient = twilio(
  process.env.TWILIO_SID,
  process.env.TWILIO_TOKEN,
  {
    lazyLoading: true,
  }
);

export function sendMessage(user, message) {
  twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER,
    to: user.phone,
    body: message,
  }, function(err, message) {
    console.log('error', err);
    console.log('message', message);
  });
}

// And then usage in a Serverless Function Handler

function example(event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;

  // user is also determined here
  sendMessage(user, 'This is a message');

  return {
    body: JSON.stringify({}),
    statusCode: 200
  };
}
Run Code Online (Sandbox Code Playgroud)

在本地,运行它可以工作,我可以看到message日志的输出,但日志上没有任何内容error。然而,部署后,运行它不会产生任何结果——该方法似乎甚至没有被调用(我可以在 Twilio 日志中验证没有进行 API 调用),因此没有errormessage回调中不会生成

在调试中我尝试了以下方法:

  • 我已经记录了所有环境变量(Twilio SSID、身份验证令牌、电话号码)以及函数参数,它们似乎都已就位。我还检查了 Lambda 函数本身,以确保环境变量存在。
  • 我检查了我的 CloudWatch 日志;不记录任何错误或异常。除了 Twilio 方法没有被调用之外,Lambda 函数的执行没有问题。
  • 我尝试过记录诸如twilio和 之类的东西twilioClient.messages.create类的内容,以确保客户端和函数定义不会以某种方式被删除。
  • 我想也许这与context.callbackWaitsForEmptyEventLoop所以我将其从 更改falsetrue

我一无所获,我不明白为什么这可以在本地工作,但在部署时却不能。


编辑:根据Twilio 客户端示例,如果省略回调函数,该方法将返回 Promise。我继续尝试等待该方法的响应:

export function sendMessage(user, message) {
  return twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER!,
    to: user.phone,
    body: message,
  });
}

// Usage...

async function example(event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;

  try {
    const message = await sendMessage(user, 'This is a message');
    console.log('message', message)
  } catch (error) {
    console.log('error', error);
  }

  return {
    body: JSON.stringify({}),
    statusCode: 200
  };
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,Lambda 函数成功,但消息和错误均未记录。

小智 5

我尝试过这个并且有效。我尝试使我的代码与使用类似,但进行了一些更改。

const twilio = require('twilio');

const twilioClient = twilio(
  process.env.TWILIO_SID,
  process.env.TWILIO_TOKEN
);

let user = '+14075551212';

function sendMessage(user, message) {
  return twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER,
    to: user,
    body: message,
  });
}

exports.handler = async function(event, context, callback) {
  try {
    const message = await sendMessage(user, 'This is a message');
    console.log('message', message);
    callback(null, {result: 'success'});
  } catch (error) {
    console.log('error', error);
    callback("error");
  }
};
Run Code Online (Sandbox Code Playgroud)