如何使用短信挂钩延迟对用户消息的响应?

com*_*ex3 2 twilio twilio-api

我的目标是在有一些延迟的情况下回答用户消息 - 1-5 分钟。但在文档中,我看不到任何设置超时的能力。这是我的代码:

app.post('/sms', async (req, res) => {
  const twiml = new MessagingResponse();
  const msg = req.body.Body;
  const toroMsg = await toroProcess(msg);
  twiml.message(toroMsg);
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});
Run Code Online (Sandbox Code Playgroud)

phi*_*ash 6

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

使用 TwiML 进行响应时,无法延迟对 Twilio 中消息的响应

相反,您需要控制应用程序中的延迟,并稍后使用 Twilio REST API 发送消息

看起来您在问题中使用了 Express 和 Node。最简单的方法是使用setTimeout这样的:

const twilioClient = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

app.post('/sms', async (req, res) => {
  const msg = req.body.Body;
  const toroMsg = await toroProcess(msg);
  setTimeout(() => {
    twilioClient.messages.create({
      to: req.body.From,
      from: req.body.To,
      body: toroMsg
    })
  }, 60 * 1000)
  const twiml = new MessagingResponse();
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});
Run Code Online (Sandbox Code Playgroud)

由于这依赖于当前正在运行的进程,因此您可能希望使用更具弹性的东西,如果进程重新启动或崩溃,则不会丢失消息。诸如AgendaBull 之类的东西。

让我知道这是否有帮助。