Twilio 错误 - 11200 HTTPS 检索/Python Flask 应用程序

Twilio Error - 11200 HTTPS Retrieval / Python Flask Application

我收到来自以下代码的 11200 HTTPS 检索错误。有人可以向我解释如何解决这个问题吗? (我在本地服务器上托管此应用程序并使用 ngrok https 5000 URL 用于 twilio API)

from flask import Flask, Response, request
from twilio import twiml
import os
from twilio.http.http_client import TwilioHttpClient
import requests
from twilio.rest import Client


app = Flask(__name__)
port = int(os.environ.get('PORT', 5000))


account_sid = "xxx"
auth_token = "xxx"

# proxy_client = TwilioHttpClient(proxy={'http': os.environ['http_proxy'], 'https': os.environ['https_proxy']})
client = Client(account_sid, auth_token)


@app.route("/")
def check_app():
    # returns a simple string stating the app is working
    return Response("It works!"), 200


@app.route("/twilio", methods=["POST"])
def inbound_sms():
    response = twiml.Response()
    # we get the SMS message from the request. we could also get the 
    # "To" and the "From" phone number as well
    inbound_message = request.form.get("Body")

    print(inbound_message)
    # we can now use the incoming message text in our Python application
    if inbound_message == "Hello":
        response.message("Hello back to you!")
    else:
        response.message("Hi! Not quite sure what you meant, but okay.")
    # we return back the mimetype because Twilio needs an XML response
    return Response(str(response), mimetype="application/xml"), 200


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

您混淆了 Flask 响应和 Twilio 响应,您的代码实际上是在 Python 3.6.9 下使用 Twilio Python Helper Library 版本 6.45.1 引发 AttributeError 因为Twilio 没有 twiml.Response 属性。

将你的代码改成下面的,请注意MessagingResponse的用法:

@app.route("/twilio", methods=["POST"])
def inbound_sms():
    response = MessagingResponse()
    inbound_message = request.form.get("Body")
    if inbound_message == "Hello":
        response.message("Hello back to you!")
    else:
        response.message("Hi! Not quite sure what you meant, but okay.")
    return Response(str(response), mimetype="application/xml"), 200

不要忘记将 from twilio.twiml.messaging_response import MessagingResponse 添加到您的导入中。另见 example in the Twilio documentation.

我只在本地测试过它,然后你的 /twilio 端点 returns 在用 HTTPie:

命中它时正确的 TwiML
$ http --form POST http://127.0.0.1:5000/twilio Body=Hello
HTTP/1.0 200 OK
Content-Length: 96
Content-Type: application/xml; charset=utf-8
Date: Fri, 26 Feb 2021 12:15:30 GMT
Server: Werkzeug/1.0.1 Python/3.6.9

<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello back to you!</Message></Response>