You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twilio Studio Flow中访问函数返回的TwiML Gather的Digits?

解决Twilio Studio中动态TwiML Gather的Digits结果获取问题

嘿,我懂你现在的处境——动态生成的Gather能正常跑起来,但就是拿不到用户输入的DTMF数字对吧?别慌,我给你两种实用的解决方案,不管你想在Twilio Function里处理,还是直接在Studio流程里做分支,都能搞定。

方案一:用Twilio Function接收并处理Digits

当用户输入完DTMF数字后,Twilio会把Digits作为请求参数发送到你指定的action地址,所以你只需要在生成Gather时明确action,再写个专门处理结果的Function就行:

1. 调整生成Gather的Function代码

确保你的Gather标签里包含action和method属性,指向处理结果的Function:

exports.handler = function(context, event, callback) {
  const twiml = new Twilio.twiml.VoiceResponse();
  // 动态获取选项数量,比如从传入的event参数里拿到numOptions
  const optionCount = event.numOptions || 3;
  
  const gather = twiml.gather({
    numDigits: 1, // 单选项就设1,多位数按需调整
    action: '/handle-gather-result', // 处理结果的Function路径
    method: 'POST' // 和接收端保持一致,Twilio默认用POST
  });
  gather.say(`请按1到${optionCount}选择对应的选项`);
  
  // 超时或无输入时的 fallback 逻辑
  twiml.say('未检测到你的输入,请重新尝试');
  twiml.redirect('/your-gather-generator-function');
  
  callback(null, twiml);
};

2. 编写处理结果的Function

在这个Function里,直接通过event.Digits就能拿到用户输入的数字:

exports.handler = function(context, event, callback) {
  const userInput = event.Digits;
  console.log(`用户选择了:${userInput}`);
  
  // 这里可以根据输入做逻辑判断,比如返回对应提示,或者跳回Studio流程
  const twiml = new Twilio.twiml.VoiceResponse();
  
  if (userInput >=1 && userInput <=10) {
    twiml.say(`你选择了选项${userInput}`);
    // 如果要回到Studio流程,把redirect指向你的Flow执行URL
    twiml.redirect('https://studio.twilio.com/v2/Flows/你的Flow SID/Executions/当前Execution SID');
  } else {
    twiml.say('输入无效,请重新选择');
    twiml.redirect('/your-gather-generator-function');
  }
  
  callback(null, twiml);
};

方案二:在Twilio Studio内部处理Digits结果

如果你想完全在Studio流程里处理输入,不用额外Function跳转,可以这么操作:

  1. 在你的Studio Flow里添加一个Incoming Request Widget,它会自动生成一个专属URL,复制这个地址。
  2. 回到生成Gather的Function,把Gather的action设置为这个Incoming Request的URL。
  3. 在Incoming Request Widget后面,添加一个Split Based On... Widget。
  4. 在拆分条件里,选择Trigger > Request Parameters > Digits,然后为每个可能的输入值(1到10)设置对应的分支,比如输入1跳转到分支A,输入2跳转到分支B,以此类推。
  5. 别忘了设置默认分支,处理用户输入无效或超时的情况。

关键注意事项

  • 如果你允许用户输入多位数字,记得调整numDigits属性,或者设置finishOnKey: '#'让用户按#结束输入。
  • 可以在Twilio Console的Logs > Function Logs里查看请求参数,确认Digits是否正确传递,方便调试。
  • 确保action指向的地址是公网可访问的(Twilio Function和Studio的Incoming Request URL默认都是公网可访问的)。

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:23:52