Giter Club home page Giter Club logo

whatsapp's Introduction

logo

whatsapp-python

Free, open-source Python wrapper for the WhatsApp Cloud API.
Forked from Neurotech-HQ/heyoo.

Made in Italy Downloads Monthly Downloads Weekly Downloads

Installation

To install the library you can either use pip (latest release version):

pip install whatsapp-python

You can also install the development GitHub version (always up to date):

git clone https://github.com/filipporomani/whatsapp.git
cd whatsapp
pip install .

If you want to use a local enviroment you can also use hatch:

git clone https://github.com/filipporomani/whatsapp.git
cd whatsapp
pip install hatch
hatch shell

Documentation is available in the wiki section on GitHub.

Why choose this library?

The main reason why I decided to fork the original library is that it uses an old version of the API, it's missing many useful features and it's almost not mantained anymore.

In this fork I added app events (to listen to incoming messages) and implemented an easier way to send/receive messages and media by using the Message object.

I fixed some bugs and added many features, however the library still needs a lot of work to be done even if it's working and usable.

Supported features:

  • Listening to events (messages, media, etc.)
  • Sending messages
  • Sending messages from different numbers individually
  • Marking messages as read
  • Reacting to messages
  • Sending Media (images, audio, video and documents)
  • Sending location
  • Sending interactive buttons
  • Sending template messages
  • Parsing messages and media received

Obtaining the WhatsApp API credentials

To use the WhatsApp API you need to create a Facebook Business account and a WhatsApp Business account.

Tip

To create an account, I recommend to follow this video.

Pricing of the API

Whereas using third-party providers of the WhatsApp API can result in monthly fees, using the WhatsApp API1 offered directly by Facebook is much cheaper, even if the billing documentation is quite difficult to understand.

Caution

It is now mandatory to add a credit card to the WhatsApp account (at least for me) in order to use the service. I was even charged a fee for using a non-test phone number (~€1.20), so be careful when using the API! I'm not responsible for any costs you may face by using the API.

All the prices are available in the WhatsApp API docs.

Tip

One recommendation I can give you is to use a test number (you can get a free phone number and use it for testing purposes only).

Migrating from Neurotech-HQ/heyoo

You can ignore this if it's your first time using the library.

  • Any version >1.1.2 is incompatible with the original heyoo library! Be careful updating! Read the docs first!
  • Any version <=1.1.2 is fully compatible with the original heyoo library and doesn't include breaking changes.

Switching from heyoo to whatsapp-python doesn't require any change for versions up to 1.1.2: just uninstall heyoo, install whatsapp-python==1.1.2 and change the import name from heyoo to whatsapp.

For versions GREATER THAN 1.1.2, messages have became objects, so you need to change your code to use the new methods.

Note

Documentation for version 1.1.2 can be found here.

Contributing

If you are facing any issues or have any questions, please open a new issue!

This is an open source project published under the MIT License.

Footnotes

  1. https://developers.facebook.com/docs/whatsapp/cloud-api

whatsapp's People

Contributors

alejamp avatar boywithkeyboard avatar claudineibr avatar daudahmad0303 avatar epcosta17 avatar esteban108 avatar filipporomani avatar jaxparrow avatar jxhnx avatar kalebu avatar mscansian avatar nikbott avatar noisecontrollers avatar pptx704 avatar seun-beta avatar sharmakh11597 avatar soerenetler avatar surajbhari avatar taylorgibb 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

Watchers

 avatar  avatar  avatar  avatar

whatsapp's Issues

[BUG] Error while trying to install the library

Describe the bug
Receiving an error while trying to install the library.

