Flask集成Twilio时,<Gather>的action无法调用本地voice_function.js
解决Twilio 结合Flask时action属性的问题
问题核心
你遇到的问题根源有两个:
- Twilio的
<Gather>组件的action属性必须指向公网可访问的HTTP(S)端点,本地的voice_function.js文件路径无法被Twilio服务器访问; 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. 测试运行
- 启动Flask服务:
python app.py; - 保持ngrok运行,确保公网地址有效;
- 访问Flask的根路由发起呼叫,按键后Twilio会把请求发送到你的Flask路由,返回对应的语音响应。
生产环境注意事项
如果部署到线上服务器,只需要把action属性替换成你的服务器域名+路由路径即可,无需再用ngrok。
内容的提问来源于stack exchange,提问作者Azhar Uddin Sheikh
相关产品推荐
相关产品推荐

