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

Flask集成Twilio时,<Gather>的action无法调用本地voice_function.js

解决Twilio 结合Flask时action属性的问题

问题核心

你遇到的问题根源有两个:

  1. Twilio的<Gather>组件的action属性必须指向公网可访问的HTTP(S)端点,本地的voice_function.js文件路径无法被Twilio服务器访问;
  2. voice_function.js是Twilio Functions的Node.js写法,不能直接作为Flask后端的处理逻辑,需要转成Python实现。

解决方案步骤

1. 将Node.js逻辑转成Flask路由

修改你的app.py,添加一个处理按键请求的POST路由,把原来JS里的逻辑用Python实现:

from flask import Flask, request, Response
from twilio.rest import Client
from twilio.twiml.voice_response import VoiceResponse
from config import ACCOUNT_SID, AUTH_TOKEN, TWILIO_NUMBER

client = Client(ACCOUNT_SID, AUTH_TOKEN)

app = Flask(__name__)


@app.route('/')
def home():
    with open('voice.xml', 'r') as file:
        twiml_content = file.read()

    call = client.calls.create(
        to='+91xxxxxxxxxx',
        from_=TWILIO_NUMBER,
        twiml=twiml_content
    )
    return f"Call initiated with SID: {call.sid}"


@app.route('/voice_function', methods=['POST'])
def voice_function():
    # 获取用户通过DTMF输入的按键
    user_digits = request.form.get('Digits')
    print(f"User Pressed {user_digits}")

    # 生成Twiml响应
    resp = VoiceResponse()
    message = "Thanks for giving your time"

    if user_digits == "1":
        message = "That's Great! Glad we will never let you down"

    resp.say(message)
    return Response(str(resp), mimetype='application/xml')


if __name__ == "__main__":
    app.run(debug=True)

2. 修改<Gather>的action属性

Twilio需要访问你的Flask路由,本地开发时必须用工具(比如ngrok)把本地服务暴露到公网:

  • 运行ngrok http 5000(默认Flask端口是5000),得到类似https://xxxx-xx-xx-xx-xx.ngrok.io的公网地址;
  • 修改voice.xml里的action属性为该地址加上路由路径:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Message From XYZ company</Say>
    <!-- 替换成你的ngrok公网URL -->
    <Gather numDigits="1" action="https://xxxx-xx-xx-xx-xx.ngrok.io/voice_function">
        <Say>For Insurance Press 1, Press any key to end this call.</Say>
    </Gather>
</Response>

3. 测试运行

  1. 启动Flask服务:python app.py;
  2. 保持ngrok运行,确保公网地址有效;
  3. 访问Flask的根路由发起呼叫,按键后Twilio会把请求发送到你的Flask路由,返回对应的语音响应。

生产环境注意事项

如果部署到线上服务器,只需要把action属性替换成你的服务器域名+路由路径即可,无需再用ngrok。

内容的提问来源于stack exchange,提问作者Azhar Uddin Sheikh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:31:32