To Reproduce
Steps to reproduce the behavior:
C:\Windows\System32>pip install --upgrade whatsapp-python
Collecting whatsapp-python
Using cached whatsapp-python-3.0.0.tar.gz (6.5 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [20 lines of output]
Traceback (most recent call last):
File "C:\Python311\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 353, in
main()
File "C:\Python311\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 118, in get_requires_for_build_wheel
return hook(config_settings)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Temp\pip-build-env-8xubgjme\overlay\Lib\site-packages\setuptools\build_meta.py", line 355, in get_requires_for_build_wheel
return self._get_build_requires(config_settings, requirements=['wheel'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Temp\pip-build-env-8xubgjme\overlay\Lib\site-packages\setuptools\build_meta.py", line 325, in _get_build_requires
self.run_setup()
File "C:\Users\user\AppData\Local\Temp\pip-build-env-8xubgjme\overlay\Lib\site-packages\setuptools\build_meta.py", line 507, in run_setup
super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
File "C:\Users\user\AppData\Local\Temp\pip-build-env-8xubgjme\overlay\Lib\site-packages\setuptools\build_meta.py", line 341, in run_setup
exec(code, locals())
File "", line 3, in
ModuleNotFoundError: No module named 'pre_dist'
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

Expected behavior
A successful completion of install process.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Windows 11
  • Version: latest updates

Additional context
Add any other context about the problem here.

[FEAT] Multiple WhatsApp Numbers in one WhatsApp instance

Is your feature request related to a problem? Please describe.
There is a possibility to have multiple numberrs added under one WhatsApp Account. Those numbers must have a single webhook endoint. However, for sending a message from those numbers, those have different WhatsApp Number Ids. Since the WhatsApp Number Id is specified as phone_number_id to WhatsApp class, it seems it is not possible to work with multiple WhatsApp numbers currently.

Describe the solution you'd like
There should be an option to provide multiple WhatsApp Number Ids, so that messages can be received (and answered) from a single WhatsApp instance. From the structure of the API, it seems it is only a matter of having multiple whatsapp phone number ids configurable for WhatsApp as all the numbers are managed under same account and whatsapp api token.

Describe alternatives you've considered
The alternative is to have instance of WhatsApp per each WhatsApp number. However, since WhatsApp platform enable having multiple numbers, it would be good to match that functionality in the whatsapp-python library.

Additional context
Can you please advice whether the asumptions are correct?

Thank you.

[BUG] 'WhatsApp' object has no attribute 'instance'

Describe the bug
For most of the operations, I get the following errors-

    changed_field = self.instance.changed_field(data)
                    ^^^^^^^^^^^^^
AttributeError: 'WhatsApp' object has no attribute 'instance'

To Reproduce

from whatsapp import WhatsApp

token = os.environ.get("WHATSAPP_TOKEN")
phone_number_id = os.environ.get("PHONE_ID")
app = WhatsApp(token, phone_number_id)

@app.on_message
async def on_message(message):
    question = message.content
    await message.reply(message.content)

app.run("0.0.0.0", 5000)

Expected behavior
Should echo the same message as a response.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version: 22.04
  • Python: 3.11
  • Environment Manager: Poetry

Additional context
Removing .instance from all self.instance fixes this. Not sure if that's the valid fix. Maybe add test cases?

[BUG] Import error parsing the package version

I started getting this error after a while, maybe you updated the package in pypi:

[ERROR] ValueError: invalid literal for int() with base 10: '303post1'
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/main.py", line 1, in <module>
    from config import client_whats, whatsapp_token, fb_verify_token, app_secret
  File "/config.py", line 15, in <module>
    client_whats = WhatsApp(whatsapp_token, whatsapp_number)
  File "/usr/local/lib/python3.11/site-packages/whatsapp/__init__.py", line 43, in __init__
    latest_int = int(latest.replace(".", ""))

I see this string 303post1 in your pyproject.toml file.

[BUG] Error with fastapi

Describe the bug
I am getting the following error-

Traceback (most recent call last):
  File "/path/to/directory/main.py", line 13, in <module>
    app.run()
  File "/path/to/env/pypoetry/virtualenvs/app-5rTTtjLO-py3.11/lib/python3.11/site-packages/whatsapp/__init__.py", line 181, in run
    self.app.run(host=host, port=port, debug=debug, **options)
    ^^^^^^^^^^^^
AttributeError: 'FastAPI' object has no attribute 'run'

To Reproduce
Copypaste the code for event listener from the wiki and run it.

Expected behavior
App server should run

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version 22.04

Additional Context
I installed it using poetry. Currently this issue can be fixed by defining the run function as following-

def run(self, host: str = "localhost", port: int = 5000, *args, **options):
    # self.app.run(host=host, port=port, debug=debug, **options)
    uvicorn.run(self.app, host=host, port=port, *args, **options)

If relevant, I am also getting AttributeError: 'Message' object has no attribute 'instance' and AttributeError: 'Whatsapp' object has no attribute 'instance' everywhere

Switch to an event-driven structure

The aim is to make a library where you can handle events (such as incoming message).

The actual versions provide a webhook server for that, but that's not enough.
This feature will be developed asap.

This is being implemented. All the commits will be done on the dev branch.

New release

Hi,

I like the library. Will you be able to make a new release, so that the fixes in main would be available?

Thank you in advance!

Stanislav

[BUG]: pip install broken

Describe the bug
Running pip-install whatsapp-python does not work as intended. If fails with various errors.

For one, fast api module is missing (screenshot below).
For the other, after installing fast api, from . import ext in __init__.py causes an ImportError.

To Reproduce
Steps to reproduce the behavior:

  1. Create .venv
  2. Run pip install whatsapp-python

Expected behavior
Install module without errors, assuming no other conflicts, for example, conflicting module requirements.

Desktop (please complete the following information):

  • OS: MacOS
  • Version Sonoma 14.2

Additional context
fast api missing:

Defaulting to user installation because normal site-packages is not writeable
Collecting whatsapp-python
  Using cached whatsapp-python-3.0.2.tar.gz (6.8 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 36, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/var/folders/1f/c30n_2q14556_p9sxtzwyx7h0000gn/T/pip-install-1xme71k0/whatsapp-python_0f9220bf20f9493b9c481d0784c5dbf3/setup.py", line 3, in <module>
          from whatsapp.constants import VERSION
        File "/private/var/folders/1f/c30n_2q14556_p9sxtzwyx7h0000gn/T/pip-install-1xme71k0/whatsapp-python_0f9220bf20f9493b9c481d0784c5dbf3/whatsapp/__init__.py", line 8, in <module>
          from fastapi import FastAPI, Request
      ModuleNotFoundError: No module named 'fastapi'
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

internal sourcing

Defaulting to user installation because normal site-packages is not writeable
Collecting whatsapp-python
  Using cached whatsapp-python-3.0.2.tar.gz (6.8 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 36, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/private/var/folders/1f/c30n_2q14556_p9sxtzwyx7h0000gn/T/pip-install-5gd09oij/whatsapp-python_de272e575cda4740afbc417c555fac57/setup.py", line 3, in <module>
          from whatsapp.constants import VERSION
        File "/private/var/folders/1f/c30n_2q14556_p9sxtzwyx7h0000gn/T/pip-install-5gd09oij/whatsapp-python_de272e575cda4740afbc417c555fac57/whatsapp/__init__.py", line 10, in <module>
          from . import ext
      ImportError: cannot import name 'ext' from 'whatsapp' (/private/var/folders/1f/c30n_2q14556_p9sxtzwyx7h0000gn/T/pip-install-5gd09oij/whatsapp-python_de272e575cda4740afbc417c555fac57/whatsapp/__init__.py)
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

[BUG] requirements not declared by default

Describe the bug
just doing pip install whatsapp-python doesn't make it run. and can be misleading for new developers who don't know what is wrong.

To Reproduce
Steps to reproduce the behavior:

  1. make a new enviorement.
  2. pip install whatsapp-python
  3. try using it by importing it and get ModuleNotFoundError

Expected behavior
it should have installed

  • fastapi
  • uvicorn
  • requests_toolkit

Additional context
just adding a requirements.txt and stating it in setup.py should work.

[BUG] Library is not pep 517-compliant (adding to a poetry project fails)

Describe the bug
The project does not follow pep517 (https://peps.python.org/pep-0517/) which means it does not work with modern python packaging tools such as poetry (https://python-poetry.org/)

To Reproduce

Either install poetry and try to poetry add whatsapp-python, or install with pip using pep517 as pip install --use-pep517 whatsapp-python

Expected behavior
Package should install correctly

Screenshots

Desktop (please complete the following information):

  • OS:Linux

Logs from pip install --use-pep517 whatsapp-python:

Collecting whatsapp-python
  Downloading whatsapp-python-3.0.0.tar.gz (6.5 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error
  
  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [20 lines of output]
      Traceback (most recent call last):
        File "/home/ldorigo/envs/braindump/lib/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 351, in <module>
          main()
        File "/home/ldorigo/envs/braindump/lib/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/home/ldorigo/envs/braindump/lib/python3.11/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 118, in get_requires_for_build_wheel
          return hook(config_settings)
                 ^^^^^^^^^^^^^^^^^^^^^
        File "/tmp/pip-build-env-m7a291kk/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 355, in get_requires_for_build_wheel
          return self._get_build_requires(config_settings, requirements=['wheel'])
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/tmp/pip-build-env-m7a291kk/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 325, in _get_build_requires
          self.run_setup()
        File "/tmp/pip-build-env-m7a291kk/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 507, in run_setup
          super(_BuildMetaLegacyBackend, self).run_setup(setup_script=setup_script)
        File "/tmp/pip-build-env-m7a291kk/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in run_setup
          exec(code, locals())
        File "<string>", line 3, in <module>
      ModuleNotFoundError: No module named 'pre_dist'
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

Proper error handler

A proper error handler to handle the most common and annoying errors is planned.

'WhatsApp' object has no attribute 'send_button'

Describe the bug
If I run the following example:

https://github.com/filipporomani/whatsapp/blob/main/examples/sending_button.py

I get the error:

Exception has occurred: AttributeError
'WhatsApp' object has no attribute 'send_button'

File "...\whatsapp_button.py", line 17, in <module>
    response = messenger.send_button(
AttributeError: 'WhatsApp' object has no attribute 'send_button'

(Sending normal text messages works)

To Reproduce
Run it under Python 3.10.

Desktop (please complete the following information):

  • OS: Windows 10
  • Python Version 3.10.5

[BUG] 'Message' object has no attribute 'url'

Describe the bug
Trying to reply to a message using message.reply()

/path/to/env/lib/python3.11/site-packages/whatsapp/ext/_message.py", line 60, in reply
    r = requests.post(self.url, headers=self.headers, json=payload)
                      ^^^^^^^^
AttributeError: 'Message' object has no attribute 'url'

To Reproduce

@app.on_message
async def on_message(message):
    question = message.content
    await message.reply(question)

Expected behavior
Message sent properly

Desktop (please complete the following information):

  • OS: Ubuntu
  • Version 22.04
  • Package Manager: Poetry
  • Python: 3.11

Additional Context
I made a small patch for the previously reported bug to progress further and stumbled upon this.

Help Request: Unable to Receive WhatsApp Messages Using Code

Hi ,

I hope this message finds you well. I am writing to seek assistance with an issue I am encountering while trying to send WhatsApp messages using a custom Python script. I have provided the relevant code snippet below:

from whatsapp import WhatsApp, Message

if __name__ == "__main__":
    whatsapp_token = 'EAAVXKQbbM7**uZBj'
    messenger = WhatsApp(token=whatsapp_token, phone_number_id='1830**0')
    msg = Message(instance=messenger, content="Hello World!", to="+44***91")
    response = msg.send()
    print(response)

The issue I am facing is that the script runs successfully without any errors, and the logs indicate that the message has been sent:

2024-01-26 15:32:07,236 - root - INFO - Sending message to +44**91
2024-01-26 15:32:08,044 - root - INFO - Message sent to +44***91

However, despite the successful message send logs, I am not receiving any messages on WhatsApp. It's worth noting that I do receive messages when testing using the pre-written functions in the Facebook Developer Portal.

I would greatly appreciate any guidance or suggestions you can provide to help me resolve this issue. If there are additional logs or information you need from my end, please let me know.

Thank you in advance for your assistance.

[BUG] Pip install error

I get the following error when trying to install it using python 3.11:

Collecting whatsapp-python
  Using cached whatsapp-python-3.0.1.tar.gz (6.4 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error
  
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [6 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-1wjse775/whatsapp-python_2858b75d696342c0802f0198df859a12/setup.py", line 3, in <module>
          from constants import VERSION
      ModuleNotFoundError: No module named 'constants'
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

To Reproduce
Steps to reproduce the behavior:

  1. Run pip install whatsapp-python inside a venv

Expected behavior
A successful installation.

Desktop (please complete the following information):

  • OS: Linux archlinux 6.5.9-arch2-1 #1 SMP PREEMPT_DYNAMIC x86_64 GNU/Linux
  • Version pip 23.3.1, python 3.11.5

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.