david-lev / pywa Goto Github PK
View Code? Open in Web Editor NEW๐ค Build WhatsApp Bots in Python
Home Page: https://pywa.readthedocs.io
License: MIT License
๐ค Build WhatsApp Bots in Python
Home Page: https://pywa.readthedocs.io
License: MIT License
Description
While integrating the pywa library with a Flask server, the webhook verification step results in a 404 error. The following message appears in the log:
"GET /webhook/?hub.mode=subscribe&hub.challenge=<challange>&hub.verify_token=<verify_token> HTTP/1.1" 404
Steps to Reproduce
Configure the pywa library with the necessary credentials and a callback URL using pagekite.me.
Start the Flask server.
Observe the 404 error in the server logs when WhatsApp attempts to verify the webhook.
Expected Behavior
The server should correctly handle the GET request for webhook verification, respond with the challenge code provided by WhatsApp, and handle incoming POST requests for messages.
Actual Behavior
The server returns a 404 error during the GET request for webhook verification.
Example Code
Here is a simplified version of the code used to set up the Flask server and pywa integration:
from pywa import WhatsApp
from pywa.types import Message
from flask import Flask
flask_app = Flask(__name__)
wa = WhatsApp(
phone_id='your_phone_id',
token='your_token',
server=flask_app,
callback_url='https://your_pagekit.mel/webhook/',
verify_token='your_verify_token',
app_id='your_app_id',
app_secret='your_app_secret',
)
@wa.on_message()
async def message_handler(_: WhatsApp, msg: Message):
print(msg)
if __name__ == '__main__':
flask_app.run(port=8000, debug=True)
Analysis
The issue arises because the pywa library does not automatically handle the webhook verification step, and there is no clear guidance in the documentation on how to configure Flask to handle this correctly. The workaround involves manually adding a route in Flask to handle the GET request for verification.
Proposed Solution
Documentation Update: Include clear instructions and example code in the pywa documentation for handling webhook verification with Flask.
Library Enhancement: Consider adding a method or functionality within pywa to automatically handle the webhook verification process, simplifying integration with web frameworks like Flask.
Additional Context
pywa Version: 1.20.2
Flask Version: 3.0.3
Python Version: 3.10.12
Operating System: Linux Mint 21.1
This issue is critical for developers attempting to integrate pywa with Flask, as it hinders the initial setup and functionality testing.
A unique Feature Request:
When we send URLs in templates, clicking that URL shall open in whatsapp webview instead of default browser of mobile(chrome/safari).
Is this available at present?
It sends the same message multiple times and then hit the limit. No matter if I send a reply or a template message.
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)
Send a message from another number and then see the unusual behavior.
It should only send 1 message.
1.16.2
3.10.8
Windows 11
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"}]}]}'
Originally posted by bcombes October 7, 2023
I'm not sure how best to file a bug report, but I found an error in the pywa send_template library when using image headers. According to the facebook docs, the key for the image location should be link
and not url
which results in the error below;
pywa.errors.WhatsAppError: WhatsAppError(message='(#100) Unexpected key "url" on param "template['components'][0]['parameters'][0]['image']".', details=None, code=100)
I've been trying to submit a PR to fix this, but not sure how.
I followed all the steps in the Get Started tutorial but when I send the message I get no whatsapp message
my terminal just print outs
wamid.<A_BUNCH_OF_LETTERS>
how I debug and figre out why the message isn't sent?
1.5.3
3.11.5
Fedora
I am using @wa.on_callback_button(), @wa.on_message() Sometimes when it receives the message through the webhook it was receiving the message and printing in log but not doing any processing
No response
1.16.2
6.10
Ubuntu 22.04
No response
This is a great app for whatsapp APIs
Please add django sever to reach a better community,
No response
No response
No response
No response
No response
No response
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.