【问题标题】:Does the post method all the function to display in Flaskpost方法是否所有功能都显示在Flask中
【发布时间】:2019-08-03 04:54:03
【问题描述】:

我正在我的代码中编写以下两个函数,以便能够处理传入的消息并通过机器人在 Messenger 上回复用户:

@app.route('/', methods=['post'])
def webhook():
    # endpoint for processing incoming messaging events
    data = request.get_json()
    print(data)  # you may not want to log every incoming message in production, but it's good for testing
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                if messaging_event.get("message"):  # someone sent us a message
                    sender_id = messaging_event["sender"]["id"]        # the Facebook ID of the person sending you the message
                    recipient_id = messaging_event["recipient"]["id"]  # the recipient's ID, which should be your page's facebook ID
                    message_text = messaging_event["message"]["text"]  # the message's text
                    responseai = response(message_text, sender_id)
                    send_message(sender_id, responseai)
                if messaging_event.get("delivery"):  # delivery confirmation
                    pass
                if messaging_event.get("optin"):  # optin confirmation
                    pass
                if messaging_event.get("postback"):  # user clicked/tapped "postback" button in earlier message
                    pass
    return "Ok", 200





 @app.route('/', methods=['GET'])
 def verify():
    # when the endpoint is registered as a web hook, it must echo back
    # the 'hub.challenge' value it receives in the query arguments
    if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
        if not request.args.get("hub.verify_token") == os.environs["VERIFY_TOKEN"]:
            return "Verification token mismatch", 403
        return request.args["hub.challenge"], 200

    return "Hello World", 200

当我访问我的 Flask 所在的 localhost:5000 时,浏览器上只显示 Hello World。我怎么知道功能 web-hook 正在工作?它是否也应该显示“Ok”?

【问题讨论】:

    标签: python flask facebook-messenger http-method


    【解决方案1】:

    如果没有一些额外的 HTML 和 Javascript 编码,您的浏览器不会发送 POST 请求。测试你的钩子是否有效的最简单方法是使用curl command-line client

    它可以发送 GET 和 POST 请求。测试您的 GET 处理程序是否正常工作:

    curl -X GET "localhost:5000/?hub.verify_token=<YOUR_VERIFY_TOKEN>&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
    

    应该产生CHALLENGE_ACCEPTED 作为输出。然后使用以下命令测试POST 处理程序:

    curl -H "Content-Type: application/json" -X POST "localhost:5000/" -d '{"sender":{"id":"<PSID>"}, "recipient":{"id":"<PAGE_ID>"}, "timestamp":1458692752478, "message":{"mid":"mid.1457764197618:41d102a3e1ae206a38", "text":"hello, world!", "quick_reply": {"payload": "<DEVELOPER_DEFINED_PAYLOAD>"}}}'
    

    请参阅 Messenger 平台入门文档的 Setting Up Your Webhook sectionmessage received event 以了解有关处理消息事件时预期的详细信息。

    另一种选择是write Python tests 覆盖相同:

    import os
    import pytest
    
    import your_flask_module
    
    @pytest.fixture
    def client():
        your_flask_module.app.config['TESTING'] = True
        yield your_flask_module.app.test_client()
    
    def test_register(client):
        args = {
            'hub.verify_token': os.environ["VERIFY_TOKEN"],
            'hub.challenge': 'CHALLENGE_ACCEPTED',
            'hub.mode': 'subscribe',
        }
        rv = client.get('/', params=args)
        assert b'CHALLANGE_ACCEPTED' in rv.data
    
    def test_message_event(client):
        event = {
            "sender": {"id": "<PSID>"},
            "recipient": {"id":"<PAGE_ID>"},
            "timestamp": 1458692752478,
            "message": {
                "mid": "mid.1457764197618:41d102a3e1ae206a38",
                "text": "hello, world!",
                "quick_reply": {
                    "payload": "<DEVELOPER_DEFINED_PAYLOAD>"
                }
            }
        }
        rv = client.post('/', json=event)
        assert rv.status_code == 200
    

    【讨论】:

    • 我已经在 node js 中运行了 CURL 命令来设置我的 webhook,但是当我检查我的本地主机时,我仍然只显示 Hello world。实际上我已经为我的 Messenger 机器人设置了所有内容,但由于错误而没有回复,我认为这是由于 POST。
    • @HateefaLowKom:但是您是否使用 curl 发出 POST 请求?
    • 不,我不是。实际上,我已经为我的 Messenger 机器人设置了所有内容,但由于错误而没有回复,我认为这是由于 POST,因为我遇到了服务器错误,当我检查我的 Heroku 日志时,我得到了这个 '2019-03- 12T17:46:43.138555+00:00 heroku[路由器]: at=info method=POST path="/" host=chatbottestbot.herokuapp.com request_id=785623ad-1d13-4d72-a42a-1c3f24595035 fwd="31.13.115.14" dyno=web.1 connect=0ms service=2ms status=500 bytes=456 protocol=https'
    • @HateefaLowKom:没有日志记录,就不可能知道是什么导致了 500 错误。我强烈建议您至少编写测试。
    猜你喜欢
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2023-03-20
    • 1970-01-01
    • 2014-11-18
    • 2018-07-13
    相关资源
    最近更新 更多