Facebook webhook 为同一条消息多次调用? [英] Facebook webhook making multiple calls for the same message?

查看:29
本文介绍了Facebook webhook 为同一条消息多次调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Python 和无服务器在 AWS 上制作并回应了机器人.

I made and echo bot on AWS with Python and serverless.

我一次又一次地收到相同的请求.我阅读了常见问题解答,其中说您必须提供状态代码 200,否则它将不断重试 webhook.

I keep getting the same request again and again. I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

我不确定我是如何做到这一点的.

I'm not sure How I do this.

我注意到呼叫的序列号总是相同的,所以我假设我发送的回复没有被确认.我的代码在这里

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged. my code is here

import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)



#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)


    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass

我在很多地方都给出了状态代码 200,但我不确定我是否仍然遇到同样的问题.

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

推荐答案

如果您收到多条消息,您的服务器没有从 Facebook 服务器向 webhook 请求返回 200 状态代码.这意味着您发生了错误,否则应返回 200.在我看来,问题出在以下几行:

If you are getting multiple messages your server did not return 200 status code to webhook request from Facebook server. This means an error occurred on your part otherwise 200 should be returned. It looks to me that problems are in following lines:

params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
headers = {"statusCode": "200","Content-Type": "application/json"}
data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                   "message": {"text": msg_txt}})

首先,您在消息的数据正文中传递 statusCode 并根据此 documentation 消息响应不应包含它.

Firstly you are passing statusCode in a data body of message and according to this documentation message response should not contain it.

另一个问题可能是在参数中发送状态代码.我会从 send_message 方法中完全删除状态代码.我怀疑那里需要它.您基本上是试图在错误的一端返回状态 200.您试图在输出而不是输入上返回它(从 Facebook 的角度来看).

Another problem could be sending status code inside params. I would remove status code completely from send_message method. I doubt its needed there. You are basically trying to return status 200 on wrong end. You are trying to return it on output instead of input (from Facebooks point of view).

因此,您很可能正确地从 Facebook 收到消息,但您仍然返回错误的状态代码,因为您正在从消息事件内部调用 send_message 方法,而 send_message 方法应返回状态400 错误请求",因为您发送的是错误请求.因此您的服务器也会返回错误的响应代码.

So its quite possible you are correctly getting message from Facebook but you are still returning wrong status code because you are calling send_message method from inside messaging event and send_message method should return status "400 bad request" because you are sending faulty request. Thus your server also returns wrong response code.

只要确保您的代码正常工作,应该返回 200.

Just make sure your code works correctly and 200 should be returned.

所以我会尝试使用以下代码:

So i would try with following code:

params  = {"access_token": os.environment['accesstoken']}
headers = {"Content-Type": "application/json"}
data = json.dumps({"recipient": {"id": send_id},
                   "message": {"text": msg_txt}})

这篇关于Facebook webhook 为同一条消息多次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