Coder Social home page Coder Social logo

david-lev / pywa Goto Github PK

View Code? Open in Web Editor NEW
184.0 9.0 28.0 2.07 MB

๐Ÿ’ฌ Python wrapper for the WhatsApp Cloud API

Home Page: https://pywa.readthedocs.io

License: MIT License

Python 100.00%
wa wapy whatsapp whatsapp-api whatsapp-api-python whatsapp-bot whatsapp-chat whatsapp-chatbot whatsapp-cloud-api whatsappbot pywa wa-cloud-api whatsapp-cloud-api-flows whatsapp-flows

pywa's Introduction

PyWa Logo


PyWa โ€ข Python wrapper for the WhatsApp Cloud API

PyPi Downloads PyPI Version Tests Docs License CodeFactor Telegram


PyWa is a Fast, Simple, Modern and easy-to-use asynchronous Python framework for building WhatsApp bots using the WhatsApp Cloud API.

๐Ÿ“„ Quick Documentation Index

Get Started โ€ข WhatsApp Client โ€ข Handlers โ€ข Filters โ€ข Updates โ€ข Flows โ€ข Examples


โšก Features

  • ๐Ÿš€ Fast and simple to use. No need to worry about the low-level details.
  • ๐Ÿ’ฌ Send text messages with interactive keyboards, images, videos, documents, audio, locations, contacts, etc.
  • ๐Ÿ“ฉ Receive messages, callbacks, message status updates, etc.
  • โ™ป๏ธ Create, send and listen to Flows (NEW!)
  • ๐Ÿ”„ Built-in support for webhooks (Flask, FastAPI, etc.)
  • ๐Ÿ”ฌ Filters for handling incoming updates
  • ๐Ÿ“„ Send and create templates
  • โœ… Fully typed, documented and tested

๐Ÿ‘จโ€๐Ÿ’ป Usage

  • Create a WhatsApp client and send a message

See Getting Started for more information.

from pywa import WhatsApp

wa = WhatsApp(
    phone_id="100458559237541",
    token="EAAEZC6hUxkTIB"
)

wa.send_message(
    to="9876543210",
    text="Hello from PyWa!"
)
  • To listen to updates, create a WhatsApp client, pass a web server app (FastAPI in this example) and register callbacks:

See Handlers for more information.

# wa.py
from pywa import WhatsApp, filters
from pywa.types import Message, CallbackButton, Button
from fastapi import FastAPI

fastapi_app = FastAPI()
wa = WhatsApp(
    phone_id="1234567890",
    token="xxxxxxx",
    server=fastapi_app,
    callback_url="https://yourdomain.com/",
    verify_token="xyz123",
    app_id=123456,
    app_secret="yyyyyy"
)

@wa.on_message(filters.matches("Hello", "Hi"))
def hello(client: WhatsApp, msg: Message):
    msg.react("๐Ÿ‘‹")
    msg.reply_text(
        text=f"Hello {msg.from_user.name}!",
        buttons=[
            Button(
                title="Click me!",
                callback_data="id:123"
            )
        ]
    )

@wa.on_callback_button(filters.startswith("id"))
def click_me(client: WhatsApp, clb: CallbackButton):
    clb.reply_text("You clicked me!")
  • To run the server, use uvicorn (pip install "uvicorn[standard]"):
uvicorn wa:fastapi_app  # see uvicorn docs for more options (port, host, reload, etc.)

๐Ÿ’ซ Async Usage

  • PyWa has async support! To use the async version, replace all the imports from pywa to pywa_async and use async/await:
# wa.py
import fastapi
from pywa_async import WhatsApp, types

fastapi_app = fastapi.FastAPI()
wa = WhatsApp(..., server=fastapi_app)

async def main():
    await wa.send_message(...)

@wa.on_message()
async def hello(_: WhatsApp, msg: types.Message):
    await msg.react("๐Ÿ‘‹")
    await msg.reply(...)
uvicorn wa:fastapi_app

๐ŸŽ› Installation

  • Install using pip3:
pip3 install -U pywa
  • Install from source (the bleeding edge):
pip3 install -U git+https://github.com/david-lev/pywa.git
  • If you going to use the webhook features, here is shortcut to install the required dependencies:
pip3 install -U "pywa[fastapi]"
pip3 install -U "pywa[flask]"
  • If you going to use the Flow features and want to use the default FlowRequestDecryptor and the default FlowResponseEncryptor, here is shortcut to install the required dependencies:
pip3 install -U "pywa[cryptography]"

๐Ÿ’พ Requirements

๐Ÿ“– Setup and Usage

See the Documentation for detailed instructions

โ˜‘๏ธ TODO

  • Add support for async
  • Add support for more web frameworks (Django, aiohttp, etc.)
  • Add support for flows
  • Add support for more types of updates (account_alerts, phone_number_quality_updates, template_category_updates, etc.)
  • Add more examples and guides

Feel free to open an issue if you have any suggestions. or even better - submit a PR!

โš–๏ธ License

This project is licensed under the MIT License - see the LICENSE file for details

๐Ÿ”ฑ Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

pywa's People

Contributors

david-lev avatar pre-commit-ci[bot] avatar shlomocode avatar yehuda-lev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pywa's Issues

Django Server need to implemented.

Describe the bug

This is a great app for whatsapp APIs
Please add django sever to reach a better community,

To Reproduce

No response

Expected behavior

No response

pywa version

No response

python version

No response

os

No response

Additional context

No response

No message sent

Describe the bug

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?

pywa version

1.5.3

python version

3.11.5

os

Fedora

Sending Too Many Messages in a Loop

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"}]}]}'

Sometimes not getting replies

Describe the bug

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

To Reproduce

  1. Integrate with fastapi
  2. Create a Docker Compose Yaml
  3. make 3 instances
  4. add nginx as load balancer and deploy app
  5. send message and wait for sometime and try to continue conversation / try to start conversation with different new phone number

Expected behavior

No response

pywa version

1.16.2

python version

6.10

os

Ubuntu 22.04

Additional context

No response

Error in pywa library for templates with image headers

Discussed in #14

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.

Error 404 on Webhook Verification with Flask Integration

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.