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

Twilio+Telegram通话机器人:Flask函数间变量传递失败求助

问题分析与修复方案

核心问题1:发起通话的URL错误

你发起Twilio通话时指定的URL没有指向/send端点,Twilio根本没触发你的send函数(除非手动测试过)。正确的URL需要拼接/send路径,并且Python字符串里不需要用HTML转义的&,直接用&即可:

call = client.calls.create(
                url= f'https://6013-71-84-89-51.ngrok.io/send?Fname={Fname}&Lname={Lname}',
                to= phone_number,
                from_= numbers,  # 这里要传random选出来的单个号码,不是原列表from_number
               
) 

核心问题2:Redirect参数传递的方式问题

Twilio默认会用POST请求访问Redirect指定的URL,但你把参数放在了query字符串里,需要明确指定Redirect的请求方法为GET,这样sent函数就能通过request.args正确拿到参数:

修改send函数里的Redirect代码:

# 添加method='GET',让Twilio用GET请求访问sent端点
response.redirect(f'https://6013-71-84-89-51.ngrok.io/sent?Fname={Fname}&Lname={Lname}', method='GET')

同时调整sent函数的参数获取方式,并且移除会导致无限循环的Redirect逻辑:

@app.route('/sent', methods=['GET', 'POST'])  # 同时支持GET和POST更稳妥
def sent():
    Fname = request.args.get('Fname')
    Lname = request.args.get('Lname')
    # 可以加打印日志方便调试
    print(f"Sent函数接收参数:Fname={Fname}, Lname={Lname}")

    response = VoiceResponse()

    response.say(f'Your last name is {Lname}')
    gather = Gather(num_digits=1, action=f'https://6013-71-84-89-51.ngrok.io/G6?Lname={Lname}')
    gather.say('Press 1 to end the call')
    response.append(gather)
    # 移除redirect回sent的代码,避免无限循环

    return str(response)

额外注意事项

  • 原代码中from_= from_number是错误的,from_参数需要传入单个号码字符串,不是列表,所以要用random.choice生成的numbers变量
  • 建议在send和sent函数中都添加打印日志,方便实时查看参数是否正常传递

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:53:19