david-lev / pywa

🤖 Hey there! I am using PyWa.
https://pywa.readthedocs.io
MIT License
230 stars 34 forks source link

Sending Too Many Messages in a Loop #52

Closed ilovefreesw closed 6 months ago

ilovefreesw commented 6 months ago

Describe the bug

It sends the same message multiple times and then hit the limit. No matter if I send a reply or a template message.

To Reproduce

Create the sample script:

from flask import Flask, request, jsonify
import logging
from pywa.types import Template as Temp
from pywa import WhatsApp

wa = WhatsApp(
    phone_id='280XXXXX830552',
    token='E2cUrb2FKvxRvo2y7NJd4aqQVUATGOUg6U9WrQbDp'
)

app = Flask(__name__)

# Configure Flask logging
app.logger.setLevel(logging.DEBUG)  # Set log level to INFO
handler = logging.FileHandler('app.log')  # Log to a file
app.logger.addHandler(handler)

@app.route('/webhook', methods=['GET', 'POST'])
def verify_webhook():
    if request.method == 'POST':
        wa.send_message(
        to='919XXXXXX785',
        text='Hello from PyWa!'
            )

        return "OK",200

    else:
        return "HELLO GET"

@app.before_request
def log_request_info():
    #app.logger.info('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

if __name__ == '__main__':
    app.config['FACEBOOK_VERIFICATION_TOKEN'] = 'test_webhook'
    app.run(debug=True, port=8000)

image

Send a message from another number and then see the unusual behavior.

Expected behavior

It should only send 1 message.

pywa version

1.16.2

python version

3.10.8

os

Windows 11

Additional context

Here's what I get in the terminal:

Traceback (most recent call last):
  File "E:\pyth\Lib\site-packages\flask\app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "E:\pyth\Lib\site-packages\flask\app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "E:\pyth\Lib\site-packages\flask\app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "E:\pyth\Lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "E:\pyth\Lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "E:\pyth\Lib\site-packages\flask\app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "E:\CFtunnel\webhook.py", line 21, in verify_webhook
    wa.send_message(
  File "E:\pyth\Lib\site-packages\pywa\client.py", line 375, in send_message
    return self.api.send_text_message(
  File "E:\pyth\Lib\site-packages\pywa\api.py", line 201, in send_text_message
    return self._make_request(
  File "E:\pyth\Lib\site-packages\pywa\api.py", line 68, in _make_request
    raise WhatsAppError.from_dict(error=res.json()["error"], response=res)
pywa.errors.TooManyMessages: TooManyMessages(message='(#131056) (Business Account, Consumer Account) pair rate limit hit', details='Message failed to send because there were too many messages sent from this phone number to the same phone number in a short period of time.', code=131056)
[2024-04-29 17:30:16,390] DEBUG in webhook: Body: b'{"object":"whatsapp_business_account","entry":[{"id":"287XXXXXX084265","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"142XXXXX8092","phone_number_id":"280390631830552"},"statuses":[{"id":"wamid.HBgMOTE5OTkwMjE1Nzg1FQIAERgSNkY1NzNFRjA4NDA5RDg5Q0NFAA==","status":"sent","timestamp":"1714391998","recipient_id":"XXXXXXXXXX","conversation":{"id":"0382a6e0c0f7085cc3ac1dd8ed049e2a","expiration_timestamp":"1714478400","origin":{"type":"service"}},"pricing":{"billable":true,"pricing_model":"CBP","category":"service"}}]},"field":"messages"}]}]}'
ibenitez commented 6 months ago

You are reacting to all kinds of messages, sent, delivered, etc.

Should react only to specific messages, text, image... etc.

Should use the handlers, ex.

@wa.on_raw_update()
def raw_update_handler(_: WhatsApp, update: dict):
    print(update)

@wa.on_message()
def message_handler(_: WhatsApp, msg: Message):
    print(msg)