Facebook webhook making multiple calls for the same message?

I made an echo bot on AWS with Python and without a server.

I get the same request again and again. I read the faq, where it says that you need to deliver the status code 200, otherwise it will continue to retry the web host.

I am not sure how I do it.

I noticed that the sequence number is always the same for calls, so I assume that the response sent was not confirmed. 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

I have given the status code 200 in many places, and I'm not sure that I will still have a problem.

+4
source share
5 answers

, , 200 - Facebook. , , 200 . , :

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 .

. send_message. , . 200 . ( Facebook).

, , Facebook, - , send_message , send_message "400 ", . , .

, 200 .

EDIT: :

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

Facebook Messenger Node/Express . 200 , . , :

var NodeCache = require('node-cache');
var myCache = new NodeCache();

app.post('/webhook/', function(req, res) {
    var messageID = req.body.entry[0].messaging[0].message.mid;
    var checkForDupe = myCache.get(messageID);

    if (checkForDupe == undefined) {
        var setID = myCache.set(req.body.entry[0].messaging[0].message.mid, req.body.entry[0].messaging[0].message.mid);
        //Handle message .....

, -. .

+2

- 200 OK HTTP Facebook. , - Messenger. ( .) . .

response = requests.post(POST_MESSAGE_URL, headers={
            'Content-Type': 'application/json'
        }, params={
            'access_token': ACCESS_TOKEN
        }, data=json.dumps(DATA_JSON)

+1

Java, .

webhook , 200

200 . 200. , 200 .

200 , - , . , 200.

0

chatbotproxy.com, 200 1 . Facebook Messenger, 1 - . , , .

0

Source: https://habr.com/ru/post/1680506/


All Articles