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

基于Twilio与Flask的SMS聊天机器人无法连接问题求助

Twilio与Flask SMS聊天机器人对接问题解决

我用Twilio和Flask开发了一个简单的SMS聊天机器人,代码能正常运行,控制台也连接上了,但Twilio始终对接不成功。看到有资料提到ngrok,现在我给Twilio号码发短信时,收到提示:

"Thanks for the message. Configure your number's SMS URL to change this message. Cheers, Londo."

相关代码

try:
    from flask import Flask, request
    import requests
    from twilio.twiml.messaging_response import MessagingResponse
    import datetime
except ModuleNotFoundError:
    from subprocess import call
    modules = ["flask","datetime"]
    call("pip install " + ' '.join(modules), shell=True)


app = Flask(__name__)

x = datetime.datetime.now()

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    responded = False
    if 'Hi' in incoming_msg:
        msg.body("Hello Londo! *Type: 'Yo*")
        responded = True
    if 'Yo' in incoming_msg:
        msg.body(f'Good morning!, the date is {x.strftime("%X")}. *Type: I am up*')
        responded = True
    if 'I am up' in incoming_msg:
        msg.body('Do 10 pushups and 5 pullups! *Type: Done*')
        responded = True
    if 'Done' in incoming_msg:
        msg.body('Now make the bed. *Type: Ok')
        responded = True
    if 'Ok' in incoming_msg:
        msg.body('Wake TF up!')
        responded = True
    if not responded:
        msg.body('I only respond to certian commands')
    return str(resp)


if __name__ == '__main__':
    app.run()

问题原因及解决步骤

1. 本地服务无法被Twilio访问

你的Flask服务默认只在本地运行(app.run()默认绑定127.0.0.1:5000),Twilio的服务器没法直接访问本地地址,这就是需要ngrok的原因——它能把本地端口映射成公网可访问的URL。

2. 配置ngrok映射本地端口

  • 安装ngrok后,打开终端运行:ngrok http 5000(如果你的Flask用了其他端口,替换对应数字)
  • 运行后会生成一个类似https://xxxx-xx-xx-xx-xx.ngrok-free.app的公网URL,复制这个地址

3. 配置Twilio号码的SMS Webhook

  • 登录Twilio控制台,找到你使用的电话号码
  • 在Messaging配置项中,找到A Message Comes In选项,选择Webhook
  • 填入刚才复制的ngrok地址,加上Flask路由路径,即https://xxxx-xx-xx-xx-xx.ngrok-free.app/bot,请求方法选POST,保存配置

4. 代码细节修正

  • 时间变量x在Flask启动时就固定了,不会实时更新,需要移到bot函数内部:
    @app.route('/bot', methods=['POST'])
    def bot():
        x = datetime.datetime.now()  # 移到此处,每次请求获取当前时间
        incoming_msg = request.values.get('Body', '').lower()
        # 后续代码不变
    
  • 修正字符串格式问题:比如"Hello Londo! *Type: 'Yo*"改成"Hello Londo! *Type: 'Yo'*",'Now make the bed. *Type: Ok'改成'Now make the bed. *Type: Ok*',避免单引号未闭合的问题

5. 验证流程

  • 确保Flask服务处于运行状态(终端执行python 你的脚本名.py)
  • 确保ngrok保持运行,公网地址有效
  • 再次给Twilio号码发短信,即可收到机器人的回复

内容的提问来源于stack exchange,提问作者Londo.py.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:35:32