Neurotech-HQ / heyoo

Opensource python wrapper to WhatsApp Cloud API
https://pypi.org/project/heyoo/
MIT License
448 stars 100 forks source link

Receiving multiple webhook new message data for single question #84

Closed hitz02 closed 1 year ago

hitz02 commented 1 year ago

Thanks for building this wonderful wrapper.

My problem is - I am receiving the same new message webhook data multiple times even if it's asked once on WhatsApp. I visited the issues sections to check comments but this one looks different to me. I do not have more than one app tied to the same account which was the case for a few.

My app uses langchain and openai internally to generate responses to incoming message. And at times it takes some seconds or even a minute to generate a response. And probably this could be one of the reasons the 200 status ack is delayed and WhatsApp pings the same question to webhook again and again until it receives 200 ack from one of the previous requests.

I am not 100% sure if the above case is true. If it is, I would like to know in the WhatsApp cloud API account -

If not, how can we handle the delay in the code itself?

Any help will be appreciated, Thanks!

@Kalebu @filipporomani

filipporomani commented 1 year ago

Well, tbh this sounds strange. You coud try to return code 200 immediately and run the other code with a post-request app middleware (this is possible if i'm not wrong).

I don't know if there's a way to extend the time window, but I don't actually think so.

You shouldn't reduce the retries from WhatsApp, you should try to slove the issue in your code. Try the thing I said above and let me know!

@hitz02

hitz02 commented 1 year ago

Thanks @filipporomani for your response, I tried the below hack with a timestamp and it worked I computed the time difference between the incoming message timestamp and the current timestamp and only if it is below a threshold (let's say 10s), it will call my generate function.

if message_type == "text":
    msg_ts = data['entry'][0]['changes'][0]['value']['messages'][0]['timestamp']
    msg_ts = pd.to_datetime(msg_ts, unit='s')
    curr_ts = datetime.datetime.now()
    time_diff = (curr_ts - msg_ts).seconds
    logging.info("msg_ts: %s", msg_ts)
    logging.info("curr_ts: %s", curr_ts)
    logging.info("time_diff: %s", time_diff)
    if time_diff < int(os.environ.get('time_diff', '10')):
        message = messenger.get_message(data)
        # name = messenger.get_name(data)
        message = message.lower()
        qanda = Function.lookup("agri-qna-job", "qanda") 
        answer = qanda.call(query=message, db_name=db_name) ## my function
        logging.info("Answer: %s", answer)
        messenger.send_message(f"{answer}", mobile)
filipporomani commented 1 year ago

Great solution too! Thanks a lot for sharing with me!