├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md ├── dependabot.yml └── workflows │ ├── codeql.yml │ ├── dependency-review.yml │ └── python-publish.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── examples ├── reply_to_message_obj.py ├── sending_audio.py ├── sending_button.py ├── sending_button_async.py ├── sending_document.py ├── sending_image.py ├── sending_location.py ├── sending_message.py ├── sending_message_async.py ├── sending_template_message.py ├── sending_video.py └── standalone_hook.py ├── pyproject.toml ├── tests ├── async_tests.py └── tests.py └── whatsapp ├── __init__.py ├── async_ext ├── _buttons.py ├── _media.py ├── _message.py ├── _property.py ├── _send_media.py ├── _send_others.py └── _static.py ├── constants.py ├── errors.py └── ext ├── _buttons.py ├── _media.py ├── _message.py ├── _property.py ├── _send_media.py ├── _send_others.py └── _static.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: filipporomani 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Version [e.g. 22] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: "[OTHER]" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEAT]" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "daily" 12 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | pull_request: 16 | branches: [ "main" ] 17 | schedule: 18 | - cron: '0 0 * * *' 19 | 20 | jobs: 21 | analyze: 22 | name: Analyze 23 | runs-on: ubuntu-latest 24 | permissions: 25 | actions: read 26 | contents: read 27 | security-events: write 28 | 29 | strategy: 30 | fail-fast: false 31 | matrix: 32 | language: [ 'python' ] 33 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 34 | # Use only 'java' to analyze code written in Java, Kotlin or both 35 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both 36 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 37 | 38 | steps: 39 | - name: Checkout repository 40 | uses: actions/checkout@v3 41 | 42 | # Initializes the CodeQL tools for scanning. 43 | - name: Initialize CodeQL 44 | uses: github/codeql-action/init@v2 45 | with: 46 | languages: ${{ matrix.language }} 47 | # If you wish to specify custom queries, you can do so here or in a config file. 48 | # By default, queries listed here will override any specified in a config file. 49 | # Prefix the list here with "+" to use these queries and those in the config file. 50 | 51 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 52 | # queries: security-extended,security-and-quality 53 | 54 | 55 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). 56 | # If this step fails, then you should remove it and run the build manually (see below) 57 | - name: Autobuild 58 | uses: github/codeql-action/autobuild@v2 59 | 60 | # ℹ️ Command-line programs to run using the OS shell. 61 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 62 | 63 | # If the Autobuild fails above, remove it and uncomment the following three lines. 64 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 65 | 66 | # - run: | 67 | # echo "Run, Build Application using script" 68 | # ./location_of_script_within_repo/buildscript.sh 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v2 72 | with: 73 | category: "/language:${{matrix.language}}" 74 | -------------------------------------------------------------------------------- /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # Dependency Review Action 2 | # 3 | # This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. 4 | # 5 | # Source repository: https://github.com/actions/dependency-review-action 6 | # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement 7 | name: 'Dependency Review' 8 | on: [pull_request] 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | dependency-review: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: 'Checkout Repository' 18 | uses: actions/checkout@v3 19 | - name: 'Dependency Review' 20 | uses: actions/dependency-review-action@v2 21 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deployment: 20 | 21 | runs-on: ubuntu-latest 22 | environment: publish 23 | steps: 24 | - uses: actions/checkout@v4 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.12' 29 | - name: Install packages 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Building... 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | test.py 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | *.DS_Store 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | .python-version 88 | 89 | # pipenv 90 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 91 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 92 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 93 | # install all needed dependencies. 94 | #Pipfile.lock 95 | 96 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 97 | __pypackages__/ 98 | 99 | # Celery stuff 100 | celerybeat-schedule 101 | celerybeat.pid 102 | 103 | # SageMath parsed files 104 | *.sage.py 105 | 106 | # Environments 107 | .env 108 | .venv 109 | env/ 110 | venv/ 111 | ENV/ 112 | env.bak/ 113 | venv.bak/ 114 | 115 | # Spyder project settings 116 | .spyderproject 117 | .spyproject 118 | 119 | # Rope project settings 120 | .ropeproject 121 | 122 | # mkdocs documentation 123 | /site 124 | 125 | # mypy 126 | .mypy_cache/ 127 | .dmypy.json 128 | dmypy.json 129 | 130 | # Pyre type checker 131 | .pyre/ 132 | whatsapp/.DS_Store 133 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mail@filipporomani.it. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | First of all, thank you for considering contributing to this project! It's people like you that make it a reality and help me keep it alive and updated. 4 | 5 | If you are unsure about anything, feel free to ask me. I am here to help you. 6 | 7 | Any bug report, feature request, or code contribution is welcome. Here are some guidelines to help you get started. 8 | 9 | ## Submitting changes 10 | 11 | Please open a [Pull Request](https://github.com/filipporomani/whatsapp-python/pull/new/master) with a list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). Make sure, if possible, that all of your commits are atomic (one feature per commit). 12 | 13 | Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: 14 | 15 | $ git commit -m "feat: a brief summary of the commit 16 | > 17 | > A paragraph describing what changed and its impact." 18 | 19 | 20 | * This is an open source software. Keep in mind to make your code readable to others. It's sort of like driving a car: perhaps you love doing donuts when you're alone, but with passengers the goal is to make the ride as smooth as possible. 21 | 22 | There isn't any other particular guideline, feel free to contribute! 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright © Filippo Romani 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | logo 3 |

whatsapp-python

4 |

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

6 | Made in Italy 7 | Downloads 8 | Monthly Downloads 9 | Weekly Downloads 10 |
11 | 12 | ## Installation 13 | 14 | To install the library you can either use pip (latest release version): 15 | 16 | ``pip install whatsapp-python`` 17 | 18 | You can also install the development GitHub version (always up to date, with the latest features and bug fixes): 19 | 20 | ```bash 21 | git clone https://github.com/filipporomani/whatsapp.git 22 | cd whatsapp 23 | pip install . 24 | ``` 25 | 26 | If you want to use a local enviroment you can also use hatch: 27 | 28 | ```bash 29 | git clone https://github.com/filipporomani/whatsapp.git 30 | cd whatsapp 31 | pip install hatch 32 | hatch shell 33 | ``` 34 | 35 | Documentation is available in the [wiki](https://github.com/filipporomani/whatsapp/wiki) here on GitHub. 36 | 37 | ### Key features: 38 | - Modern interface using `async` and `await` 39 | - Full support for Graph API error handling 40 | - Optimized for high-load workflows using asyncronous programming 41 | - Always up to date 42 | - All of the WhatsApp Business chat UI features supported 43 | 44 | 45 | ### All features 46 | - Event listening (incoming messages) 47 | - Asyncronous API calls 48 | - Error handling 49 | - Sending messages 50 | - Sending messages from different numbers individually 51 | - Marking messages as read 52 | - Replying to messages 53 | - Reacting to messages 54 | - Sending medias (images, audios, videos, links and documents) 55 | - Sending location 56 | - Sending interactive buttons 57 | - Sending template messages 58 | - Parsing messages and media received 59 | - Sending contacts 60 | - Uploading media to the Facebook cloud 61 | 62 | ## Obtaining the WhatsApp API credentials 63 | 64 | To use the WhatsApp API you need to create a Facebook Business account and a WhatsApp Business account. 65 | 66 | > [!TIP] 67 | > To create an account, I recommend to follow [this video](https://youtu.be/d6lNxP2gadA). 68 | 69 | ## Pricing of the API 70 | 71 | Whereas using third-party providers of the WhatsApp API can result in monthly fees, using the WhatsApp API[^1] offered directly by Facebook is much cheaper, even if the billing documentation is quite difficult to understand. 72 | 73 | > [!CAUTION] 74 | > 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 tiny 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. 75 | > 76 | > The API should be, however, free for testing purposes with the provided test phone number. 77 | 78 | All the prices are available in the [**WhatsApp API docs**](https://developers.facebook.com/docs/whatsapp/pricing). 79 | 80 | > [!TIP] 81 | > I recomend to use a test number, as you you can get a free one and use it for testing purposes. 82 | 83 | ## Migrating from `Neurotech-HQ/heyoo` 84 | 85 | *You can ignore this if it's your first time using the library.* 86 | 87 | - Any version >1.1.2 is incompatible with the original `heyoo` library! Be careful updating! Read the docs first! 88 | - Any version <=1.1.2 is fully compatible with the original `heyoo` library and doesn't include breaking changes. 89 | 90 | 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`. 91 | 92 | For versions GREATER THAN 1.1.2, messages have became objects, so you need to change your code to use the new methods. 93 | 94 | > [!NOTE] 95 | > Documentation for version 1.1.2 can be found [here](https://github.com/filipporomani/whatsapp/wiki/v1.1.2). 96 | 97 | ## Contributing 98 | 99 | If you are facing any issues or have any questions, please [open a new issue](https://github.com/filipporomani/whatsapp/issues/new/choose)! 100 | 101 | *This is an open source project published under the [GNU Affero General Public License v3](LICENSE).* 102 | 103 | [^1]: https://developers.facebook.com/docs/whatsapp/cloud-api 104 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | >=3.3.96 | :white_check_mark: | 8 | | <3.3.96 | :x: | 9 | 10 | ## Reporting a Vulnerability 11 | 12 | Please report any vulnerability via e-mail: mail@filipporomani.it. 13 | I'll review vulnerabilities as soon as possible, with maximum prioirity. 14 | If you find any security issue that is not crucial, feel free to open an issue for it. 15 | -------------------------------------------------------------------------------- /examples/reply_to_message_obj.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp, Message 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | data = {"your": "data"} 10 | 11 | msg = Message(data=data, instance=messenger, sender=1) 12 | msg.reply("lol") 13 | 14 | print(msg) 15 | -------------------------------------------------------------------------------- /examples/sending_audio.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | response = messenger.send_audio( 10 | audio="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", 11 | recipient_id="255757xxxxxx", 12 | sender=1, 13 | ) 14 | 15 | print(response) 16 | -------------------------------------------------------------------------------- /examples/sending_button.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | response = messenger.send_button( 10 | recipient_id="255757xxxxxx", 11 | button={ 12 | "header": "Header Testing", 13 | "body": "Body Testing", 14 | "footer": "Footer Testing", 15 | "action": { 16 | "button": "Button Testing", 17 | "sections": [ 18 | { 19 | "title": "iBank", 20 | "rows": [ 21 | {"id": "row 1", "title": "Send Money", "description": ""}, 22 | { 23 | "id": "row 2", 24 | "title": "Withdraw money", 25 | "description": "", 26 | }, 27 | ], 28 | } 29 | ], 30 | }, 31 | }, 32 | sender=1, 33 | ) 34 | -------------------------------------------------------------------------------- /examples/sending_button_async.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import AsyncWhatsApp, AsyncMessage 3 | import asyncio 4 | from dotenv import load_dotenv 5 | 6 | if __name__ == "__main__": 7 | load_dotenv() 8 | messenger = AsyncWhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 9 | 10 | async def run_test(): 11 | response = await messenger.send_button( 12 | recipient_id="255757xxxxxx", 13 | button={ 14 | "header": "Header Testing", 15 | "body": "Body Testing", 16 | "footer": "Footer Testing", 17 | "action": { 18 | "button": "Button Testing", 19 | "sections": [ 20 | { 21 | "title": "iBank", 22 | "rows": [ 23 | {"id": "row 1", "title": "Send Money", "description": ""}, 24 | { 25 | "id": "row 2", 26 | "title": "Withdraw money", 27 | "description": "", 28 | }, 29 | ], 30 | } 31 | ], 32 | }, 33 | }, 34 | sender=1, 35 | ) 36 | while not response.done(): 37 | await asyncio.sleep(.1) 38 | print(response.result()) 39 | 40 | asyncio.run(run_test()) 41 | -------------------------------------------------------------------------------- /examples/sending_document.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | 8 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 9 | 10 | response = messenger.send_document( 11 | document="http://www.africau.edu/images/default/sample.pdf", 12 | recipient_id="255757294146", 13 | sender=1, 14 | ) 15 | 16 | print(response) 17 | -------------------------------------------------------------------------------- /examples/sending_image.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | from os import getenv 5 | from whatsapp import WhatsApp 6 | from dotenv import load_dotenv 7 | 8 | if __name__ == "__main__": 9 | load_dotenv() 10 | messenger = WhatsApp(token=getenv("TOKEN"), 11 | phone_number_id={1:"1234", 2: "5678"}) 12 | 13 | response = messenger.send_image( 14 | image="https://i.imgur.com/Fh7XVYY.jpeg", 15 | recipient_id="255757294146", 16 | sender=1 17 | ) 18 | 19 | print(response) 20 | -------------------------------------------------------------------------------- /examples/sending_location.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | response = messenger.send_location( 10 | lat=1.29, 11 | long=103.85, 12 | name="Singapore", 13 | address="Singapore", 14 | recipient_id="255757294146", 15 | sender=1, 16 | ) 17 | 18 | print(response) 19 | -------------------------------------------------------------------------------- /examples/sending_message.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp, Message 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | msg = Message( 10 | instance=messenger, content="Hello World!", to="919999999999", sender=1 11 | ) 12 | response = msg.send() 13 | 14 | print(response) 15 | -------------------------------------------------------------------------------- /examples/sending_message_async.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import AsyncWhatsApp, AsyncMessage 3 | import asyncio 4 | from dotenv import load_dotenv 5 | 6 | if __name__ == "__main__": 7 | load_dotenv() 8 | messenger = AsyncWhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 9 | 10 | msg = AsyncMessage( 11 | instance=messenger, content="Hello World!", to="919999999999", sender=1 12 | ) 13 | async def run_test(): 14 | response = await msg.send() 15 | while not response.done(): 16 | await asyncio.sleep(.1) 17 | print(response.result()) 18 | 19 | asyncio.run(run_test()) 20 | -------------------------------------------------------------------------------- /examples/sending_template_message.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | response = messenger.send_template( 10 | "hello_world", "255757xxxxxx", components=[], lang="en_US", sender=1 11 | ) 12 | 13 | print(response) 14 | -------------------------------------------------------------------------------- /examples/sending_video.py: -------------------------------------------------------------------------------- 1 | from os import getenv 2 | from whatsapp import WhatsApp 3 | from dotenv import load_dotenv 4 | 5 | if __name__ == "__main__": 6 | load_dotenv() 7 | messenger = WhatsApp(token=getenv("TOKEN"), phone_number_id={1: "1234", 2: "5678"}) 8 | 9 | response = messenger.send_video( 10 | video="https://www.youtube.com/watch?v=K4TOrB7at0Y", 11 | recipient_id="255757xxxxxx", 12 | sender=1, 13 | ) 14 | 15 | print(response) 16 | -------------------------------------------------------------------------------- /examples/standalone_hook.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | from whatsapp import WhatsApp, Message 4 | from dotenv import load_dotenv 5 | from flask import Flask, request, Response 6 | 7 | # Initialize Flask App 8 | app = Flask(__name__) 9 | 10 | # Load .env file 11 | load_dotenv("../.env") 12 | messenger = WhatsApp(os.getenv("TOKEN"), phone_number_id=os.getenv("ID")) 13 | VERIFY_TOKEN = "30cca545-3838-48b2-80a7-9e43b1ae8ce4" 14 | 15 | # Logging 16 | logging.basicConfig( 17 | level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 18 | ) 19 | 20 | 21 | @app.get("/") 22 | def verify_token(): 23 | if request.args.get("hub.verify_token") == VERIFY_TOKEN: 24 | logging.info("Verified webhook") 25 | challenge = request.args.get("hub.challenge") 26 | return str(challenge) 27 | logging.error("Webhook Verification failed") 28 | return "Invalid verification token" 29 | 30 | 31 | @app.post("/") 32 | def hook(): 33 | # Handle Webhook Subscriptions 34 | data = request.get_json() 35 | if data is None: 36 | return Response(status=200) 37 | logging.info("Received webhook data: %s", data) 38 | changed_field = messenger.changed_field(data) 39 | if changed_field == "messages": 40 | new_message = messenger.is_message(data) 41 | if new_message: 42 | msg = Message(instance=messenger, data=data) 43 | mobile = msg.sender 44 | name = msg.name 45 | message_type = msg.type 46 | logging.info( 47 | f"New Message; sender:{mobile} name:{name} type:{message_type}" 48 | ) 49 | if message_type == "text": 50 | message = msg.content 51 | name = msg.name 52 | logging.info("Message: %s", message) 53 | m = Message(instance=messenger, to=mobile, content="Hello World") 54 | m.send() 55 | 56 | elif message_type == "interactive": 57 | message_response = msg.interactive 58 | if message_response is None: 59 | return Response(status=400) 60 | interactive_type = message_response.get("type") 61 | message_id = message_response[interactive_type]["id"] 62 | message_text = message_response[interactive_type]["title"] 63 | logging.info(f"Interactive Message; {message_id}: {message_text}") 64 | 65 | elif message_type == "location": 66 | message_location = msg.location 67 | if message_location is None: 68 | return Response(status=400) 69 | message_latitude = message_location["latitude"] 70 | message_longitude = message_location["longitude"] 71 | logging.info("Location: %s, %s", message_latitude, message_longitude) 72 | 73 | elif message_type == "image": 74 | image = msg.image 75 | if image is None: 76 | return Response(status=400) 77 | image_id, mime_type = image["id"], image["mime_type"] 78 | image_url = messenger.query_media_url(image_id) 79 | if image_url is None: 80 | return Response(status=400) 81 | image_filename = messenger.download_media(image_url, mime_type) 82 | logging.info(f"{mobile} sent image {image_filename}") 83 | 84 | elif message_type == "sticker": 85 | sticker = msg.sticker 86 | if sticker is None: 87 | return Response(status=400) 88 | sticker_id, mime_type = sticker["id"], sticker["mime_type"] 89 | sticker_url = messenger.query_media_url(sticker_id) 90 | if sticker_url is None: 91 | return Response(status=400) 92 | sticker_filename = messenger.download_media(sticker_url, mime_type) 93 | logging.info(f"{mobile} sent sticker {sticker_filename}") 94 | 95 | elif message_type == "video": 96 | video = msg.video 97 | if video is None: 98 | return Response(status=400) 99 | video_id, mime_type = video["id"], video["mime_type"] 100 | video_url = messenger.query_media_url(video_id) 101 | if video_url is None: 102 | return Response(status=400) 103 | video_filename = messenger.download_media(video_url, mime_type) 104 | logging.info(f"{mobile} sent video {video_filename}") 105 | 106 | elif message_type == "audio": 107 | audio = msg.audio 108 | if audio is None: 109 | return Response(status=400) 110 | audio_id, mime_type = audio["id"], audio["mime_type"] 111 | audio_url = messenger.query_media_url(audio_id) 112 | if audio_url is None: 113 | return Response(status=400) 114 | audio_filename = messenger.download_media(audio_url, mime_type) 115 | logging.info(f"{mobile} sent audio {audio_filename}") 116 | 117 | elif message_type == "document": 118 | file = msg.document 119 | if file is None: 120 | return Response(status=400) 121 | file_id, mime_type = file["id"], file["mime_type"] 122 | file_url = messenger.query_media_url(file_id) 123 | if file_url is None: 124 | return Response(status=400) 125 | file_filename = messenger.download_media(file_url, mime_type) 126 | logging.info(f"{mobile} sent file {file_filename}") 127 | else: 128 | logging.info(f"{mobile} sent {message_type} ") 129 | logging.info(data) 130 | else: 131 | delivery = messenger.get_delivery(data) 132 | if delivery: 133 | logging.info(f"Message : {delivery}") 134 | else: 135 | logging.info("No new message") 136 | return "OK", 200 137 | 138 | 139 | if __name__ == "__main__": 140 | app.run(port=6869, debug=False) 141 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name="whatsapp-python" 7 | authors = [{name="Filippo Romani", email="mail@filipporomani.it"}] 8 | description="Open source Python wrapper for the WhatsApp Cloud API" 9 | readme = "README.md" 10 | requires-python = ">=3.10" 11 | classifiers=[ 12 | "Development Status :: 4 - Beta", 13 | "Intended Audience :: Developers", 14 | "Intended Audience :: Customer Service", 15 | "Intended Audience :: Education", 16 | "Intended Audience :: Telecommunications Industry", 17 | "Topic :: Software Development :: Build Tools", 18 | "License :: OSI Approved :: GNU Affero General Public License v3", 19 | "Programming Language :: Python :: 3.10", 20 | "Programming Language :: Python :: 3.11", 21 | "Programming Language :: Python :: 3.12", 22 | "Programming Language :: Python :: 3.13", 23 | "Programming Language :: Python :: 3.14", 24 | "Topic :: Communications :: Chat", 25 | "Topic :: Communications :: Telephony", 26 | "Topic :: Internet :: WWW/HTTP :: HTTP Servers", 27 | "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", 28 | "Topic :: Software Development :: Libraries :: Python Modules", 29 | 30 | ] 31 | dynamic = [ 32 | "version" 33 | ] 34 | dependencies = ["fastapi", "uvicorn", "requests_toolbelt", "asyncio", "aiohttp", "python-dotenv", "BeautifulSoup4"] 35 | 36 | [project.urls] 37 | Homepage = "https://github.com/filipporomani/whatsapp-python" 38 | Docs = "https://github.com/filipporomani/whatsapp-python/wiki" 39 | "Issues Reporting" = "https://github.com/filipporomani/whatsapp-python/issues" 40 | Download = "https://github.com/filipporomani/whatsapp-python/releases/latest" 41 | Changelog = "https://github.com/filipporomani/whatsapp-python/releases" 42 | 43 | 44 | [tool.hatch.version] 45 | path = "whatsapp/constants.py" 46 | variable = "VERSION" 47 | 48 | [tool.hatch.build.targets.wheel] 49 | packages = ["whatsapp"] -------------------------------------------------------------------------------- /tests/async_tests.py: -------------------------------------------------------------------------------- 1 | from whatsapp import WhatsApp, Message, AsyncWhatsApp 2 | from dotenv import load_dotenv 3 | from os import getenv 4 | import asyncio 5 | from logging import getLogger, basicConfig, DEBUG 6 | 7 | load_dotenv() 8 | token = getenv("GRAPH_API_TOKEN") 9 | phone_number_id = {1: getenv("TEST_PHONE_NUMBER_ID")} 10 | dest_phone_number = getenv("DEST_PHONE_NUMBER") 11 | 12 | app = AsyncWhatsApp(token=token, phone_number_id=phone_number_id, update_check=False, logger=True, debug=True) 13 | syncapp = WhatsApp(token=token, phone_number_id=phone_number_id, update_check=False, logger=True, debug=True) 14 | loop = asyncio.get_event_loop() 15 | msg = app.create_message(to=dest_phone_number, content="Hello world") 16 | 17 | basicConfig(level=DEBUG) 18 | logger = getLogger(__name__) 19 | 20 | async def run_test(): 21 | 22 | # test every single method and print the result 23 | print("Testing send_text") 24 | v = await msg.send() 25 | # print(v) 26 | # await asyncio.sleep(1) 27 | # print("Getting request status") 28 | # print(v.result()) 29 | 30 | print("Testing send_reply_button") 31 | v = await app.send_reply_button( 32 | button={ 33 | "type": "button", 34 | "body": {"text": "This is a test button"}, 35 | "action": { 36 | "buttons": [ 37 | { 38 | "type": "reply", 39 | "reply": {"id": "b1", "title": "This is button 1"}, 40 | }, 41 | { 42 | "type": "reply", 43 | "reply": {"id": "b2", "title": "this is button 2"}, 44 | }, 45 | ] 46 | }, 47 | }, 48 | recipient_id=dest_phone_number, 49 | sender=1, 50 | ) 51 | print(f"send_reply_button: {v}") 52 | 53 | print("Creating button") 54 | v = app.create_button( 55 | button={ 56 | "header": {"type": "text", "text": "your-header-content"}, 57 | "body": {"text": "your-text-message-content"}, 58 | "footer": {"text": "your-footer-content"}, 59 | "action": { 60 | "button": "cta-button-content", 61 | "sections": [ 62 | { 63 | "title": "your-section-title-content", 64 | "rows": [ 65 | { 66 | "id": "unique-row-identifier", 67 | "title": "row-title-content", 68 | "description": "row-description-content", 69 | } 70 | ], 71 | }, 72 | ], 73 | }, 74 | }, 75 | ) 76 | print(f"create_button: {v}") 77 | print("sending button") 78 | v = await app.send_button( 79 | { 80 | "header": "Header Testing", 81 | "body": "Body Testing", 82 | "footer": "Footer Testing", 83 | "action": { 84 | "button": "cta-button-content", 85 | "sections": [ 86 | { 87 | "title": "your-secti", 88 | "rows": [ 89 | { 90 | "id": "unique-row-", 91 | "title": "row-title-", 92 | "description": "row-description-", 93 | } 94 | ], 95 | }, 96 | ], 97 | }, 98 | }, 99 | dest_phone_number, 100 | sender=1, 101 | ) 102 | while not v.done(): 103 | await asyncio.sleep(1) 104 | try: app.handle(v.result()) 105 | except Exception as error: 106 | print(f"error: {error}") 107 | print("sending wrong button") 108 | v = await app.send_button( 109 | { 110 | "header": "Header Testing", 111 | 112 | }, 113 | dest_phone_number, 114 | sender=1, 115 | ) 116 | while not v.done(): 117 | await asyncio.sleep(1) 118 | try: app.handle(v.result()) 119 | except Exception as error: 120 | print(f"error: {error}") 121 | raise Exception("Error") 122 | 123 | 124 | print(f"send_button: {v}") 125 | print("sending image") 126 | v = await app.send_image( 127 | "https://filesamples.com/samples/image/jpeg/sample_640%C3%97426.jpeg", 128 | dest_phone_number, 129 | sender=1, 130 | ) 131 | print(f"send_image: {v}") 132 | print("sending video") 133 | v = await app.send_video( 134 | "https://filesamples.com/samples/video/mp4/sample_1280x720_surfing_with_audio.mp4", 135 | dest_phone_number, 136 | sender=1, 137 | ) 138 | print(f"send_video: {v}") 139 | print("sending audio") 140 | v = await app.send_audio( 141 | "https://filesamples.com/samples/audio/mp3/Symphony%20No.6%20(1st%20movement).mp3", 142 | dest_phone_number, 143 | sender=1, 144 | ) 145 | print(f"send_audio: {v}") 146 | print("sending document") 147 | v = await app.send_document( 148 | "https://filesamples.com/samples/document/docx/sample1.docx", 149 | dest_phone_number, 150 | sender=1, 151 | ) 152 | print(f"send_document: {v}") 153 | print("sending location") 154 | v = await app.send_location( 155 | "37.7749", "-122.4194", "test", "test, test", dest_phone_number, sender=1 156 | ) 157 | print(f"send_location: {v}") 158 | print("sending template") 159 | v = await app.send_template("hello_world", dest_phone_number, sender=1) 160 | print( 161 | f"send_template: {v}" 162 | ) # this returns error if the phone number is not a test phone number 163 | 164 | 165 | 166 | 167 | await asyncio.sleep(60) 168 | 169 | async def upload(): 170 | print("uploading media") 171 | f = await app.upload_media( 172 | getenv("TEST_IMAGE_PATH"), 173 | sender=1 174 | ) 175 | print(f"upload_media: {f}") 176 | print(f) 177 | 178 | 179 | asyncio.run(run_test()) 180 | asyncio.run(upload()) 181 | -------------------------------------------------------------------------------- /tests/tests.py: -------------------------------------------------------------------------------- 1 | from whatsapp import WhatsApp, Message 2 | from dotenv import load_dotenv 3 | from os import getenv 4 | 5 | load_dotenv() 6 | token = getenv("GRAPH_API_TOKEN") 7 | phone_number_id = {1: getenv("TEST_PHONE_NUMBER_ID")} 8 | dest_phone_number = getenv("DEST_PHONE_NUMBER") 9 | 10 | app = WhatsApp(token=token, phone_number_id=phone_number_id, update_check=False) 11 | msg = app.create_message(to=dest_phone_number, content="Hello world") 12 | 13 | 14 | # test every single method and print the result 15 | print("Testing send_text") 16 | msg.send(sender=1) 17 | 18 | print("Testing send_reply_button") 19 | v = app.send_reply_button( 20 | button={ 21 | "type": "button", 22 | "body": {"text": "This is a test button"}, 23 | "action": { 24 | "buttons": [ 25 | {"type": "reply", "reply": {"id": "b1", "title": "This is button 1"}}, 26 | {"type": "reply", "reply": {"id": "b2", "title": "this is button 2"}}, 27 | ] 28 | }, 29 | }, 30 | recipient_id=dest_phone_number, 31 | sender=1, 32 | ) 33 | print(f"send_reply_button: {v}") 34 | 35 | 36 | print("Creating button") 37 | v = app.create_button( 38 | button={ 39 | "header": {"type": "text", "text": "your-header-content"}, 40 | "body": {"text": "your-text-message-content"}, 41 | "footer": {"text": "your-footer-content"}, 42 | "action": { 43 | "button": "cta-button-content", 44 | "sections": [ 45 | { 46 | "title": "your-section-title-content", 47 | "rows": [ 48 | { 49 | "id": "unique-row-identifier", 50 | "title": "row-title-content", 51 | "description": "row-description-content", 52 | } 53 | ], 54 | }, 55 | ], 56 | }, 57 | }, 58 | ) 59 | print(f"create_button: {v}") 60 | print("sending button") 61 | v = app.send_button( 62 | { 63 | "header": "Header Testing", 64 | "body": "Body Testing", 65 | "footer": "Footer Testing", 66 | "action": { 67 | "button": "cta-button-content", 68 | "sections": [ 69 | { 70 | "title": "your-secti", 71 | "rows": [ 72 | { 73 | "id": "unique-row-", 74 | "title": "row-title-", 75 | "description": "row-description-", 76 | } 77 | ], 78 | }, 79 | ], 80 | }, 81 | }, 82 | dest_phone_number, 83 | sender=1, 84 | ) 85 | print(f"send_button: {v}") 86 | print("sending image") 87 | v = app.send_image( 88 | "https://file-examples.com/storage/feb05093336710053a32bc1/2017/10/file_example_JPG_1MB.jpg", 89 | dest_phone_number, 90 | sender=1, 91 | ) 92 | print(f"send_image: {v}") 93 | print("sending video") 94 | v = app.send_video( 95 | "https://file-examples.com/storage/feb05093336710053a32bc1/2017/04/file_example_MP4_480_1_5MG.mp4", 96 | dest_phone_number, 97 | sender=1, 98 | ) 99 | print(f"send_video: {v}") 100 | print("sending audio") 101 | v = app.send_audio( 102 | "https://file-examples.com/storage/feb05093336710053a32bc1/2017/11/file_example_MP3_1MG.mp3", 103 | dest_phone_number, 104 | sender=1, 105 | ) 106 | print(f"send_audio: {v}") 107 | print("sending document") 108 | v = app.send_document( 109 | "https://file-examples.com/storage/feb05093336710053a32bc1/2017/10/file-example_PDF_1MB.pdf", 110 | dest_phone_number, 111 | sender=1, 112 | ) 113 | print(f"send_document: {v}") 114 | print("sending location") 115 | v = app.send_location( 116 | "37.7749", "-122.4194", "test", "test, test", dest_phone_number, sender=1 117 | ) 118 | print(f"send_location: {v}") 119 | print("sending template") 120 | v = app.send_template("hello_world", dest_phone_number, sender=1) 121 | print( 122 | f"send_template: {v}" 123 | ) # this returns error if the phone number is not a test phone number 124 | -------------------------------------------------------------------------------- /whatsapp/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Unofficial Python wrapper for the WhatsApp Cloud API. 3 | """ 4 | 5 | from __future__ import annotations 6 | import requests 7 | import logging 8 | import json 9 | import asyncio 10 | import aiohttp 11 | from bs4 import BeautifulSoup 12 | from fastapi import FastAPI, HTTPException, Request 13 | from uvicorn import run as _run 14 | from .constants import VERSION 15 | from .ext._property import authorized 16 | from .ext._send_others import send_custom_json, send_contacts 17 | from .ext._message import send_template 18 | from .ext._send_media import ( 19 | send_image, 20 | send_video, 21 | send_audio, 22 | send_location, 23 | send_sticker, 24 | send_document, 25 | ) 26 | from .ext._media import upload_media, query_media_url, download_media, delete_media 27 | from .ext._buttons import send_button, create_button, send_reply_button 28 | from .ext._static import ( 29 | is_message, 30 | get_mobile, 31 | get_author, 32 | get_name, 33 | get_message, 34 | get_message_id, 35 | get_message_type, 36 | get_message_timestamp, 37 | get_audio, 38 | get_delivery, 39 | get_document, 40 | get_image, 41 | get_sticker, 42 | get_interactive_response, 43 | get_location, 44 | get_video, 45 | changed_field, 46 | ) 47 | 48 | from .async_ext._property import authorized as async_authorized 49 | from .async_ext._send_others import ( 50 | send_custom_json as async_send_custom_json, 51 | send_contacts as async_send_contacts, 52 | ) 53 | from .async_ext._message import send_template as async_send_template 54 | from .async_ext._send_media import ( 55 | send_image as async_send_image, 56 | send_video as async_send_video, 57 | send_audio as async_send_audio, 58 | send_location as async_send_location, 59 | send_sticker as async_send_sticker, 60 | send_document as async_send_document, 61 | ) 62 | from .async_ext._media import ( 63 | upload_media as async_upload_media, 64 | query_media_url as async_query_media_url, 65 | download_media as async_download_media, 66 | delete_media as async_delete_media, 67 | ) 68 | from .async_ext._buttons import ( 69 | send_button as async_send_button, 70 | create_button as async_create_button, 71 | send_reply_button as async_send_reply_button, 72 | ) 73 | from .async_ext._static import ( 74 | is_message as async_is_message, 75 | get_mobile as async_get_mobile, 76 | get_author as async_get_author, 77 | get_name as async_get_name, 78 | get_message as async_get_message, 79 | get_message_id as async_get_message_id, 80 | get_message_type as async_get_message_type, 81 | get_message_timestamp as async_get_message_timestamp, 82 | get_audio as async_get_audio, 83 | get_delivery as async_get_delivery, 84 | get_document as async_get_document, 85 | get_image as async_get_image, 86 | get_sticker as async_get_sticker, 87 | get_interactive_response as async_get_interactive_response, 88 | get_location as async_get_location, 89 | get_video as async_get_video, 90 | changed_field as async_changed_field, 91 | ) 92 | 93 | from .errors import Handle 94 | 95 | 96 | class WhatsApp: 97 | def __init__( 98 | self, 99 | token: str = "", 100 | phone_number_id: dict = "", 101 | logger: bool = True, 102 | update_check: bool = True, 103 | verify_token: str = "", 104 | debug: bool = True, 105 | version: str = "latest", 106 | ): 107 | """ 108 | Initialize the WhatsApp Object 109 | 110 | Args: 111 | token[str]: Token for the WhatsApp cloud API obtained from the Facebook developer portal 112 | phone_number_id[str]: Phone number id for the WhatsApp cloud API obtained from the developer portal 113 | logger[bool]: Whether to enable logging or not (default: True) 114 | """ 115 | 116 | # Check if the version is up to date 117 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 118 | 119 | self.l = phone_number_id 120 | 121 | if isinstance(phone_number_id, dict): 122 | # use first phone number id as default 123 | phone_number_id = phone_number_id[list(phone_number_id.keys())[0]] 124 | 125 | elif phone_number_id == "": 126 | logging.error("Phone number ID not provided") 127 | raise ValueError("Phone number ID not provided but required") 128 | elif isinstance(phone_number_id, str): 129 | logging.critical( 130 | "The phone number ID should be a dictionary of phone numbers and their IDs. Using strings is deprecated." 131 | ) 132 | raise ValueError( 133 | "Phone number ID should be a dictionary of phone numbers and their IDs" 134 | ) 135 | else: 136 | pass 137 | 138 | self.VERSION = VERSION # package version 139 | r = requests.get( 140 | "https://developers.facebook.com/docs/graph-api/changelog/" 141 | ).text 142 | 143 | # dynamically get the latest version of the API 144 | if version == "latest": 145 | soup = BeautifulSoup(r, features="html.parser") 146 | t1 = soup.findAll("table") 147 | 148 | def makeversion(table: BeautifulSoup) -> str: 149 | result = [] 150 | allrows = table.findAll("tr") 151 | for row in allrows: 152 | result.append([]) 153 | allcols = row.findAll("td") 154 | for col in allcols: 155 | thestrings = [(s) for s in col.findAll(text=True)] 156 | thetext = "".join(thestrings) 157 | result[-1].append(thetext) 158 | return result[0][1] 159 | 160 | self.LATEST = makeversion(t1[0]) # latest version of the API 161 | else: 162 | self.LATEST = version 163 | 164 | if update_check is True: 165 | latest = str( 166 | requests.get("https://pypi.org/pypi/whatsapp-python/json").json()[ 167 | "info" 168 | ]["version"] 169 | ) 170 | if self.VERSION != latest: 171 | try: 172 | version_int = int(self.VERSION.replace(".", "")) 173 | except: 174 | version_int = 0 175 | try: 176 | latest_int = int(latest.replace(".", "")) 177 | except: 178 | latest_int = 0 179 | # this is to avoid the case where the version is 1.0.10 and the latest is 1.0.2 (possible if user is using the github version) 180 | if version_int < latest_int: 181 | if version_int == 0: 182 | logging.critical( 183 | f"There was an error while checking for updates, please check for updates manually. This may be due to the version being a post-release version (e.g. 1.0.0.post1) or a pre-release version (e.g. 1.0.0a1). READ THE CHANGELOG BEFORE UPDATING. NEW VERSIONS MAY BREAK YOUR CODE IF NOT PROPERLY UPDATED." 184 | ) 185 | else: 186 | logging.critical( 187 | f"Whatsapp-python is out of date. Please update to the latest version {latest}. READ THE CHANGELOG BEFORE UPDATING. NEW VERSIONS MAY BREAK YOUR CODE IF NOT PROPERLY UPDATED." 188 | ) 189 | 190 | if token == "": 191 | logging.error("Token not provided") 192 | raise ValueError("Token not provided but required") 193 | if phone_number_id == "": 194 | logging.error("Phone number ID not provided") 195 | raise ValueError("Phone number ID not provided but required") 196 | self.token = token 197 | self.phone_number_id = phone_number_id 198 | self.base_url = f"https://graph.facebook.com/{self.LATEST}" 199 | self.url = f"{self.base_url}/{phone_number_id}/messages" 200 | self.verify_token = verify_token 201 | 202 | async def base(*args): 203 | pass 204 | 205 | self.message_handler = base 206 | self.other_handler = base 207 | self.verification_handler = base 208 | self.headers = { 209 | "Content-Type": "application/json", 210 | "Authorization": f"Bearer {self.token}", 211 | } 212 | if logger is False: 213 | logging.disable(logging.INFO) 214 | logging.disable(logging.ERROR) 215 | if debug is False: 216 | logging.disable(logging.DEBUG) 217 | logging.disable(logging.ERROR) 218 | 219 | self.app = FastAPI() 220 | 221 | # Verification handler has 1 argument: challenge (str | bool): str if verification is successful, False if not 222 | 223 | @self.app.get("/") 224 | async def verify_endpoint(r: Request): 225 | if r.query_params.get("hub.verify_token") == self.verify_token: 226 | logging.debug("Webhook verified successfully") 227 | challenge = r.query_params.get("hub.challenge") 228 | await self.verification_handler(challenge) 229 | await self.other_handler(challenge) 230 | return int(challenge) 231 | logging.error("Webhook Verification failed - token mismatch") 232 | await self.verification_handler(False) 233 | await self.other_handler(False) 234 | return {"success": False} 235 | 236 | @self.app.post("/") 237 | async def hook(r: Request): 238 | try: 239 | # Handle Webhook Subscriptions 240 | data = await r.json() 241 | if data is None: 242 | return {"success": False} 243 | data_str = json.dumps(data, indent=4) 244 | # log the data received only if the log level is debug 245 | logging.debug(f"Received webhook data: {data_str}") 246 | 247 | changed_field = self.changed_field(data) 248 | if changed_field == "messages": 249 | new_message = self.is_message(data) 250 | if new_message: 251 | msg = Message(instance=self, data=data) 252 | await self.message_handler(msg) 253 | await self.other_handler(msg) 254 | return {"success": True} 255 | except Exception as e: 256 | logging.error(f"Error parsing message: {e}") 257 | raise HTTPException( 258 | status_code=500, detail={"success": False, "error": str(e)} 259 | ) 260 | 261 | # all the files starting with _ are imported here, and should not be imported directly. 262 | 263 | is_message = staticmethod(is_message) 264 | get_mobile = staticmethod(get_mobile) 265 | get_name = staticmethod(get_name) 266 | get_message = staticmethod(get_message) 267 | get_message_id = staticmethod(get_message_id) 268 | get_message_type = staticmethod(get_message_type) 269 | get_message_timestamp = staticmethod(get_message_timestamp) 270 | get_audio = staticmethod(get_audio) 271 | get_delivery = staticmethod(get_delivery) 272 | get_document = staticmethod(get_document) 273 | get_image = staticmethod(get_image) 274 | get_sticker = staticmethod(get_sticker) 275 | get_interactive_response = staticmethod(get_interactive_response) 276 | get_location = staticmethod(get_location) 277 | get_video = staticmethod(get_video) 278 | changed_field = staticmethod(changed_field) 279 | get_author = staticmethod(get_author) 280 | 281 | send_button = send_button 282 | create_button = create_button 283 | send_reply_button = send_reply_button 284 | send_image = send_image 285 | send_video = send_video 286 | send_audio = send_audio 287 | send_location = send_location 288 | send_sticker = send_sticker 289 | send_document = send_document 290 | upload_media = upload_media 291 | query_media_url = query_media_url 292 | download_media = download_media 293 | delete_media = delete_media 294 | send_template = send_template 295 | send_custom_json = send_custom_json 296 | send_contacts = send_contacts 297 | authorized = property(authorized) 298 | 299 | def create_message(self, **kwargs) -> Message: 300 | """ 301 | Create a message object 302 | 303 | Args: 304 | data[dict]: The message data 305 | content[str]: The message content 306 | to[str]: The recipient 307 | rec_type[str]: The recipient type (individual/group) 308 | """ 309 | return Message(**kwargs, instance=self) 310 | 311 | def on_message(self, handler: function): 312 | """ 313 | Set the handler for incoming messages 314 | 315 | Args: 316 | handler[function]: The handler function 317 | """ 318 | self.message_handler = handler 319 | 320 | def on_event(self, handler: function): 321 | """ 322 | Set the handler for other events 323 | 324 | Args: 325 | handler[function]: The handler function 326 | """ 327 | self.other_handler = handler 328 | 329 | def on_verification(self, handler: function): 330 | """ 331 | Set the handler for verification 332 | 333 | Args: 334 | handler[function]: The handler function 335 | """ 336 | self.verification_handler = handler 337 | 338 | def run(self, host: str = "localhost", port: int = 5000, **options): 339 | _run(self.app, host=host, port=port, **options) 340 | 341 | 342 | class AsyncWhatsApp(WhatsApp): 343 | def __init__( 344 | self, 345 | token: str = "", 346 | phone_number_id: dict = "", 347 | logger: bool = True, 348 | update_check: bool = True, 349 | verify_token: str = "", 350 | debug: bool = True, 351 | version: str = "latest", 352 | ): 353 | """ 354 | Initialize the WhatsApp Object 355 | 356 | Args: 357 | token[str]: Token for the WhatsApp cloud API obtained from the Facebook developer portal 358 | phone_number_id[str]: Phone number id for the WhatsApp cloud API obtained from the developer portal 359 | logger[bool]: Whether to enable logging or not (default: True) 360 | """ 361 | 362 | # Check if the version is up to date 363 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 364 | self.l = phone_number_id 365 | 366 | if isinstance(phone_number_id, dict): 367 | # use first phone number id as default 368 | phone_number_id = phone_number_id[list(phone_number_id.keys())[0]] 369 | 370 | elif phone_number_id == "": 371 | logging.error("Phone number ID not provided") 372 | raise ValueError("Phone number ID not provided but required") 373 | elif isinstance(phone_number_id, str): 374 | logging.critical( 375 | "The phone number ID should be a dictionary of phone numbers and their IDs. Using strings is deprecated." 376 | ) 377 | raise ValueError( 378 | "Phone number ID should be a dictionary of phone numbers and their IDs" 379 | ) 380 | else: 381 | pass 382 | 383 | self.VERSION = VERSION # package version 384 | r = requests.get( 385 | "https://developers.facebook.com/docs/graph-api/changelog/" 386 | ).text 387 | 388 | # dynamically get the latest version of the API 389 | if version == "latest": 390 | soup = BeautifulSoup(r, features="html.parser") 391 | t1 = soup.findAll("table") 392 | 393 | def makeversion(table: BeautifulSoup) -> str: 394 | result = [] 395 | allrows = table.findAll("tr") 396 | for row in allrows: 397 | result.append([]) 398 | allcols = row.findAll("td") 399 | for col in allcols: 400 | thestrings = [(s) for s in col.findAll(text=True)] 401 | thetext = "".join(thestrings) 402 | result[-1].append(thetext) 403 | return result[0][1] 404 | 405 | self.LATEST = makeversion(t1[0]) # latest version of the API 406 | else: 407 | self.LATEST = version 408 | 409 | if update_check is True: 410 | latest = str( 411 | requests.get("https://pypi.org/pypi/whatsapp-python/json").json()[ 412 | "info" 413 | ]["version"] 414 | ) 415 | if self.VERSION != latest: 416 | try: 417 | version_int = int(self.VERSION.replace(".", "")) 418 | except: 419 | version_int = 0 420 | try: 421 | latest_int = int(latest.replace(".", "")) 422 | except: 423 | latest_int = 0 424 | # this is to avoid the case where the version is 1.0.10 and the latest is 1.0.2 (possible if user is using the github version) 425 | if version_int < latest_int: 426 | if version_int == 0: 427 | logging.critical( 428 | f"There was an error while checking for updates, please check for updates manually. This may be due to the version being a post-release version (e.g. 1.0.0.post1) or a pre-release version (e.g. 1.0.0a1). READ THE CHANGELOG BEFORE UPDATING. NEW VERSIONS MAY BREAK YOUR CODE IF NOT PROPERLY UPDATED." 429 | ) 430 | else: 431 | logging.critical( 432 | f"Whatsapp-python is out of date. Please update to the latest version {latest}. READ THE CHANGELOG BEFORE UPDATING. NEW VERSIONS MAY BREAK YOUR CODE IF NOT PROPERLY UPDATED." 433 | ) 434 | 435 | if token == "": 436 | logging.error("Token not provided") 437 | raise ValueError("Token not provided but required") 438 | if phone_number_id == "": 439 | logging.error("Phone number ID not provided") 440 | raise ValueError("Phone number ID not provided but required") 441 | self.token = token 442 | self.phone_number_id = phone_number_id 443 | self.base_url = f"https://graph.facebook.com/{self.LATEST}" 444 | self.url = f"{self.base_url}/{phone_number_id}/messages" 445 | self.verify_token = verify_token 446 | 447 | async def base(*args): 448 | pass 449 | 450 | self.message_handler = base 451 | self.other_handler = base 452 | self.verification_handler = base 453 | self.headers = { 454 | "Content-Type": "application/json", 455 | "Authorization": f"Bearer {self.token}", 456 | } 457 | if logger is False: 458 | logging.disable(logging.INFO) 459 | logging.disable(logging.ERROR) 460 | if debug is False: 461 | logging.disable(logging.DEBUG) 462 | logging.disable(logging.ERROR) 463 | 464 | self.app = FastAPI() 465 | 466 | # Verification handler has 1 argument: challenge (str | bool): str if verification is successful, False if not 467 | 468 | @self.app.get("/") 469 | async def verify_endpoint(r: Request): 470 | if r.query_params.get("hub.verify_token") == self.verify_token: 471 | logging.debug("Webhook verified successfully") 472 | challenge = r.query_params.get("hub.challenge") 473 | await self.verification_handler(challenge) 474 | await self.other_handler(challenge) 475 | return int(challenge) 476 | logging.error("Webhook Verification failed - token mismatch") 477 | await self.verification_handler(False) 478 | await self.other_handler(False) 479 | return {"success": False} 480 | 481 | @self.app.post("/") 482 | async def hook(r: Request): 483 | try: 484 | # Handle Webhook Subscriptions 485 | data = await r.json() 486 | if data is None: 487 | return {"success": False} 488 | data_str = json.dumps(data, indent=4) 489 | # log the data received only if the log level is debug 490 | logging.debug(f"Received webhook data: {data_str}") 491 | 492 | changed_field = self.changed_field(data) 493 | if changed_field == "messages": 494 | new_message = self.is_message(data) 495 | if new_message: 496 | msg = Message(instance=self, data=data) 497 | await self.message_handler(msg) 498 | await self.other_handler(msg) 499 | return {"success": True} 500 | except Exception as e: 501 | logging.error(f"Error parsing message: {e}") 502 | raise HTTPException( 503 | status_code=500, detail={"success": False, "error": str(e)} 504 | ) 505 | 506 | # all the files starting with _ are imported here, and should not be imported directly. 507 | 508 | is_message = staticmethod(is_message) 509 | get_mobile = staticmethod(get_mobile) 510 | get_name = staticmethod(get_name) 511 | get_message = staticmethod(get_message) 512 | get_message_id = staticmethod(get_message_id) 513 | get_message_type = staticmethod(get_message_type) 514 | get_message_timestamp = staticmethod(get_message_timestamp) 515 | get_audio = staticmethod(get_audio) 516 | get_delivery = staticmethod(get_delivery) 517 | get_document = staticmethod(get_document) 518 | get_image = staticmethod(get_image) 519 | get_sticker = staticmethod(get_sticker) 520 | get_interactive_response = staticmethod(get_interactive_response) 521 | get_location = staticmethod(get_location) 522 | get_video = staticmethod(get_video) 523 | changed_field = staticmethod(changed_field) 524 | get_author = staticmethod(get_author) 525 | 526 | send_button = async_send_button 527 | create_button = async_create_button 528 | send_reply_button = async_send_reply_button 529 | send_image = async_send_image 530 | send_video = async_send_video 531 | send_audio = async_send_audio 532 | send_location = async_send_location 533 | send_sticker = async_send_sticker 534 | send_document = async_send_document 535 | upload_media = async_upload_media 536 | query_media_url = async_query_media_url 537 | download_media = async_download_media 538 | delete_media = async_delete_media 539 | send_template = async_send_template 540 | send_custom_json = async_send_custom_json 541 | send_contacts = async_send_contacts 542 | authorized = property(async_authorized) 543 | 544 | def handle(self, data: dict): 545 | return Handle(data) 546 | 547 | def create_message(self, **kwargs) -> AsyncMessage: 548 | """ 549 | Create a message object 550 | 551 | Args: 552 | data[dict]: The message data 553 | content[str]: The message content 554 | to[str]: The recipient 555 | rec_type[str]: The recipient type (individual/group) 556 | """ 557 | return AsyncMessage(**kwargs, instance=self) 558 | 559 | def on_message(self, handler: function): 560 | """ 561 | Set the handler for incoming messages 562 | 563 | Args: 564 | handler[function]: The handler function 565 | """ 566 | self.message_handler = handler 567 | 568 | def on_event(self, handler: function): 569 | """ 570 | Set the handler for other events 571 | 572 | Args: 573 | handler[function]: The handler function 574 | """ 575 | self.other_handler = handler 576 | 577 | def on_verification(self, handler: function): 578 | """ 579 | Set the handler for verification 580 | 581 | Args: 582 | handler[function]: The handler function 583 | """ 584 | self.verification_handler = handler 585 | 586 | def run(self, host: str = "localhost", port: int = 5000, **options): 587 | _run(self.app, host=host, port=port, **options) 588 | 589 | 590 | class Message: 591 | # type: ignore 592 | def __init__( 593 | self, 594 | id: int = None, 595 | data: dict = {}, 596 | instance: WhatsApp = None, 597 | content: str = "", 598 | to: str = "", 599 | rec_type: str = "individual", 600 | ): 601 | self.instance = instance 602 | self.url = self.instance.url 603 | self.headers = self.instance.headers 604 | 605 | try: 606 | self.id = instance.get_message_id(data) 607 | except: 608 | self.id = id 609 | try: 610 | self.type = self.instance.get_message_type(data) 611 | except: 612 | self.type = "text" 613 | self.data = data 614 | self.rec = rec_type 615 | self.to = to 616 | try: 617 | self.content = content if content != "" else self.instance.get_message(data) 618 | except: 619 | self.content = content 620 | try: 621 | self.name = self.instance.get_name(data) 622 | except: 623 | self.name = None 624 | 625 | if self.type == "image": 626 | try: 627 | self.image = self.instance.get_image(data) 628 | except: 629 | self.image = None 630 | if self.type == "sticker": 631 | try: 632 | self.sticker = self.instance.get_sticker(data) 633 | except: 634 | self.sticker = None 635 | elif self.type == "video": 636 | try: 637 | self.video = self.instance.get_video(data) 638 | except: 639 | self.video = None 640 | elif self.type == "audio": 641 | try: 642 | self.audio = self.instance.get_audio(data) 643 | except: 644 | pass 645 | elif self.type == "document": 646 | try: 647 | self.document = self.instance.get_document(data) 648 | except: 649 | pass 650 | elif self.type == "location": 651 | try: 652 | self.location = self.instance.get_location(data) 653 | except: 654 | pass 655 | elif self.type == "interactive": 656 | try: 657 | self.interactive = self.instance.get_interactive_response(data) 658 | except: 659 | pass 660 | 661 | def reply(self, reply_text: str = "", preview_url: bool = True) -> dict: 662 | if self.data == {}: 663 | return {"error": "No data provided"} 664 | author = self.instance.get_author(self.data) 665 | payload = { 666 | "messaging_product": "whatsapp", 667 | "recipient_type": "individual", 668 | "to": str(author), 669 | "type": "text", 670 | "context": {"message_id": self.id}, 671 | "text": {"preview_url": preview_url, "body": reply_text}, 672 | } 673 | logging.info(f"Replying to {self.id}") 674 | r = requests.post(self.url, headers=self.headers, json=payload) 675 | if r.status_code == 200: 676 | logging.info(f"Message sent to {self.instance.get_author(self.data)}") 677 | return r.json() 678 | logging.info(f"Message not sent to {self.instance.get_author(self.data)}") 679 | logging.info(f"Status code: {r.status_code}") 680 | logging.error(f"Response: {r.json()}") 681 | return r.json() 682 | 683 | def mark_as_read(self) -> dict: 684 | 685 | payload = { 686 | "messaging_product": "whatsapp", 687 | "status": "read", 688 | "message_id": self.id, 689 | } 690 | 691 | response = requests.post( 692 | f"{self.instance.url}", headers=self.instance.headers, json=payload 693 | ) 694 | if response.status_code == 200: 695 | logging.info(response.json()) 696 | return response.json() 697 | else: 698 | logging.error(response.json()) 699 | return response.json() 700 | 701 | def send(self, sender=None, preview_url: bool = True) -> dict: 702 | 703 | try: 704 | sender = dict(self.instance.l)[sender] 705 | 706 | except: 707 | sender = self.instance.phone_number_id 708 | 709 | if sender == None: 710 | sender = self.instance.phone_number_id 711 | 712 | url = f"https://graph.facebook.com/{self.instance.LATEST}/{sender}/messages" 713 | data = { 714 | "messaging_product": "whatsapp", 715 | "recipient_type": self.rec, 716 | "to": self.to, 717 | "type": "text", 718 | "text": {"preview_url": preview_url, "body": self.content}, 719 | } 720 | logging.info(f"Sending message to {self.to}") 721 | r = requests.post(url, headers=self.headers, json=data) 722 | if r.status_code == 200: 723 | logging.info(f"Message sent to {self.to}") 724 | return r.json() 725 | logging.info(f"Message not sent to {self.to}") 726 | logging.info(f"Status code: {r.status_code}") 727 | logging.error(f"Response: {r.json()}") 728 | return r.json() 729 | 730 | def react(self, emoji: str) -> dict: 731 | data = { 732 | "messaging_product": "whatsapp", 733 | "recipient_type": "individual", 734 | "to": self.to, 735 | "type": "reaction", 736 | "reaction": {"message_id": self.id, "emoji": emoji}, 737 | } 738 | logging.info(f"Reacting to {self.id}") 739 | r = requests.post(self.url, headers=self.headers, json=data) 740 | if r.status_code == 200: 741 | logging.info(f"Reaction sent to {self.to}") 742 | return r.json() 743 | logging.info(f"Reaction not sent to {self.to}") 744 | logging.info(f"Status code: {r.status_code}") 745 | logging.debug(f"Response: {r.json()}") 746 | return r.json() 747 | 748 | 749 | class AsyncMessage: 750 | # type: ignore 751 | def __init__( 752 | self, 753 | id: int = None, 754 | data: dict = {}, 755 | instance: WhatsApp = None, 756 | content: str = "", 757 | to: str = "", 758 | rec_type: str = "individual", 759 | ): 760 | self.instance = instance 761 | self.url = self.instance.url 762 | self.headers = self.instance.headers 763 | 764 | try: 765 | self.id = instance.get_message_id(data) 766 | except: 767 | self.id = id 768 | try: 769 | self.type = self.instance.get_message_type(data) 770 | except: 771 | self.type = "text" 772 | self.data = data 773 | self.rec = rec_type 774 | self.to = to 775 | try: 776 | self.content = content if content != "" else self.instance.get_message(data) 777 | except: 778 | self.content = content 779 | try: 780 | self.name = self.instance.get_name(data) 781 | except: 782 | self.name = None 783 | 784 | if self.type == "image": 785 | try: 786 | self.image = self.instance.get_image(data) 787 | except: 788 | self.image = None 789 | if self.type == "sticker": 790 | try: 791 | self.sticker = self.instance.get_sticker(data) 792 | except: 793 | self.sticker = None 794 | elif self.type == "video": 795 | try: 796 | self.video = self.instance.get_video(data) 797 | except: 798 | self.video = None 799 | elif self.type == "audio": 800 | try: 801 | self.audio = self.instance.get_audio(data) 802 | except: 803 | pass 804 | elif self.type == "document": 805 | try: 806 | self.document = self.instance.get_document(data) 807 | except: 808 | pass 809 | elif self.type == "location": 810 | try: 811 | self.location = self.instance.get_location(data) 812 | except: 813 | pass 814 | elif self.type == "interactive": 815 | try: 816 | self.interactive = self.instance.get_interactive_response(data) 817 | except: 818 | pass 819 | 820 | async def reply( 821 | self, reply_text: str = "", preview_url: bool = True 822 | ) -> asyncio.Future: 823 | if self.data == {}: 824 | return {"error": "No data provided"} 825 | author = self.instance.get_author(self.data) 826 | payload = { 827 | "messaging_product": "whatsapp", 828 | "recipient_type": "individual", 829 | "to": str(author), 830 | "type": "text", 831 | "context": {"message_id": self.id}, 832 | "text": {"preview_url": preview_url, "body": reply_text}, 833 | } 834 | logging.info(f"Replying to {self.id}") 835 | 836 | async def call(): 837 | async with aiohttp.ClientSession() as session: 838 | async with session.post( 839 | self.url, headers=self.headers, json=payload 840 | ) as response: 841 | if response.status == 200: 842 | logging.info( 843 | f"Message sent to {self.instance.get_author(self.data)}" 844 | ) 845 | return await response.json() 846 | logging.info( 847 | f"Message not sent to {self.instance.get_author(self.data)}" 848 | ) 849 | logging.info(f"Status code: {response.status}") 850 | logging.error(f"Response: {await response.json()}") 851 | return await response.json() 852 | 853 | f = asyncio.ensure_future(call()) 854 | await asyncio.sleep(0.001) # make asyncio run the task 855 | return f 856 | 857 | async def mark_as_read(self) -> asyncio.Future: 858 | 859 | payload = { 860 | "messaging_product": "whatsapp", 861 | "status": "read", 862 | "message_id": self.id, 863 | } 864 | 865 | async def call(): 866 | async with aiohttp.ClientSession() as session: 867 | async with session.post( 868 | f"{self.instance.url}", headers=self.instance.headers, json=payload 869 | ) as response: 870 | if response.status == 200: 871 | logging.info(await response.json()) 872 | return await response.json() 873 | else: 874 | logging.error(await response.json()) 875 | return await response.json() 876 | 877 | f = asyncio.ensure_future(call()) 878 | await asyncio.sleep(0.001) # make asyncio run the task 879 | return f 880 | 881 | async def send(self, sender=None, preview_url: bool = True) -> asyncio.Future: 882 | try: 883 | sender = dict(self.instance.l)[sender] 884 | 885 | except: 886 | sender = self.instance.phone_number_id 887 | 888 | if sender == None: 889 | sender = self.instance.phone_number_id 890 | 891 | url = f"https://graph.facebook.com/{self.instance.LATEST}/{sender}/messages" 892 | data = { 893 | "messaging_product": "whatsapp", 894 | "recipient_type": self.rec, 895 | "to": self.to, 896 | "type": "text", 897 | "text": {"preview_url": preview_url, "body": self.content}, 898 | } 899 | logging.info(f"Sending message to {self.to}") 900 | 901 | async def call(): 902 | print("sending") 903 | async with aiohttp.ClientSession() as session: 904 | async with session.post( 905 | url, headers=self.headers, json=data 906 | ) as response: 907 | if response.status == 200: 908 | logging.info(f"Message sent to {self.to}") 909 | return await response.json() 910 | logging.info(f"Message not sent to {self.to}") 911 | logging.info(f"Status code: {response.status}") 912 | logging.error(f"Response: {await response.json()}") 913 | return await response.json() 914 | 915 | f = asyncio.ensure_future(call()) 916 | await asyncio.sleep(0.001) # make asyncio run the task 917 | return f 918 | 919 | async def react(self, emoji: str) -> asyncio.Future: 920 | data = { 921 | "messaging_product": "whatsapp", 922 | "recipient_type": "individual", 923 | "to": self.to, 924 | "type": "reaction", 925 | "reaction": {"message_id": self.id, "emoji": emoji}, 926 | } 927 | logging.info(f"Reacting to {self.id}") 928 | 929 | async def call(): 930 | async with aiohttp.ClientSession() as session: 931 | async with session.post( 932 | self.url, headers=self.headers, json=data 933 | ) as response: 934 | if response.status == 200: 935 | logging.info(f"Reaction sent to {self.to}") 936 | return await response.json() 937 | logging.info(f"Reaction not sent to {self.to}") 938 | logging.info(f"Status code: {response.status}") 939 | logging.debug(f"Response: {await response.json()}") 940 | return await response.json() 941 | 942 | f = asyncio.ensure_future(call()) 943 | await asyncio.sleep(0.001) 944 | return f 945 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_buttons.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import aiohttp 3 | import asyncio 4 | from typing import Dict, Any 5 | 6 | 7 | def create_button(self, button: Dict[Any, Any]) -> Dict[Any, Any]: 8 | """ 9 | Method to create a button object to be used in the send_message method. 10 | 11 | This is method is designed to only be used internally by the send_button method. 12 | 13 | Args: 14 | button[dict]: A dictionary containing the button data 15 | """ 16 | data = {"type": "list", "action": button.get("action")} 17 | if button.get("header"): 18 | data["header"] = {"type": "text", "text": button.get("header")} 19 | if button.get("body"): 20 | data["body"] = {"text": button.get("body")} 21 | if button.get("footer"): 22 | data["footer"] = {"text": button.get("footer")} 23 | if button.get("type"): 24 | data["type"] = button.get("type") 25 | return data 26 | 27 | 28 | async def send_button( 29 | self, button: Dict[Any, Any], recipient_id: str, sender=None 30 | ) -> asyncio.Future: 31 | """ 32 | Sends an interactive buttons message to a WhatsApp user 33 | 34 | Args: 35 | button[dict]: A dictionary containing the button data(rows-title may not exceed 20 characters) 36 | recipient_id[str]: Phone number of the user with country code wihout + 37 | 38 | check https://github.com/Neurotech-HQ/whatsapp#sending-interactive-reply-buttons for an example. 39 | """ 40 | try: 41 | sender = dict(self.l)[sender] 42 | 43 | except: 44 | sender = self.phone_number_id 45 | 46 | if sender == None: 47 | sender = self.phone_number_id 48 | 49 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 50 | data = { 51 | "messaging_product": "whatsapp", 52 | "to": recipient_id, 53 | "type": "interactive", 54 | "interactive": self.create_button(button), 55 | } 56 | logging.info(f"Sending buttons to {recipient_id}") 57 | 58 | async def call(): 59 | async with aiohttp.ClientSession() as session: 60 | async with session.post(url, headers=self.headers, json=data) as r: 61 | if r.status == 200: 62 | logging.info(f"Buttons sent to {recipient_id}") 63 | return await r.json() 64 | logging.info(f"Buttons not sent to {recipient_id}") 65 | logging.info(f"Status code: {r.status}") 66 | logging.info(f"Response: {await r.json()}") 67 | return await r.json() 68 | 69 | f = asyncio.ensure_future(call()) 70 | await asyncio.sleep(0.001) # make asyncio run the task 71 | return f 72 | 73 | 74 | async def send_reply_button( 75 | self, button: Dict[Any, Any], recipient_id: str, sender=None 76 | ) -> asyncio.Future: 77 | """ 78 | Sends an interactive reply buttons[menu] message to a WhatsApp user 79 | 80 | Args: 81 | button[dict]: A dictionary containing the button data 82 | recipient_id[str]: Phone number of the user with country code wihout + 83 | 84 | Note: 85 | The maximum number of buttons is 3, more than 3 buttons will rise an error. 86 | """ 87 | try: 88 | sender = dict(self.l)[sender] 89 | 90 | except: 91 | sender = self.phone_number_id 92 | 93 | if sender == None: 94 | sender = self.phone_number_id 95 | 96 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 97 | if len(button["action"]["buttons"]) > 3: 98 | raise ValueError("The maximum number of buttons is 3.") 99 | 100 | data = { 101 | "messaging_product": "whatsapp", 102 | "recipient_type": "individual", 103 | "to": recipient_id, 104 | "type": "interactive", 105 | "interactive": button, 106 | } 107 | logging.info(f"Sending buttons to {recipient_id}") 108 | 109 | async def call(): 110 | async with aiohttp.ClientSession() as session: 111 | async with session.post(url, headers=self.headers, json=data) as r: 112 | if r.status == 200: 113 | logging.info(f"Buttons sent to {recipient_id}") 114 | return await r.json() 115 | logging.info(f"Buttons not sent to {recipient_id}") 116 | logging.info(f"Status code: {r.status}") 117 | logging.info(f"Response: {await r.json()}") 118 | return await r.json() 119 | 120 | f = asyncio.ensure_future(call()) 121 | await asyncio.sleep(0.001) # make asyncio run the task 122 | return f 123 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_media.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import aiohttp 3 | import requests 4 | import asyncio 5 | import os 6 | import mimetypes 7 | from requests_toolbelt.multipart.encoder import MultipartEncoder 8 | from typing import Union, Dict, Any 9 | 10 | 11 | async def upload_media(self, media: str, sender=None) -> Union[Dict[str, Any], None]: 12 | """ 13 | Uploads a media to the cloud api and returns the id of the media 14 | 15 | Args: 16 | media[str]: Path of the media to be uploaded 17 | 18 | Example: 19 | >>> from whatsapp import WhatsApp 20 | >>> whatsapp = WhatsApp(token, phone_number_id) 21 | >>> whatsapp.upload_media("/path/to/media") 22 | 23 | REFERENCE: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media# 24 | """ 25 | try: 26 | sender = dict(self.l)[sender] 27 | 28 | except: 29 | sender = self.phone_number_id 30 | 31 | if sender == None: 32 | sender = self.phone_number_id 33 | 34 | form_data = { 35 | "file": ( 36 | media, 37 | open(os.path.realpath(media), "rb"), 38 | mimetypes.guess_type(media)[0], 39 | ), 40 | "messaging_product": "whatsapp", 41 | "type": mimetypes.guess_type(media)[0], 42 | } 43 | form_data = MultipartEncoder(fields=form_data) 44 | headers = self.headers.copy() 45 | headers["Content-Type"] = form_data.content_type 46 | logging.info(f"Content-Type: {form_data.content_type}") 47 | logging.info(f"Uploading media {media}") 48 | r = requests.post( 49 | f"{self.base_url}/{sender}/media", 50 | headers=headers, 51 | data=form_data, 52 | ) 53 | if r.status_code == 200: 54 | logging.info(f"Media {media} uploaded") 55 | return r.json() 56 | logging.info(f"Error uploading media {media}") 57 | logging.info(f"Status code: {r.status_code}") 58 | logging.debug(f"Response: {r.json()}") # Changed to debug level 59 | return r.status_code 60 | 61 | 62 | async def delete_media(self, media_id: str) -> asyncio.Future: 63 | """ 64 | Deletes a media from the cloud api 65 | 66 | Args: 67 | media_id[str]: Id of the media to be deleted 68 | """ 69 | logging.info(f"Deleting media {media_id}") 70 | 71 | async def call(): 72 | async with aiohttp.ClientSession() as session: 73 | async with session.delete( 74 | f"https://graph.facebook.com/{self.LATEST}/{media_id}", 75 | headers=self.headers, 76 | ) as r: 77 | if r.status == 200: 78 | logging.info(f"Media {media_id} deleted") 79 | return await r.json() 80 | logging.info(f"Error deleting media {media_id}") 81 | logging.info(f"Status code: {r.status}") 82 | logging.info(f"Response: {await r.json()}") 83 | return await r.json() 84 | 85 | f = asyncio.ensure_future(call()) 86 | await asyncio.sleep(0.001) # make asyncio run the task 87 | return f 88 | 89 | 90 | async def query_media_url(self, media_id: str) -> asyncio.Future: 91 | """ 92 | Query media url from media id obtained either by manually uploading media or received media 93 | 94 | Args: 95 | media_id[str]: Media id of the media 96 | 97 | Returns: 98 | str: Media url 99 | 100 | Example: 101 | >>> from whatsapp import WhatsApp 102 | >>> whatsapp = WhatsApp(token, phone_number_id) 103 | >>> whatsapp.query_media_url("media_id") 104 | """ 105 | 106 | logging.info(f"Querying media url for {media_id}") 107 | 108 | async def call(): 109 | async with aiohttp.ClientSession() as session: 110 | async with session.get( 111 | f"https://graph.facebook.com/{self.LATEST}/{media_id}", 112 | headers=self.headers, 113 | ) as r: 114 | if r.status == 200: 115 | logging.info(f"Media url for {media_id} queried") 116 | return await r.json() 117 | logging.info(f"Error querying media url for {media_id}") 118 | logging.info(f"Status code: {r.status}") 119 | logging.info(f"Response: {await r.json()}") 120 | return await r.json() 121 | 122 | f = asyncio.ensure_future(call()) 123 | await asyncio.sleep(0.001) # make asyncio run the task 124 | return f 125 | 126 | 127 | async def download_media( 128 | self, media_url: str, mime_type: str, file_path: str = "temp" 129 | ) -> asyncio.Future: 130 | """ 131 | Download media from media url obtained either by manually uploading media or received media 132 | 133 | Args: 134 | media_url[str]: Media url of the media 135 | mime_type[str]: Mime type of the media 136 | file_path[str]: Path of the file to be downloaded to. Default is "temp" 137 | Do not include the file extension. It will be added automatically. 138 | 139 | Returns: 140 | str: Media url 141 | 142 | Example: 143 | >>> from whatsapp import WhatsApp 144 | >>> whatsapp = WhatsApp(token, phone_number_id) 145 | >>> whatsapp.download_media("media_url", "image/jpeg") 146 | >>> whatsapp.download_media("media_url", "video/mp4", "path/to/file") #do not include the file extension 147 | """ 148 | logging.info(f"Downloading media from {media_url}") 149 | 150 | async def call(): 151 | async with aiohttp.ClientSession() as session: 152 | async with session.get(media_url, headers=self.headers) as r: 153 | if r.status == 200: 154 | logging.info(f"Media downloaded from {media_url}") 155 | extension = mime_type.split("/")[1] 156 | save_file_here = ( 157 | f"{file_path}.{extension}" if file_path else f"temp.{extension}" 158 | ) 159 | with open(save_file_here, "wb") as f: 160 | f.write(await r.read()) 161 | return save_file_here 162 | logging.info(f"Error downloading media from {media_url}") 163 | logging.info(f"Status code: {r.status}") 164 | logging.info(f"Response: {await r.json()}") 165 | return await r.json() 166 | 167 | f = asyncio.ensure_future(call()) 168 | await asyncio.sleep(0.001) # make asyncio run the task 169 | return f 170 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_message.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import aiohttp 3 | import asyncio 4 | 5 | 6 | async def react(self, emoji: str) -> asyncio.Future: 7 | data = { 8 | "messaging_product": "whatsapp", 9 | "recipient_type": "individual", 10 | "to": self.sender, 11 | "type": "reaction", 12 | "reaction": {"message_id": self.id, "emoji": emoji}, 13 | } 14 | logging.info(f"Reacting to {self.id}") 15 | 16 | async def call(): 17 | async with aiohttp.ClientSession() as session: 18 | async with session.post(self.url, headers=self.headers, json=data) as r: 19 | if r.status == 200: 20 | logging.info(f"Reacted to {self.id}") 21 | return await r.json() 22 | logging.info(f"Reaction not sent to {self.id}") 23 | logging.info(f"Status code: {r.status}") 24 | logging.info(f"Response: {await r.json()}") 25 | return await r.json() 26 | 27 | f = asyncio.ensure_future(call()) 28 | await asyncio.sleep(0.001) # make asyncio run the task 29 | return f 30 | 31 | 32 | async def send_template( 33 | self, 34 | template: str, 35 | recipient_id: str, 36 | components: str = None, 37 | lang: str = "en_US", 38 | sender=None, 39 | ) -> asyncio.Future: 40 | """ 41 | Sends a template message to a WhatsApp user, Template messages can either be; 42 | 1. Text template 43 | 2. Media based template 44 | 3. Interactive template 45 | You can customize the template message by passing a dictionary of components. 46 | You can find the available components in the documentation. 47 | https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates 48 | Args: 49 | template[str]: Template name to be sent to the user 50 | recipient_id[str]: Phone number of the user with country code wihout + 51 | lang[str]: Language of the template message 52 | components[list]: List of components to be sent to the user # \ 53 | Example: 54 | >>> from whatsapp import WhatsApp 55 | >>> whatsapp = WhatsApp(token, phone_number_id) 56 | >>> whatsapp.send_template("hello_world", "5511999999999", lang="en_US")) 57 | """ 58 | try: 59 | sender = dict(self.l)[sender] 60 | 61 | except: 62 | sender = self.phone_number_id 63 | 64 | if sender == None: 65 | sender = self.phone_number_id 66 | 67 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 68 | data = { 69 | "messaging_product": "whatsapp", 70 | "to": recipient_id, 71 | "type": "template", 72 | "template": { 73 | "name": template, 74 | "language": {"code": lang}, 75 | "components": components, 76 | }, 77 | } 78 | logging.info(f"Sending template to {recipient_id}") 79 | 80 | async def call(): 81 | async with aiohttp.ClientSession() as session: 82 | async with session.post(url, headers=self.headers, json=data) as r: 83 | if r.status == 200: 84 | logging.info(f"Template sent to {recipient_id}") 85 | return await r.json() 86 | logging.info(f"Template not sent to {recipient_id}") 87 | logging.info(f"Status code: {r.status}") 88 | logging.info(f"Response: {await r.json()}") 89 | return await r.json() 90 | 91 | f = asyncio.ensure_future(call()) 92 | await asyncio.sleep(0.001) # make asyncio run the task 93 | return f 94 | 95 | 96 | # MESSAGE() 97 | 98 | 99 | async def reply(self, reply_text: str = "", preview_url: bool = True) -> asyncio.Future: 100 | if self.data == {}: 101 | return {"error": "No data provided"} 102 | author = self.instance.get_author(self.data) 103 | payload = { 104 | "messaging_product": "whatsapp", 105 | "recipient_type": "individual", 106 | "to": str(author), 107 | "type": "text", 108 | "context": {"message_id": self.id}, 109 | "text": {"preview_url": preview_url, "body": reply_text}, 110 | } 111 | logging.info(f"Replying to {self.id}") 112 | 113 | async def call(): 114 | async with aiohttp.ClientSession() as session: 115 | async with session.post(self.url, headers=self.headers, json=payload) as r: 116 | if r.status == 200: 117 | logging.info(f"Replied to {self.id}") 118 | return await r.json() 119 | logging.info(f"Reply not sent to {self.id}") 120 | logging.info(f"Status code: {r.status}") 121 | logging.info(f"Response: {await r.json()}") 122 | return await r.json() 123 | 124 | f = asyncio.ensure_future(call()) 125 | await asyncio.sleep(0.001) # make asyncio run the task 126 | return f 127 | 128 | 129 | async def mark_as_read(self) -> asyncio.Future: 130 | payload = { 131 | "messaging_product": "whatsapp", 132 | "status": "read", 133 | "message_id": self.id, 134 | } 135 | 136 | logging.info(f"Marking message {self.id} as read") 137 | 138 | async def call(): 139 | async with aiohttp.ClientSession() as session: 140 | async with session.post(self.url, headers=self.headers, json=payload) as r: 141 | if r.status == 200: 142 | logging.info(f"Message {self.id} marked as read") 143 | return await r.json() 144 | logging.info(f"Error marking message {self.id} as read") 145 | logging.info(f"Status code: {r.status}") 146 | logging.info(f"Response: {await r.json()}") 147 | return await r.json() 148 | 149 | f = asyncio.ensure_future(call()) 150 | await asyncio.sleep(0.001) # make asyncio run the task 151 | return f 152 | 153 | 154 | async def send(self, preview_url: bool = True) -> asyncio.Future: 155 | url = f"https://graph.facebook.com/{self.LATEST}/{self.sender}/messages" 156 | data = { 157 | "messaging_product": "whatsapp", 158 | "recipient_type": self.rec, 159 | "to": self.to, 160 | "type": "text", 161 | "text": {"preview_url": preview_url, "body": self.content}, 162 | } 163 | logging.info(f"Sending message to {self.to}") 164 | 165 | async def call(): 166 | async with aiohttp.ClientSession() as session: 167 | async with session.post(url, headers=self.headers, json=data) as r: 168 | if r.status == 200: 169 | logging.info(f"Message sent to {self.to}") 170 | return await r.json() 171 | logging.info(f"Message not sent to {self.to}") 172 | logging.info(f"Status code: {r.status}") 173 | logging.info(f"Response: {await r.json()}") 174 | return await r.json() 175 | 176 | f = asyncio.ensure_future(call()) 177 | await asyncio.sleep(0.001) # make asyncio run the task 178 | return f 179 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_property.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | def authorized(self) -> bool: 5 | return requests.get(self.url, headers=self.headers).status_code != 401 6 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_send_media.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import aiohttp 3 | import asyncio 4 | 5 | 6 | async def send_location( 7 | self, lat: str, long: str, name: str, address: str, recipient_id: str, sender=None 8 | ) -> asyncio.Future: 9 | """ 10 | Sends a location message to a WhatsApp user 11 | 12 | Args: 13 | lat[str]: Latitude of the location 14 | long[str]: Longitude of the location 15 | name[str]: Name of the location 16 | address[str]: Address of the location 17 | recipient_id[str]: Phone number of the user with country code wihout + 18 | 19 | Example: 20 | >>> from whatsapp import WhatsApp 21 | >>> whatsapp = WhatsApp(token, phone_number_id) 22 | >>> whatsapp.send_location("-23.564", "-46.654", "My Location", "Rua dois, 123", "5511999999999") 23 | """ 24 | try: 25 | sender = dict(self.l)[sender] 26 | 27 | except: 28 | sender = self.phone_number_id 29 | 30 | if sender == None: 31 | sender = self.phone_number_id 32 | 33 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 34 | data = { 35 | "messaging_product": "whatsapp", 36 | "to": recipient_id, 37 | "type": "location", 38 | "location": { 39 | "latitude": lat, 40 | "longitude": long, 41 | "name": name, 42 | "address": address, 43 | }, 44 | } 45 | logging.info(f"Sending location to {recipient_id}") 46 | 47 | async def call(): 48 | async with aiohttp.ClientSession() as session: 49 | async with session.post(url, headers=self.headers, json=data) as r: 50 | if r.status == 200: 51 | logging.info(f"Location sent to {recipient_id}") 52 | return await r.json() 53 | logging.info(f"Location not sent to {recipient_id}") 54 | logging.info(f"Status code: {r.status}") 55 | logging.info(f"Response: {await r.json()}") 56 | return await r.json() 57 | 58 | f = asyncio.ensure_future(call()) 59 | await asyncio.sleep(0.001) # make asyncio run the task 60 | return f 61 | 62 | 63 | async def send_image( 64 | self, 65 | image: str, 66 | recipient_id: str, 67 | recipient_type: str = "individual", 68 | caption: str = "", 69 | link: bool = True, 70 | sender=None, 71 | ) -> asyncio.Future: 72 | """ 73 | Sends an image message to a WhatsApp user 74 | 75 | There are two ways to send an image message to a user, either by passing the image id or by passing the image link. 76 | Image id is the id of the image uploaded to the cloud api. 77 | 78 | Args: 79 | image[str]: Image id or link of the image 80 | recipient_id[str]: Phone number of the user with country code wihout + 81 | recipient_type[str]: Type of the recipient, either individual or group 82 | caption[str]: Caption of the image 83 | link[bool]: Whether to send an image id or an image link, True means that the image is an id, False means that the image is a link 84 | 85 | 86 | Example: 87 | >>> from whatsapp import WhatsApp 88 | >>> whatsapp = WhatsApp(token, phone_number_id) 89 | >>> whatsapp.send_image("https://i.imgur.com/Fh7XVYY.jpeg", "5511999999999") 90 | """ 91 | try: 92 | sender = dict(self.l)[sender] 93 | 94 | except: 95 | sender = self.phone_number_id 96 | 97 | if sender == None: 98 | sender = self.phone_number_id 99 | 100 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 101 | if link: 102 | data = { 103 | "messaging_product": "whatsapp", 104 | "recipient_type": recipient_type, 105 | "to": recipient_id, 106 | "type": "image", 107 | "image": {"link": image, "caption": caption}, 108 | } 109 | else: 110 | data = { 111 | "messaging_product": "whatsapp", 112 | "recipient_type": recipient_type, 113 | "to": recipient_id, 114 | "type": "image", 115 | "image": {"id": image, "caption": caption}, 116 | } 117 | logging.info(f"Sending image to {recipient_id}") 118 | 119 | async def call(): 120 | async with aiohttp.ClientSession() as session: 121 | async with session.post(url, headers=self.headers, json=data) as r: 122 | if r.status == 200: 123 | logging.info(f"Image sent to {recipient_id}") 124 | return await r.json() 125 | logging.info(f"Image not sent to {recipient_id}") 126 | logging.info(f"Status code: {r.status}") 127 | logging.info(f"Response: {await r.json()}") 128 | return await r.json() 129 | 130 | f = asyncio.ensure_future(call()) 131 | await asyncio.sleep(0.001) # make asyncio run the task 132 | return f 133 | 134 | 135 | async def send_sticker( 136 | self, 137 | sticker: str, 138 | recipient_id: str, 139 | recipient_type: str = "individual", 140 | link: bool = True, 141 | sender=None, 142 | ) -> asyncio.Future: 143 | """ 144 | Sends a sticker message to a WhatsApp user 145 | 146 | There are two ways to send a sticker message to a user, either by passing the image id or by passing the sticker link. 147 | Sticker id is the id of the sticker uploaded to the cloud api. 148 | 149 | Args: 150 | sticker[str]: Sticker id or link of the sticker 151 | recipient_id[str]: Phone number of the user with country code wihout + 152 | recipient_type[str]: Type of the recipient, either individual or group 153 | link[bool]: Whether to send an sticker id or an sticker link, True means that the sticker is an id, False means that the image is a link 154 | 155 | 156 | Example: 157 | >>> from whatsapp import WhatsApp 158 | >>> whatsapp = WhatsApp(token, phone_number_id) 159 | >>> whatsapp.send_sticker("170511049062862", "5511999999999", link=False) 160 | """ 161 | try: 162 | sender = dict(self.l)[sender] 163 | 164 | except: 165 | sender = self.phone_number_id 166 | 167 | if sender == None: 168 | sender = self.phone_number_id 169 | 170 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 171 | if link: 172 | data = { 173 | "messaging_product": "whatsapp", 174 | "recipient_type": recipient_type, 175 | "to": recipient_id, 176 | "type": "sticker", 177 | "sticker": {"link": sticker}, 178 | } 179 | else: 180 | data = { 181 | "messaging_product": "whatsapp", 182 | "recipient_type": recipient_type, 183 | "to": recipient_id, 184 | "type": "sticker", 185 | "sticker": {"id": sticker}, 186 | } 187 | logging.info(f"Sending sticker to {recipient_id}") 188 | 189 | async def call(): 190 | async with aiohttp.ClientSession() as session: 191 | async with session.post(url, headers=self.headers, json=data) as r: 192 | if r.status == 200: 193 | logging.info(f"Sticker sent to {recipient_id}") 194 | return await r.json() 195 | logging.info(f"Sticker not sent to {recipient_id}") 196 | logging.info(f"Status code: {r.status}") 197 | logging.info(f"Response: {await r.json()}") 198 | return await r.json() 199 | 200 | f = asyncio.ensure_future(call()) 201 | await asyncio.sleep(0.001) # make asyncio run the task 202 | return f 203 | 204 | 205 | async def send_audio( 206 | self, audio: str, recipient_id: str, link: bool = True, sender=None 207 | ) -> asyncio.Future: 208 | """ 209 | Sends an audio message to a WhatsApp user 210 | Audio messages can either be sent by passing the audio id or by passing the audio link. 211 | 212 | Args: 213 | audio[str]: Audio id or link of the audio 214 | recipient_id[str]: Phone number of the user with country code wihout + 215 | link[bool]: Whether to send an audio id or an audio link, True means that the audio is an id, False means that the audio is a link 216 | 217 | Example: 218 | >>> from whatsapp import WhatsApp 219 | >>> whatsapp = WhatsApp(token, phone_number_id) 220 | >>> whatsapp.send_audio("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", "5511999999999") 221 | """ 222 | try: 223 | sender = dict(self.l)[sender] 224 | 225 | except: 226 | sender = self.phone_number_id 227 | 228 | if sender == None: 229 | sender = self.phone_number_id 230 | 231 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 232 | if link: 233 | data = { 234 | "messaging_product": "whatsapp", 235 | "to": recipient_id, 236 | "type": "audio", 237 | "audio": {"link": audio}, 238 | } 239 | else: 240 | data = { 241 | "messaging_product": "whatsapp", 242 | "to": recipient_id, 243 | "type": "audio", 244 | "audio": {"id": audio}, 245 | } 246 | logging.info(f"Sending audio to {recipient_id}") 247 | 248 | async def call(): 249 | async with aiohttp.ClientSession() as session: 250 | async with session.post(url, headers=self.headers, json=data) as r: 251 | if r.status == 200: 252 | logging.info(f"Audio sent to {recipient_id}") 253 | return await r.json() 254 | logging.info(f"Audio not sent to {recipient_id}") 255 | logging.info(f"Status code: {r.status}") 256 | logging.info(f"Response: {await r.json()}") 257 | return await r.json() 258 | 259 | f = asyncio.ensure_future(call()) 260 | await asyncio.sleep(0.001) # make asyncio run the task 261 | return f 262 | 263 | 264 | async def send_video( 265 | self, 266 | video: str, 267 | recipient_id: str, 268 | caption: str = "", 269 | link: bool = True, 270 | sender=None, 271 | ) -> asyncio.Future: 272 | """ " 273 | Sends a video message to a WhatsApp user 274 | Video messages can either be sent by passing the video id or by passing the video link. 275 | 276 | Args: 277 | video[str]: Video id or link of the video 278 | recipient_id[str]: Phone number of the user with country code wihout + 279 | caption[str]: Caption of the video 280 | link[bool]: Whether to send a video id or a video link, True means that the video is an id, False means that the video is a link 281 | 282 | example: 283 | >>> from whatsapp import WhatsApp 284 | >>> whatsapp = WhatsApp(token, phone_number_id) 285 | >>> whatsapp.send_video("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "5511999999999") 286 | """ 287 | try: 288 | sender = dict(self.l)[sender] 289 | 290 | except: 291 | sender = self.phone_number_id 292 | 293 | if sender == None: 294 | sender = self.phone_number_id 295 | 296 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 297 | if link: 298 | data = { 299 | "messaging_product": "whatsapp", 300 | "to": recipient_id, 301 | "type": "video", 302 | "video": {"link": video, "caption": caption}, 303 | } 304 | else: 305 | data = { 306 | "messaging_product": "whatsapp", 307 | "to": recipient_id, 308 | "type": "video", 309 | "video": {"id": video, "caption": caption}, 310 | } 311 | logging.info(f"Sending video to {recipient_id}") 312 | 313 | async def call(): 314 | async with aiohttp.ClientSession() as session: 315 | async with session.post(url, headers=self.headers, json=data) as r: 316 | if r.status == 200: 317 | logging.info(f"Video sent to {recipient_id}") 318 | return await r.json() 319 | logging.info(f"Video not sent to {recipient_id}") 320 | logging.info(f"Status code: {r.status}") 321 | logging.info(f"Response: {await r.json()}") 322 | return await r.json() 323 | 324 | f = asyncio.ensure_future(call()) 325 | await asyncio.sleep(0.001) # make asyncio run the task 326 | return f 327 | 328 | 329 | async def send_document( 330 | self, 331 | document: str, 332 | recipient_id: str, 333 | caption: str = "", 334 | link: bool = True, 335 | sender=None, 336 | ) -> asyncio.Future: 337 | """ " 338 | Sends a document message to a WhatsApp user 339 | Document messages can either be sent by passing the document id or by passing the document link. 340 | 341 | Args: 342 | document[str]: Document id or link of the document 343 | recipient_id[str]: Phone number of the user with country code wihout + 344 | caption[str]: Caption of the document 345 | link[bool]: Whether to send a document id or a document link, True means that the document is an id, False means that the document is a link 346 | 347 | Example: 348 | >>> from whatsapp import WhatsApp 349 | >>> whatsapp = WhatsApp(token, phone_number_id) 350 | >>> whatsapp.send_document("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", "5511999999999") 351 | """ 352 | try: 353 | sender = dict(self.l)[sender] 354 | 355 | except: 356 | sender = self.phone_number_id 357 | 358 | if sender == None: 359 | sender = self.phone_number_id 360 | 361 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 362 | if link: 363 | data = { 364 | "messaging_product": "whatsapp", 365 | "to": recipient_id, 366 | "type": "document", 367 | "document": {"link": document, "caption": caption}, 368 | } 369 | else: 370 | data = { 371 | "messaging_product": "whatsapp", 372 | "to": recipient_id, 373 | "type": "document", 374 | "document": {"id": document, "caption": caption}, 375 | } 376 | 377 | logging.info(f"Sending document to {recipient_id}") 378 | 379 | async def call(): 380 | async with aiohttp.ClientSession() as session: 381 | async with session.post(url, headers=self.headers, json=data) as r: 382 | if r.status == 200: 383 | logging.info(f"Document sent to {recipient_id}") 384 | return await r.json() 385 | logging.info(f"Document not sent to {recipient_id}") 386 | logging.info(f"Status code: {r.status}") 387 | logging.info(f"Response: {await r.json()}") 388 | return await r.json() 389 | 390 | f = asyncio.ensure_future(call()) 391 | await asyncio.sleep(0.001) # make asyncio run the task 392 | return f 393 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_send_others.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, List 2 | import aiohttp 3 | import asyncio 4 | import logging 5 | 6 | 7 | async def send_custom_json( 8 | self, data: dict, recipient_id: str = "", sender=None 9 | ) -> asyncio.Future: 10 | """ 11 | Sends a custom json to a WhatsApp user. This can be used to send custom objects to the message endpoint. 12 | 13 | Args: 14 | data[dict]: Dictionary that should be send 15 | recipient_id[str]: Phone number of the user with country code wihout + 16 | Example: 17 | >>> from whatsapp import WhatsApp 18 | >>> whatsapp = WhatsApp(token, phone_number_id) 19 | >>> whatsapp.send_custom_json({ 20 | "messaging_product": "whatsapp", 21 | "type": "audio", 22 | "audio": {"id": audio}}, "5511999999999") 23 | """ 24 | try: 25 | sender = dict(self.l)[sender] 26 | 27 | except: 28 | sender = self.phone_number_id 29 | 30 | if sender == None: 31 | sender = self.phone_number_id 32 | 33 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 34 | 35 | if recipient_id: 36 | if "to" in data.keys(): 37 | data_recipient_id = data["to"] 38 | logging.info( 39 | f"Recipient Id is defined in data ({data_recipient_id}) and recipient_id parameter ({recipient_id})" 40 | ) 41 | else: 42 | data["to"] = recipient_id 43 | 44 | logging.info(f"Sending custom json to {recipient_id}") 45 | 46 | async def call(): 47 | async with aiohttp.ClientSession() as session: 48 | async with session.post(url, headers=self.headers, json=data) as r: 49 | if r.status == 200: 50 | logging.info(f"Custom json sent to {recipient_id}") 51 | return await r.json() 52 | logging.info(f"Custom json not sent to {recipient_id}") 53 | logging.info(f"Status code: {r.status}") 54 | logging.info(f"Response: {await r.json()}") 55 | return await r.json() 56 | 57 | f = asyncio.ensure_future(call()) 58 | await asyncio.sleep(0.001) # make asyncio run the task 59 | return f 60 | 61 | 62 | async def send_contacts( 63 | self, contacts: List[Dict[Any, Any]], recipient_id: str, sender=None 64 | ) -> asyncio.Future: 65 | """send_contacts 66 | 67 | Send a list of contacts to a user 68 | 69 | Args: 70 | contacts(List[Dict[Any, Any]]): List of contacts to send 71 | recipient_id(str): Phone number of the user with country code wihout + 72 | 73 | Example: 74 | >>> from whatsapp import WhatsApp 75 | >>> whatsapp = WhatsApp(token, phone_number_id) 76 | >>> contacts = [{ 77 | "addresses": [{ 78 | "street": "STREET", 79 | "city": "CITY", 80 | "state": "STATE", 81 | "zip": "ZIP", 82 | "country": "COUNTRY", 83 | "country_code": "COUNTRY_CODE", 84 | "type": "HOME" 85 | }, 86 | .... 87 | } 88 | ] 89 | 90 | REFERENCE: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#contacts-object 91 | """ 92 | try: 93 | sender = dict(self.l)[sender] 94 | 95 | except: 96 | sender = self.phone_number_id 97 | 98 | if sender == None: 99 | sender = self.phone_number_id 100 | 101 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 102 | 103 | data = { 104 | "messaging_product": "whatsapp", 105 | "to": recipient_id, 106 | "type": "contacts", 107 | "contacts": contacts, 108 | } 109 | logging.info(f"Sending contacts to {recipient_id}") 110 | 111 | async def call(): 112 | async with aiohttp.ClientSession() as session: 113 | async with session.post(url, headers=self.headers, json=data) as r: 114 | if r.status == 200: 115 | logging.info(f"Contacts sent to {recipient_id}") 116 | return await r.json() 117 | logging.info(f"Contacts not sent to {recipient_id}") 118 | logging.info(f"Status code: {r.status}") 119 | logging.info(f"Response: {await r.json()}") 120 | return await r.json() 121 | 122 | f = asyncio.ensure_future(call()) 123 | await asyncio.sleep(0.001) # make asyncio run the task 124 | return f 125 | -------------------------------------------------------------------------------- /whatsapp/async_ext/_static.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, Union 2 | 3 | 4 | @staticmethod 5 | def is_message(data: Dict[Any, Any]) -> bool: 6 | """is_message checks if the data received from the webhook is a message. 7 | 8 | Args: 9 | data (Dict[Any, Any]): The data received from the webhook 10 | 11 | Returns: 12 | bool: True if the data is a message, False otherwise 13 | """ 14 | data = data["entry"][0]["changes"][0]["value"] 15 | if "messages" in data: 16 | return True 17 | else: 18 | return False 19 | 20 | 21 | @staticmethod 22 | def get_mobile(data: Dict[Any, Any]) -> Union[str, None]: 23 | """ 24 | Extracts the mobile number of the sender from the data received from the webhook. 25 | 26 | Args: 27 | data[dict]: The data received from the webhook 28 | Returns: 29 | str: The mobile number of the sender 30 | 31 | Example: 32 | >>> from whatsapp import WhatsApp 33 | >>> whatsapp = WhatsApp(token, phone_number_id) 34 | >>> mobile = whatsapp.get_mobile(data) 35 | """ 36 | data = data["entry"][0]["changes"][0]["value"] 37 | if "contacts" in data: 38 | return data["contacts"][0]["wa_id"] 39 | 40 | 41 | @staticmethod 42 | def get_name(data: Dict[Any, Any]) -> Union[str, None]: 43 | """ 44 | Extracts the name of the sender from the data received from the webhook. 45 | 46 | Args: 47 | data[dict]: The data received from the webhook 48 | Returns: 49 | str: The name of the sender 50 | Example: 51 | >>> from whatsapp import WhatsApp 52 | >>> whatsapp = WhatsApp(token, phone_number_id) 53 | >>> mobile = whatsapp.get_name(data) 54 | """ 55 | contact = data["entry"][0]["changes"][0]["value"] 56 | if contact: 57 | return contact["contacts"][0]["profile"]["name"] 58 | 59 | 60 | @staticmethod 61 | def get_message(data: Dict[Any, Any]) -> Union[str, None]: 62 | """ 63 | Extracts the text message of the sender from the data received from the webhook. 64 | 65 | Args: 66 | data[dict]: The data received from the webhook 67 | Returns: 68 | str: The text message received from the sender 69 | Example: 70 | >>> from whatsapp import WhatsApp 71 | >>> whatsapp = WhatsApp(token, phone_number_id) 72 | >>> message = message.get_message(data) 73 | """ 74 | data = data["entry"][0]["changes"][0]["value"] 75 | if "messages" in data: 76 | return data["messages"][0]["text"]["body"] 77 | 78 | 79 | @staticmethod 80 | def get_message_id(data: Dict[Any, Any]) -> Union[str, None]: 81 | """ 82 | Extracts the message id of the sender from the data received from the webhook. 83 | 84 | Args: 85 | data[dict]: The data received from the webhook 86 | Returns: 87 | str: The message id of the sender 88 | Example: 89 | >>> from whatsapp import WhatsApp 90 | >>> whatsapp = WhatsApp(token, phone_number_id) 91 | >>> message_id = whatsapp.get_message_id(data) 92 | """ 93 | data = data["entry"][0]["changes"][0]["value"] 94 | if "messages" in data: 95 | return data["messages"][0]["id"] 96 | 97 | 98 | @staticmethod 99 | def get_message_timestamp(data: Dict[Any, Any]) -> Union[str, None]: 100 | """ " 101 | Extracts the timestamp of the message from the data received from the webhook. 102 | 103 | Args: 104 | data[dict]: The data received from the webhook 105 | Returns: 106 | str: The timestamp of the message 107 | Example: 108 | >>> from whatsapp import WhatsApp 109 | >>> whatsapp = WhatsApp(token, phone_number_id) 110 | >>> whatsapp.get_message_timestamp(data) 111 | """ 112 | data = data["entry"][0]["changes"][0]["value"] 113 | if "messages" in data: 114 | return data["messages"][0]["timestamp"] 115 | 116 | 117 | @staticmethod 118 | def get_interactive_response(data: Dict[Any, Any]) -> Union[Dict, None]: 119 | """ 120 | Extracts the response of the interactive message from the data received from the webhook. 121 | 122 | Args: 123 | data[dict]: The data received from the webhook 124 | Returns: 125 | dict: The response of the interactive message 126 | 127 | Example: 128 | >>> from whatsapp import WhatsApp 129 | >>> whatsapp = WhatsApp(token, phone_number_id) 130 | >>> response = whatsapp.get_interactive_response(data) 131 | >>> interactive_type = response.get("type") 132 | >>> message_id = response[interactive_type]["id"] 133 | >>> message_text = response[interactive_type]["title"] 134 | """ 135 | data = data["entry"][0]["changes"][0]["value"] 136 | if "messages" in data: 137 | if "interactive" in data["messages"][0]: 138 | return data["messages"][0]["interactive"] 139 | 140 | 141 | @staticmethod 142 | def get_location(data: Dict[Any, Any]) -> Union[Dict, None]: 143 | """ 144 | Extracts the location of the sender from the data received from the webhook. 145 | 146 | Args: 147 | data[dict]: The data received from the webhook 148 | 149 | Returns: 150 | dict: The location of the sender 151 | 152 | Example: 153 | >>> from whatsapp import WhatsApp 154 | >>> whatsapp = WhatsApp(token, phone_number_id) 155 | >>> whatsapp.get_location(data) 156 | """ 157 | data = data["entry"][0]["changes"][0]["value"] 158 | if "messages" in data: 159 | if "location" in data["messages"][0]: 160 | return data["messages"][0]["location"] 161 | 162 | 163 | @staticmethod 164 | def get_image(data: Dict[Any, Any]) -> Union[Dict, None]: 165 | """ " 166 | Extracts the image of the sender from the data received from the webhook. 167 | 168 | Args: 169 | data[dict]: The data received from the webhook 170 | Returns: 171 | dict: The image_id of an image sent by the sender 172 | 173 | Example: 174 | >>> from whatsapp import WhatsApp 175 | >>> whatsapp = WhatsApp(token, phone_number_id) 176 | >>> image_id = whatsapp.get_image(data) 177 | """ 178 | data = data["entry"][0]["changes"][0]["value"] 179 | if "messages" in data: 180 | if "image" in data["messages"][0]: 181 | return data["messages"][0]["image"] 182 | 183 | 184 | @staticmethod 185 | def get_sticker(data: Dict[Any, Any]) -> Union[Dict, None]: 186 | """ " 187 | Extracts the sticker of the sender from the data received from the webhook. 188 | 189 | Args: 190 | data[dict]: The data received from the webhook 191 | Returns: 192 | dict: The sticker_id of an sticker sent by the sender 193 | 194 | Example: 195 | >>> from whatsapp import WhatsApp 196 | >>> whatsapp = WhatsApp(token, phone_number_id) 197 | >>> sticker_id = whatsapp.get_sticker(data) 198 | """ 199 | data = data["entry"][0]["changes"][0]["value"] 200 | if "messages" in data: 201 | if "sticker" in data["messages"][0]: 202 | return data["messages"][0]["sticker"] 203 | 204 | 205 | @staticmethod 206 | def get_document(data: Dict[Any, Any]) -> Union[Dict, None]: 207 | """ " 208 | Extracts the document of the sender from the data received from the webhook. 209 | 210 | Args: 211 | data[dict]: The data received from the webhook 212 | Returns: 213 | dict: The document_id of an image sent by the sender 214 | 215 | Example: 216 | >>> from whatsapp import WhatsApp 217 | >>> whatsapp = WhatsApp(token, phone_number_id) 218 | >>> document_id = whatsapp.get_document(data) 219 | """ 220 | data = data["entry"][0]["changes"][0]["value"] 221 | if "messages" in data: 222 | if "document" in data["messages"][0]: 223 | return data["messages"][0]["document"] 224 | 225 | 226 | @staticmethod 227 | def get_audio(data: Dict[Any, Any]) -> Union[Dict, None]: 228 | """ 229 | Extracts the audio of the sender from the data received from the webhook. 230 | 231 | Args: 232 | data[dict]: The data received from the webhook 233 | 234 | Returns: 235 | dict: The audio of the sender 236 | 237 | Example: 238 | >>> from whatsapp import WhatsApp 239 | >>> whatsapp = WhatsApp(token, phone_number_id) 240 | >>> whatsapp.get_audio(data) 241 | """ 242 | data = data["entry"][0]["changes"][0]["value"] 243 | if "messages" in data: 244 | if "audio" in data["messages"][0]: 245 | return data["messages"][0]["audio"] 246 | 247 | 248 | @staticmethod 249 | def get_video(data: Dict[Any, Any]) -> Union[Dict, None]: 250 | """ 251 | Extracts the video of the sender from the data received from the webhook. 252 | 253 | Args: 254 | data[dict]: The data received from the webhook 255 | 256 | Returns: 257 | dict: Dictionary containing the video details sent by the sender 258 | 259 | Example: 260 | >>> from whatsapp import WhatsApp 261 | >>> whatsapp = WhatsApp(token, phone_number_id) 262 | >>> whatsapp.get_video(data) 263 | """ 264 | data = data["entry"][0]["changes"][0]["value"] 265 | if "messages" in data: 266 | if "video" in data["messages"][0]: 267 | return data["messages"][0]["video"] 268 | 269 | 270 | @staticmethod 271 | def get_message_type(data: Dict[Any, Any]) -> Union[str, None]: 272 | """ 273 | Gets the type of the message sent by the sender from the data received from the webhook. 274 | 275 | 276 | Args: 277 | data [dict]: The data received from the webhook 278 | 279 | Returns: 280 | str: The type of the message sent by the sender 281 | 282 | Example: 283 | >>> from whatsapp import WhatsApp 284 | >>> whatsapp = WhatsApp(token, phone_number_id) 285 | >>> whatsapp.get_message_type(data) 286 | """ 287 | data = data["entry"][0]["changes"][0]["value"] 288 | if "messages" in data: 289 | return data["messages"][0]["type"] 290 | 291 | 292 | @staticmethod 293 | def get_delivery(data: Dict[Any, Any]) -> Union[Dict, None]: 294 | """ 295 | Extracts the delivery status of the message from the data received from the webhook. 296 | Args: 297 | data [dict]: The data received from the webhook 298 | 299 | Returns: 300 | dict: The delivery status of the message and message id of the message 301 | """ 302 | data = data["entry"][0]["changes"][0]["value"] 303 | if "statuses" in data: 304 | return data["statuses"][0]["status"] 305 | 306 | 307 | @staticmethod 308 | def changed_field(data: Dict[Any, Any]) -> str: 309 | """ 310 | Helper function to check if the field changed in the data received from the webhook. 311 | 312 | Args: 313 | data [dict]: The data received from the webhook 314 | 315 | Returns: 316 | str: The field changed in the data received from the webhook 317 | 318 | Example: 319 | >>> from whatsapp import WhatsApp 320 | >>> whatsapp = WhatsApp(token, phone_number_id) 321 | >>> whatsapp.changed_field(data) 322 | """ 323 | return data["entry"][0]["changes"][0]["field"] 324 | 325 | 326 | @staticmethod 327 | def get_author(data: Dict[Any, Any]) -> Union[str, None]: 328 | try: 329 | return data["entry"][0]["changes"][0]["value"]["messages"][0]["from"] 330 | except Exception: 331 | return None 332 | -------------------------------------------------------------------------------- /whatsapp/constants.py: -------------------------------------------------------------------------------- 1 | # This file contains the constants used in the project. 2 | # The VERSION constant is used to store the version of the project - it's not only used in the __init__.py file, but also in the pyproject.toml file. 3 | 4 | VERSION = "4.3.0" 5 | -------------------------------------------------------------------------------- /whatsapp/errors.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | 4 | class Handler: 5 | def __init__(self, error: dict): 6 | self.error = error 7 | 8 | 9 | class AuthException(Exception): # invoked by code 0 10 | pass 11 | 12 | 13 | class MethodException(AuthException): # invoked by code 3 14 | pass 15 | 16 | 17 | class ForbiddenException(AuthException): # invoked by codes 10, 200-299 18 | pass 19 | 20 | 21 | class ExpiredTokenException(AuthException): # invoked by code 190 22 | pass 23 | 24 | 25 | class ThrottlingException(Exception): # Category exception 26 | pass 27 | 28 | 29 | class RateLimitException(ThrottlingException): # invoked by code 4 30 | pass 31 | 32 | 33 | class UserRateLimitException(ThrottlingException): # invoked by code 80007 34 | pass 35 | 36 | 37 | class AppRateLimitException(ThrottlingException): # invoked by code 130429 38 | pass 39 | 40 | 41 | class SpamException(ThrottlingException): # invoked by code 131048 42 | pass 43 | 44 | 45 | class CoupleRateLimitException(ThrottlingException): # invoked by code 131056 46 | pass 47 | 48 | 49 | class RegistrationRateLimitException(ThrottlingException): # invoked by code 133016 50 | pass 51 | 52 | 53 | class IntegrityException(Exception): # Category exception 54 | pass 55 | 56 | 57 | class RulesViolationException(IntegrityException): # invoked by code 368 58 | pass 59 | 60 | 61 | class GeoRestrictionException(IntegrityException): # invoked by code 130497 62 | pass 63 | 64 | 65 | class BlockedAccountException(IntegrityException): # invoked by code 131031 66 | pass 67 | 68 | 69 | # Generic exceptions 70 | class UnknownAPIException(Exception): # invoked by code 1 71 | pass 72 | 73 | 74 | class ServiceUnavailableException(Exception): # invoked by code 2 75 | pass 76 | 77 | 78 | class WrongPhoneNumberException(Exception): # invoked by code 33 79 | pass 80 | 81 | 82 | class InvalidParameterException(Exception): # invoked by code 100 83 | pass 84 | 85 | 86 | class ExperimentalNumberException(Exception): # invoked by code 130472 87 | pass 88 | 89 | 90 | class UnknownErrorException(Exception): # invoked by code 131000 91 | pass 92 | 93 | 94 | class AccessDeniedException(Exception): # invoked by code 131005 95 | pass 96 | 97 | 98 | class RequiredParameterMissingException(Exception): # invoked by code 131008 99 | pass 100 | 101 | 102 | class InvalidParameterTypeException(Exception): # invoked by code 131009 103 | pass 104 | 105 | 106 | class ServiceUnavailableException(Exception): # invoked by code 131016 107 | pass 108 | 109 | 110 | class SamePhoneNumberException(Exception): # invoked by code 131021 111 | pass 112 | 113 | 114 | class DeliveryFailureException(Exception): # invoked by code 131026 115 | pass 116 | 117 | 118 | class PaymentFailureException(Exception): # invoked by code 131042 119 | pass 120 | 121 | 122 | class PhoneRegistrationFailureException(Exception): # invoked by code 131045 123 | pass 124 | 125 | 126 | class ChatExpiredException(Exception): # invoked by code 131047 127 | pass 128 | 129 | 130 | class MetaDeliveryFailureException(Exception): # invoked by code 131049 131 | pass 132 | 133 | 134 | class UnsupportedMessageTypeException(Exception): # invoked by code 131051 135 | pass 136 | 137 | 138 | class MediaDownloadFailureException(Exception): # invoked by code 131052 139 | pass 140 | 141 | 142 | class MediaLoadFailureException(Exception): # invoked by code 131053 143 | pass 144 | 145 | 146 | class MaintenanceException(Exception): # invoked by code 131057 147 | pass 148 | 149 | 150 | class ParameterNumberMismatchException(Exception): # invoked by code 132000 151 | pass 152 | 153 | 154 | class ModelNotFoundException(Exception): # invoked by code 132001 155 | pass 156 | 157 | 158 | class TextTooLongException(Exception): # invoked by code 132005 159 | pass 160 | 161 | 162 | class CharacterFormatException(Exception): # invoked by code 132007 163 | pass 164 | 165 | 166 | class WrongParameterFormatException(Exception): # invoked by code 132012 167 | pass 168 | 169 | 170 | class PausedTemplateException(Exception): # invoked by code 132015 171 | pass 172 | 173 | 174 | class DisabledTemplateException(Exception): # invoked by code 132016 175 | pass 176 | 177 | 178 | class StreamBlockedException(Exception): # invoked by code 132068 179 | pass 180 | 181 | 182 | class StreamThrottlingException(Exception): # invoked by code 132069 183 | pass 184 | 185 | 186 | class FailedToRevertRegistrationException(Exception): # invoked by code 133000 187 | pass 188 | 189 | 190 | class ServerTemporaryUnavailableException(Exception): # invoked by code 133004 191 | pass 192 | 193 | 194 | class MFAPinIncorrectException(Exception): # invoked by code 133005 195 | pass 196 | 197 | 198 | class PhoneVerificationRequiredException(Exception): # invoked by code 133006 199 | pass 200 | 201 | 202 | class TooManyPinAttemptsException(Exception): # invoked by code 133008 203 | pass 204 | 205 | 206 | class TooFastPinAttemptsException(Exception): # invoked by code 133009 207 | pass 208 | 209 | 210 | class UnregisteredNumberException(Exception): # invoked by code 133010 211 | pass 212 | 213 | 214 | class RetryLaterException(Exception): # invoked by code 133015 215 | pass 216 | 217 | 218 | class GenericUserException(Exception): # invoked by code 135000 219 | pass 220 | 221 | 222 | pairings = { 223 | 0: AuthException, 224 | 1: UnknownAPIException, 225 | 2: ServiceUnavailableException, 226 | 3: MethodException, 227 | 4: RateLimitException, 228 | 10: ForbiddenException, 229 | 33: WrongPhoneNumberException, 230 | 100: InvalidParameterException, 231 | 200: ForbiddenException, 232 | 130429: AppRateLimitException, 233 | 130472: ExperimentalNumberException, 234 | 130497: GeoRestrictionException, 235 | 131000: UnknownErrorException, 236 | 131005: AccessDeniedException, 237 | 131008: RequiredParameterMissingException, 238 | 131009: InvalidParameterTypeException, 239 | 131016: ServiceUnavailableException, 240 | 131021: SamePhoneNumberException, 241 | 131026: DeliveryFailureException, 242 | 131042: PaymentFailureException, 243 | 131045: PhoneRegistrationFailureException, 244 | 131047: ChatExpiredException, 245 | 131048: SpamException, 246 | 131049: MetaDeliveryFailureException, 247 | 131051: UnsupportedMessageTypeException, 248 | 131052: MediaDownloadFailureException, 249 | 131053: MediaLoadFailureException, 250 | 131056: CoupleRateLimitException, 251 | 131057: MaintenanceException, 252 | 132000: ParameterNumberMismatchException, 253 | 132001: ModelNotFoundException, 254 | 132005: TextTooLongException, 255 | 132007: CharacterFormatException, 256 | 132012: WrongParameterFormatException, 257 | 132015: PausedTemplateException, 258 | 132016: DisabledTemplateException, 259 | 132068: StreamBlockedException, 260 | 132069: StreamThrottlingException, 261 | 133000: FailedToRevertRegistrationException, 262 | 133004: ServerTemporaryUnavailableException, 263 | 133005: MFAPinIncorrectException, 264 | 133006: PhoneVerificationRequiredException, 265 | 133008: TooManyPinAttemptsException, 266 | 133009: TooFastPinAttemptsException, 267 | 133010: UnregisteredNumberException, 268 | 133015: RetryLaterException, 269 | 80007: UserRateLimitException, 270 | 131031: BlockedAccountException, 271 | 131056: CoupleRateLimitException, 272 | 131057: MaintenanceException, 273 | 133016: RegistrationRateLimitException, 274 | 368: RulesViolationException, 275 | 190: ExpiredTokenException, 276 | } 277 | 278 | 279 | class Handle: 280 | def __init__(self, data: dict) -> Union[Exception, None]: 281 | try: 282 | code = data["error"]["code"] 283 | if code in pairings: 284 | raise pairings[code]({"error": data["error"]["message"], "code": code}) 285 | else: 286 | if code in range(200, 300): 287 | raise ForbiddenException({"error": data["error"]["message"], "code": code}) 288 | raise Handler(Exception({"error": data["error"]["message"], "code": code})) 289 | except KeyError: 290 | return None -------------------------------------------------------------------------------- /whatsapp/ext/_buttons.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from typing import Dict, Any 4 | from ..errors import Handle 5 | 6 | 7 | def create_button(self, button: Dict[Any, Any]) -> Dict[Any, Any]: 8 | """ 9 | Method to create a button object to be used in the send_message method. 10 | 11 | This is method is designed to only be used internally by the send_button method. 12 | 13 | Args: 14 | button[dict]: A dictionary containing the button data 15 | """ 16 | data = {"type": "list", "action": button.get("action")} 17 | if button.get("header"): 18 | data["header"] = {"type": "text", "text": button.get("header")} 19 | if button.get("body"): 20 | data["body"] = {"text": button.get("body")} 21 | if button.get("footer"): 22 | data["footer"] = {"text": button.get("footer")} 23 | if button.get("type"): 24 | data["type"] = button.get("type") 25 | return data 26 | 27 | 28 | def send_button( 29 | self, button: Dict[Any, Any], recipient_id: str, sender=None 30 | ) -> Dict[Any, Any]: 31 | """ 32 | Sends an interactive buttons message to a WhatsApp user 33 | 34 | Args: 35 | button[dict]: A dictionary containing the button data(rows-title may not exceed 20 characters) 36 | recipient_id[str]: Phone number of the user with country code wihout + 37 | 38 | check https://github.com/Neurotech-HQ/whatsapp#sending-interactive-reply-buttons for an example. 39 | """ 40 | try: 41 | sender = dict(self.l)[sender] 42 | 43 | except: 44 | sender = self.phone_number_id 45 | 46 | if sender == None: 47 | sender = self.phone_number_id 48 | 49 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 50 | data = { 51 | "messaging_product": "whatsapp", 52 | "to": recipient_id, 53 | "type": "interactive", 54 | "interactive": self.create_button(button), 55 | } 56 | logging.info(f"Sending buttons to {recipient_id}") 57 | r = requests.post(url, headers=self.headers, json=data) 58 | if r.status_code == 200: 59 | logging.info(f"Buttons sent to {recipient_id}") 60 | return r.json() 61 | logging.info(f"Buttons not sent to {recipient_id}") 62 | logging.info(f"Status code: {r.status_code}") 63 | logging.info(f"Response: {r.json()}") 64 | return Handle(r.json()) 65 | 66 | 67 | def send_reply_button( 68 | self, button: Dict[Any, Any], recipient_id: str, sender=None 69 | ) -> Dict[Any, Any]: 70 | """ 71 | Sends an interactive reply buttons[menu] message to a WhatsApp user 72 | 73 | Args: 74 | button[dict]: A dictionary containing the button data 75 | recipient_id[str]: Phone number of the user with country code wihout + 76 | 77 | Note: 78 | The maximum number of buttons is 3, more than 3 buttons will rise an error. 79 | """ 80 | try: 81 | sender = dict(self.l)[sender] 82 | 83 | except: 84 | sender = self.phone_number_id 85 | 86 | if sender == None: 87 | sender = self.phone_number_id 88 | 89 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 90 | if len(button["action"]["buttons"]) > 3: 91 | raise ValueError("The maximum number of buttons is 3.") 92 | 93 | data = { 94 | "messaging_product": "whatsapp", 95 | "recipient_type": "individual", 96 | "to": recipient_id, 97 | "type": "interactive", 98 | "interactive": button, 99 | } 100 | r = requests.post(url, headers=self.headers, json=data) 101 | if r.status_code == 200: 102 | logging.info(f"Reply buttons sent to {recipient_id}") 103 | return r.json() 104 | logging.info(f"Reply buttons not sent to {recipient_id}") 105 | logging.info(f"Status code: {r.status_code}") 106 | logging.info(f"Response: {r.json()}") 107 | return Handle(r.json()) 108 | -------------------------------------------------------------------------------- /whatsapp/ext/_media.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import os 4 | import mimetypes 5 | from requests_toolbelt.multipart.encoder import MultipartEncoder 6 | from typing import Union, Dict, Any 7 | from ..errors import Handle 8 | 9 | 10 | def upload_media(self, media: str, sender=None) -> Union[Dict[Any, Any], None]: 11 | """ 12 | Uploads a media to the cloud api and returns the id of the media 13 | 14 | Args: 15 | media[str]: Path of the media to be uploaded 16 | 17 | Example: 18 | >>> from whatsapp import WhatsApp 19 | >>> whatsapp = WhatsApp(token, phone_number_id) 20 | >>> whatsapp.upload_media("/path/to/media") 21 | 22 | REFERENCE: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media# 23 | """ 24 | try: 25 | sender = dict(self.l)[sender] 26 | 27 | except: 28 | sender = self.phone_number_id 29 | 30 | if sender == None: 31 | sender = self.phone_number_id 32 | 33 | form_data = { 34 | "file": ( 35 | media, 36 | open(os.path.realpath(media), "rb"), 37 | mimetypes.guess_type(media)[0], 38 | ), 39 | "messaging_product": "whatsapp", 40 | "type": mimetypes.guess_type(media)[0], 41 | } 42 | form_data = MultipartEncoder(fields=form_data) 43 | headers = self.headers.copy() 44 | headers["Content-Type"] = form_data.content_type 45 | logging.info(f"Content-Type: {form_data.content_type}") 46 | logging.info(f"Uploading media {media}") 47 | r = requests.post( 48 | f"{self.base_url}/{sender}/media", 49 | headers=headers, 50 | data=form_data, 51 | ) 52 | if r.status_code == 200: 53 | logging.info(f"Media {media} uploaded") 54 | return r.json() 55 | logging.info(f"Error uploading media {media}") 56 | logging.info(f"Status code: {r.status_code}") 57 | logging.debug(f"Response: {r.json()}") # Changed to debug level 58 | return Handle(r.json()) 59 | 60 | 61 | def delete_media(self, media_id: str) -> Union[Dict[Any, Any], None]: 62 | """ 63 | Deletes a media from the cloud api 64 | 65 | Args: 66 | media_id[str]: Id of the media to be deleted 67 | """ 68 | logging.info(f"Deleting media {media_id}") 69 | r = requests.delete(f"{self.base_url}/{media_id}", headers=self.headers) 70 | if r.status_code == 200: 71 | logging.info(f"Media {media_id} deleted") 72 | return r.json() 73 | logging.info(f"Error deleting media {media_id}") 74 | logging.info(f"Status code: {r.status_code}") 75 | logging.debug(f"Response: {r.json()}") # Changed to debug level 76 | return Handle(r.json()) 77 | 78 | 79 | def query_media_url(self, media_id: str) -> Union[str, None]: 80 | """ 81 | Query media url from media id obtained either by manually uploading media or received media 82 | 83 | Args: 84 | media_id[str]: Media id of the media 85 | 86 | Returns: 87 | str: Media url 88 | 89 | Example: 90 | >>> from whatsapp import WhatsApp 91 | >>> whatsapp = WhatsApp(token, phone_number_id) 92 | >>> whatsapp.query_media_url("media_id") 93 | """ 94 | 95 | logging.info(f"Querying media url for {media_id}") 96 | r = requests.get(f"{self.base_url}/{media_id}", headers=self.headers) 97 | if r.status_code == 200: 98 | logging.info(f"Media url queried for {media_id}") 99 | return r.json()["url"] 100 | logging.info(f"Media url not queried for {media_id}") 101 | logging.info(f"Status code: {r.status_code}") 102 | logging.debug(f"Response: {r.json()}") # Changed to debug level 103 | return Handle(r.json()) 104 | 105 | 106 | def download_media( 107 | self, media_url: str, mime_type: str, file_path: str = "temp" 108 | ) -> Union[str, None]: 109 | """ 110 | Download media from media url obtained either by manually uploading media or received media 111 | 112 | Args: 113 | media_url[str]: Media url of the media 114 | mime_type[str]: Mime type of the media 115 | file_path[str]: Path of the file to be downloaded to. Default is "temp" 116 | Do not include the file extension. It will be added automatically. 117 | 118 | Returns: 119 | str: Media url 120 | 121 | Example: 122 | >>> from whatsapp import WhatsApp 123 | >>> whatsapp = WhatsApp(token, phone_number_id) 124 | >>> whatsapp.download_media("media_url", "image/jpeg") 125 | >>> whatsapp.download_media("media_url", "video/mp4", "path/to/file") #do not include the file extension 126 | """ 127 | r = requests.get(media_url, headers=self.headers) 128 | if r.status_code != 200: 129 | logging.error(f"Error downloading media from {media_url}") 130 | logging.error(f"Status code: {r.status_code}") 131 | logging.error(f"Response: {r.json()}") 132 | return Handle(r.json()) 133 | content = r.content 134 | extension = mime_type.split("/")[1] 135 | save_file_here = None 136 | # create a temporary file 137 | try: 138 | 139 | save_file_here = ( 140 | f"{file_path}.{extension}" if file_path else f"temp.{extension}" 141 | ) 142 | with open(save_file_here, "wb") as f: 143 | f.write(content) 144 | logging.info(f"Media downloaded to {save_file_here}") 145 | return f.name 146 | except Exception as e: 147 | logging.info(e) 148 | logging.error(f"Error downloading media to {save_file_here}") 149 | return None 150 | -------------------------------------------------------------------------------- /whatsapp/ext/_message.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from ..errors import Handle 4 | 5 | 6 | def react(self, emoji: str) -> dict: 7 | data = { 8 | "messaging_product": "whatsapp", 9 | "recipient_type": "individual", 10 | "to": self.sender, 11 | "type": "reaction", 12 | "reaction": {"message_id": self.id, "emoji": emoji}, 13 | } 14 | logging.info(f"Reacting to {self.id}") 15 | r = requests.post(self.url, headers=self.headers, json=data) 16 | if r.status_code == 200: 17 | logging.info(f"Reaction sent to {self.to}") 18 | return r.json() 19 | logging.info(f"Reaction not sent to {self.to}") 20 | logging.info(f"Status code: {r.status_code}") 21 | logging.debug(f"Response: {r.json()}") 22 | return Handle(r.json()) 23 | 24 | 25 | def send_template( 26 | self, 27 | template: str, 28 | recipient_id: str, 29 | components: str = None, 30 | lang: str = "en_US", 31 | sender=None, 32 | ) -> dict: 33 | """ 34 | Sends a template message to a WhatsApp user, Template messages can either be; 35 | 1. Text template 36 | 2. Media based template 37 | 3. Interactive template 38 | You can customize the template message by passing a dictionary of components. 39 | You can find the available components in the documentation. 40 | https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates 41 | Args: 42 | template[str]: Template name to be sent to the user 43 | recipient_id[str]: Phone number of the user with country code wihout + 44 | lang[str]: Language of the template message 45 | components[list]: List of components to be sent to the user # \ 46 | Example: 47 | >>> from whatsapp import WhatsApp 48 | >>> whatsapp = WhatsApp(token, phone_number_id) 49 | >>> whatsapp.send_template("hello_world", "5511999999999", lang="en_US")) 50 | """ 51 | try: 52 | sender = dict(self.l)[sender] 53 | 54 | except: 55 | sender = self.phone_number_id 56 | 57 | if sender == None: 58 | sender = self.phone_number_id 59 | 60 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 61 | data = { 62 | "messaging_product": "whatsapp", 63 | "to": recipient_id, 64 | "type": "template", 65 | "template": { 66 | "name": template, 67 | "language": {"code": lang}, 68 | "components": components, 69 | }, 70 | } 71 | logging.info(f"Sending template to {recipient_id}") 72 | r = requests.post(url, headers=self.headers, json=data) 73 | if r.status_code == 200: 74 | logging.info(f"Template sent to {recipient_id}") 75 | return r.json() 76 | logging.info(f"Template not sent to {recipient_id}") 77 | logging.info(f"Status code: {r.status_code}") 78 | logging.error(f"Response: {r.json()}") 79 | return Handle(r.json()) 80 | 81 | 82 | # MESSAGE() 83 | 84 | 85 | def reply(self, reply_text: str = "", preview_url: bool = True) -> dict: 86 | if self.data == {}: 87 | return {"error": "No data provided"} 88 | author = self.instance.get_author(self.data) 89 | payload = { 90 | "messaging_product": "whatsapp", 91 | "recipient_type": "individual", 92 | "to": str(author), 93 | "type": "text", 94 | "context": {"message_id": self.id}, 95 | "text": {"preview_url": preview_url, "body": reply_text}, 96 | } 97 | logging.info(f"Replying to {self.id}") 98 | r = requests.post(self.url, headers=self.headers, json=payload) 99 | if r.status_code == 200: 100 | logging.info(f"Message sent to {self.instance.get_author(self.data)}") 101 | return r.json() 102 | logging.info(f"Message not sent to {self.instance.get_author(self.data)}") 103 | logging.info(f"Status code: {r.status_code}") 104 | logging.error(f"Response: {r.json()}") 105 | return Handle(r.json()) 106 | 107 | 108 | def mark_as_read(self) -> dict: 109 | payload = { 110 | "messaging_product": "whatsapp", 111 | "status": "read", 112 | "message_id": self.id, 113 | } 114 | 115 | response = requests.post( 116 | f"{self.instance.url}", headers=self.instance.headers, json=payload 117 | ) 118 | if response.status_code == 200: 119 | logging.info(response.json()) 120 | return response.json() 121 | else: 122 | logging.error(response.json()) 123 | return Handle(response.json()) 124 | 125 | 126 | def send(self, preview_url: bool = True) -> dict: 127 | url = f"https://graph.facebook.com/{self.LATEST}/{self.sender}/messages" 128 | data = { 129 | "messaging_product": "whatsapp", 130 | "recipient_type": self.rec, 131 | "to": self.to, 132 | "type": "text", 133 | "text": {"preview_url": preview_url, "body": self.content}, 134 | } 135 | logging.info(f"Sending message to {self.to}") 136 | r = requests.post(url, headers=self.headers, json=data) 137 | if r.status_code == 200: 138 | logging.info(f"Message sent to {self.to}") 139 | return r.json() 140 | logging.info(f"Message not sent to {self.to}") 141 | logging.info(f"Status code: {r.status_code}") 142 | logging.error(f"Response fddfscsad: {r.json()}") 143 | return Handle(r.json()) 144 | -------------------------------------------------------------------------------- /whatsapp/ext/_property.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | def authorized(self) -> bool: 5 | return requests.get(self.url, headers=self.headers).status_code != 401 6 | -------------------------------------------------------------------------------- /whatsapp/ext/_send_media.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | from ..errors import Handle 4 | 5 | 6 | def send_location( 7 | self, lat: str, long: str, name: str, address: str, recipient_id: str, sender=None 8 | ) -> dict: 9 | """ 10 | Sends a location message to a WhatsApp user 11 | 12 | Args: 13 | lat[str]: Latitude of the location 14 | long[str]: Longitude of the location 15 | name[str]: Name of the location 16 | address[str]: Address of the location 17 | recipient_id[str]: Phone number of the user with country code wihout + 18 | 19 | Example: 20 | >>> from whatsapp import WhatsApp 21 | >>> whatsapp = WhatsApp(token, phone_number_id) 22 | >>> whatsapp.send_location("-23.564", "-46.654", "My Location", "Rua dois, 123", "5511999999999") 23 | """ 24 | try: 25 | sender = dict(self.l)[sender] 26 | 27 | except: 28 | sender = self.phone_number_id 29 | 30 | if sender == None: 31 | sender = self.phone_number_id 32 | 33 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 34 | data = { 35 | "messaging_product": "whatsapp", 36 | "to": recipient_id, 37 | "type": "location", 38 | "location": { 39 | "latitude": lat, 40 | "longitude": long, 41 | "name": name, 42 | "address": address, 43 | }, 44 | } 45 | logging.info(f"Sending location to {recipient_id}") 46 | r = requests.post(url, headers=self.headers, json=data) 47 | if r.status_code == 200: 48 | logging.info(f"Location sent to {recipient_id}") 49 | return r.json() 50 | logging.info(f"Location not sent to {recipient_id}") 51 | logging.info(f"Status code: {r.status_code}") 52 | logging.error(r.json()) 53 | return Handle(r.json()) 54 | 55 | 56 | def send_image( 57 | self, 58 | image: str, 59 | recipient_id: str, 60 | recipient_type: str = "individual", 61 | caption: str = "", 62 | link: bool = True, 63 | sender=None, 64 | ) -> dict: 65 | """ 66 | Sends an image message to a WhatsApp user 67 | 68 | There are two ways to send an image message to a user, either by passing the image id or by passing the image link. 69 | Image id is the id of the image uploaded to the cloud api. 70 | 71 | Args: 72 | image[str]: Image id or link of the image 73 | recipient_id[str]: Phone number of the user with country code wihout + 74 | recipient_type[str]: Type of the recipient, either individual or group 75 | caption[str]: Caption of the image 76 | link[bool]: Whether to send an image id or an image link, True means that the image is an id, False means that the image is a link 77 | 78 | 79 | Example: 80 | >>> from whatsapp import WhatsApp 81 | >>> whatsapp = WhatsApp(token, phone_number_id) 82 | >>> whatsapp.send_image("https://i.imgur.com/Fh7XVYY.jpeg", "5511999999999") 83 | """ 84 | try: 85 | sender = dict(self.l)[sender] 86 | 87 | except: 88 | sender = self.phone_number_id 89 | 90 | if sender == None: 91 | sender = self.phone_number_id 92 | 93 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 94 | if link: 95 | data = { 96 | "messaging_product": "whatsapp", 97 | "recipient_type": recipient_type, 98 | "to": recipient_id, 99 | "type": "image", 100 | "image": {"link": image, "caption": caption}, 101 | } 102 | else: 103 | data = { 104 | "messaging_product": "whatsapp", 105 | "recipient_type": recipient_type, 106 | "to": recipient_id, 107 | "type": "image", 108 | "image": {"id": image, "caption": caption}, 109 | } 110 | logging.info(f"Sending image to {recipient_id}") 111 | r = requests.post(url, headers=self.headers, json=data) 112 | if r.status_code == 200: 113 | logging.info(f"Image sent to {recipient_id}") 114 | return r.json() 115 | logging.info(f"Image not sent to {recipient_id}") 116 | logging.info(f"Status code: {r.status_code}") 117 | logging.error(r.json()) 118 | return Handle(r.json()) 119 | 120 | 121 | def send_sticker( 122 | self, 123 | sticker: str, 124 | recipient_id: str, 125 | recipient_type: str = "individual", 126 | link: bool = True, 127 | sender=None, 128 | ) -> dict: 129 | """ 130 | Sends a sticker message to a WhatsApp user 131 | 132 | There are two ways to send a sticker message to a user, either by passing the image id or by passing the sticker link. 133 | Sticker id is the id of the sticker uploaded to the cloud api. 134 | 135 | Args: 136 | sticker[str]: Sticker id or link of the sticker 137 | recipient_id[str]: Phone number of the user with country code wihout + 138 | recipient_type[str]: Type of the recipient, either individual or group 139 | link[bool]: Whether to send an sticker id or an sticker link, True means that the sticker is an id, False means that the image is a link 140 | 141 | 142 | Example: 143 | >>> from whatsapp import WhatsApp 144 | >>> whatsapp = WhatsApp(token, phone_number_id) 145 | >>> whatsapp.send_sticker("170511049062862", "5511999999999", link=False) 146 | """ 147 | try: 148 | sender = dict(self.l)[sender] 149 | 150 | except: 151 | sender = self.phone_number_id 152 | 153 | if sender == None: 154 | sender = self.phone_number_id 155 | 156 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 157 | if link: 158 | data = { 159 | "messaging_product": "whatsapp", 160 | "recipient_type": recipient_type, 161 | "to": recipient_id, 162 | "type": "sticker", 163 | "sticker": {"link": sticker}, 164 | } 165 | else: 166 | data = { 167 | "messaging_product": "whatsapp", 168 | "recipient_type": recipient_type, 169 | "to": recipient_id, 170 | "type": "sticker", 171 | "sticker": {"id": sticker}, 172 | } 173 | logging.info(f"Sending sticker to {recipient_id}") 174 | r = requests.post(url, headers=self.headers, json=data) 175 | if r.status_code == 200: 176 | logging.info(f"Sticker sent to {recipient_id}") 177 | return r.json() 178 | logging.info(f"Sticker not sent to {recipient_id}") 179 | logging.info(f"Status code: {r.status_code}") 180 | logging.error(r.json()) 181 | return Handle(r.json()) 182 | 183 | 184 | def send_audio( 185 | self, audio: str, recipient_id: str, link: bool = True, sender=None 186 | ) -> dict: 187 | """ 188 | Sends an audio message to a WhatsApp user 189 | Audio messages can either be sent by passing the audio id or by passing the audio link. 190 | 191 | Args: 192 | audio[str]: Audio id or link of the audio 193 | recipient_id[str]: Phone number of the user with country code wihout + 194 | link[bool]: Whether to send an audio id or an audio link, True means that the audio is an id, False means that the audio is a link 195 | 196 | Example: 197 | >>> from whatsapp import WhatsApp 198 | >>> whatsapp = WhatsApp(token, phone_number_id) 199 | >>> whatsapp.send_audio("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3", "5511999999999") 200 | """ 201 | try: 202 | sender = dict(self.l)[sender] 203 | 204 | except: 205 | sender = self.phone_number_id 206 | 207 | if sender == None: 208 | sender = self.phone_number_id 209 | 210 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 211 | if link: 212 | data = { 213 | "messaging_product": "whatsapp", 214 | "to": recipient_id, 215 | "type": "audio", 216 | "audio": {"link": audio}, 217 | } 218 | else: 219 | data = { 220 | "messaging_product": "whatsapp", 221 | "to": recipient_id, 222 | "type": "audio", 223 | "audio": {"id": audio}, 224 | } 225 | logging.info(f"Sending audio to {recipient_id}") 226 | r = requests.post(url, headers=self.headers, json=data) 227 | if r.status_code == 200: 228 | logging.info(f"Audio sent to {recipient_id}") 229 | return r.json() 230 | logging.info(f"Audio not sent to {recipient_id}") 231 | logging.info(f"Status code: {r.status_code}") 232 | logging.error(f"Response: {r.json()}") 233 | return Handle(r.json()) 234 | 235 | 236 | def send_video( 237 | self, 238 | video: str, 239 | recipient_id: str, 240 | caption: str = "", 241 | link: bool = True, 242 | sender=None, 243 | ) -> dict: 244 | """ " 245 | Sends a video message to a WhatsApp user 246 | Video messages can either be sent by passing the video id or by passing the video link. 247 | 248 | Args: 249 | video[str]: Video id or link of the video 250 | recipient_id[str]: Phone number of the user with country code wihout + 251 | caption[str]: Caption of the video 252 | link[bool]: Whether to send a video id or a video link, True means that the video is an id, False means that the video is a link 253 | 254 | example: 255 | >>> from whatsapp import WhatsApp 256 | >>> whatsapp = WhatsApp(token, phone_number_id) 257 | >>> whatsapp.send_video("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "5511999999999") 258 | """ 259 | try: 260 | sender = dict(self.l)[sender] 261 | 262 | except: 263 | sender = self.phone_number_id 264 | 265 | if sender == None: 266 | sender = self.phone_number_id 267 | 268 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 269 | if link: 270 | data = { 271 | "messaging_product": "whatsapp", 272 | "to": recipient_id, 273 | "type": "video", 274 | "video": {"link": video, "caption": caption}, 275 | } 276 | else: 277 | data = { 278 | "messaging_product": "whatsapp", 279 | "to": recipient_id, 280 | "type": "video", 281 | "video": {"id": video, "caption": caption}, 282 | } 283 | logging.info(f"Sending video to {recipient_id}") 284 | r = requests.post(url, headers=self.headers, json=data) 285 | if r.status_code == 200: 286 | logging.info(f"Video sent to {recipient_id}") 287 | return r.json() 288 | logging.info(f"Video not sent to {recipient_id}") 289 | logging.info(f"Status code: {r.status_code}") 290 | logging.error(f"Response: {r.json()}") 291 | return Handle(r.json()) 292 | 293 | 294 | def send_document( 295 | self, 296 | document: str, 297 | recipient_id: str, 298 | caption: str = "", 299 | link: bool = True, 300 | sender=None, 301 | ) -> dict: 302 | """ " 303 | Sends a document message to a WhatsApp user 304 | Document messages can either be sent by passing the document id or by passing the document link. 305 | 306 | Args: 307 | document[str]: Document id or link of the document 308 | recipient_id[str]: Phone number of the user with country code wihout + 309 | caption[str]: Caption of the document 310 | link[bool]: Whether to send a document id or a document link, True means that the document is an id, False means that the document is a link 311 | 312 | Example: 313 | >>> from whatsapp import WhatsApp 314 | >>> whatsapp = WhatsApp(token, phone_number_id) 315 | >>> whatsapp.send_document("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf", "5511999999999") 316 | """ 317 | try: 318 | sender = dict(self.l)[sender] 319 | 320 | except: 321 | sender = self.phone_number_id 322 | 323 | if sender == None: 324 | sender = self.phone_number_id 325 | 326 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 327 | if link: 328 | data = { 329 | "messaging_product": "whatsapp", 330 | "to": recipient_id, 331 | "type": "document", 332 | "document": {"link": document, "caption": caption}, 333 | } 334 | else: 335 | data = { 336 | "messaging_product": "whatsapp", 337 | "to": recipient_id, 338 | "type": "document", 339 | "document": {"id": document, "caption": caption}, 340 | } 341 | 342 | logging.info(f"Sending document to {recipient_id}") 343 | r = requests.post(url, headers=self.headers, json=data) 344 | if r.status_code == 200: 345 | logging.info(f"Document sent to {recipient_id}") 346 | return r.json() 347 | logging.info(f"Document not sent to {recipient_id}") 348 | logging.info(f"Status code: {r.status_code}") 349 | logging.error(f"Response: {r.json()}") 350 | return Handle(r.json()) 351 | -------------------------------------------------------------------------------- /whatsapp/ext/_send_others.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, List 2 | import requests 3 | import logging 4 | from ..errors import Handle 5 | 6 | 7 | def send_custom_json(self, data: dict, recipient_id: str = "", sender=None): 8 | """ 9 | Sends a custom json to a WhatsApp user. This can be used to send custom objects to the message endpoint. 10 | 11 | Args: 12 | data[dict]: Dictionary that should be send 13 | recipient_id[str]: Phone number of the user with country code wihout + 14 | Example: 15 | >>> from whatsapp import WhatsApp 16 | >>> whatsapp = WhatsApp(token, phone_number_id) 17 | >>> whatsapp.send_custom_json({ 18 | "messaging_product": "whatsapp", 19 | "type": "audio", 20 | "audio": {"id": audio}}, "5511999999999") 21 | """ 22 | try: 23 | sender = dict(self.l)[sender] 24 | 25 | except: 26 | sender = self.phone_number_id 27 | 28 | if sender == None: 29 | sender = self.phone_number_id 30 | 31 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 32 | 33 | if recipient_id: 34 | if "to" in data.keys(): 35 | data_recipient_id = data["to"] 36 | logging.info( 37 | f"Recipient Id is defined in data ({data_recipient_id}) and recipient_id parameter ({recipient_id})" 38 | ) 39 | else: 40 | data["to"] = recipient_id 41 | 42 | logging.info(f"Sending custom json to {recipient_id}") 43 | r = requests.post(url, headers=self.headers, json=data) 44 | if r.status_code == 200: 45 | logging.info(f"Custom json sent to {recipient_id}") 46 | return r.json() 47 | logging.info(f"Custom json not sent to {recipient_id}") 48 | logging.info(f"Status code: {r.status_code}") 49 | logging.error(f"Response: {r.json()}") 50 | return Handle(r.json()) 51 | 52 | 53 | def send_contacts( 54 | self, contacts: List[Dict[Any, Any]], recipient_id: str, sender=None 55 | ) -> Dict[Any, Any]: 56 | """send_contacts 57 | 58 | Send a list of contacts to a user 59 | 60 | Args: 61 | contacts(List[Dict[Any, Any]]): List of contacts to send 62 | recipient_id(str): Phone number of the user with country code wihout + 63 | 64 | Example: 65 | >>> from whatsapp import WhatsApp 66 | >>> whatsapp = WhatsApp(token, phone_number_id) 67 | >>> contacts = [{ 68 | "addresses": [{ 69 | "street": "STREET", 70 | "city": "CITY", 71 | "state": "STATE", 72 | "zip": "ZIP", 73 | "country": "COUNTRY", 74 | "country_code": "COUNTRY_CODE", 75 | "type": "HOME" 76 | }, 77 | .... 78 | } 79 | ] 80 | 81 | REFERENCE: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#contacts-object 82 | """ 83 | try: 84 | sender = dict(self.l)[sender] 85 | 86 | except: 87 | sender = self.phone_number_id 88 | 89 | if sender == None: 90 | sender = self.phone_number_id 91 | 92 | url = f"https://graph.facebook.com/{self.LATEST}/{sender}/messages" 93 | 94 | data = { 95 | "messaging_product": "whatsapp", 96 | "to": recipient_id, 97 | "type": "contacts", 98 | "contacts": contacts, 99 | } 100 | logging.info(f"Sending contacts to {recipient_id}") 101 | r = requests.post(url, headers=self.headers, json=data) 102 | if r.status_code == 200: 103 | logging.info(f"Contacts sent to {recipient_id}") 104 | return r.json() 105 | logging.info(f"Contacts not sent to {recipient_id}") 106 | logging.info(f"Status code: {r.status_code}") 107 | logging.error(f"Response: {r.json()}") 108 | return Handle(r.json()) 109 | -------------------------------------------------------------------------------- /whatsapp/ext/_static.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict, Union 2 | 3 | 4 | @staticmethod 5 | def is_message(data: Dict[Any, Any]) -> bool: 6 | """is_message checks if the data received from the webhook is a message. 7 | 8 | Args: 9 | data (Dict[Any, Any]): The data received from the webhook 10 | 11 | Returns: 12 | bool: True if the data is a message, False otherwise 13 | """ 14 | data = data["entry"][0]["changes"][0]["value"] 15 | if "messages" in data: 16 | return True 17 | else: 18 | return False 19 | 20 | 21 | @staticmethod 22 | def get_mobile(data: Dict[Any, Any]) -> Union[str, None]: 23 | """ 24 | Extracts the mobile number of the sender from the data received from the webhook. 25 | 26 | Args: 27 | data[dict]: The data received from the webhook 28 | Returns: 29 | str: The mobile number of the sender 30 | 31 | Example: 32 | >>> from whatsapp import WhatsApp 33 | >>> whatsapp = WhatsApp(token, phone_number_id) 34 | >>> mobile = whatsapp.get_mobile(data) 35 | """ 36 | data = data["entry"][0]["changes"][0]["value"] 37 | if "contacts" in data: 38 | return data["contacts"][0]["wa_id"] 39 | 40 | 41 | @staticmethod 42 | def get_name(data: Dict[Any, Any]) -> Union[str, None]: 43 | """ 44 | Extracts the name of the sender from the data received from the webhook. 45 | 46 | Args: 47 | data[dict]: The data received from the webhook 48 | Returns: 49 | str: The name of the sender 50 | Example: 51 | >>> from whatsapp import WhatsApp 52 | >>> whatsapp = WhatsApp(token, phone_number_id) 53 | >>> mobile = whatsapp.get_name(data) 54 | """ 55 | contact = data["entry"][0]["changes"][0]["value"] 56 | if contact: 57 | return contact["contacts"][0]["profile"]["name"] 58 | 59 | 60 | @staticmethod 61 | def get_message(data: Dict[Any, Any]) -> Union[str, None]: 62 | """ 63 | Extracts the text message of the sender from the data received from the webhook. 64 | 65 | Args: 66 | data[dict]: The data received from the webhook 67 | Returns: 68 | str: The text message received from the sender 69 | Example: 70 | >>> from whatsapp import WhatsApp 71 | >>> whatsapp = WhatsApp(token, phone_number_id) 72 | >>> message = message.get_message(data) 73 | """ 74 | data = data["entry"][0]["changes"][0]["value"] 75 | if "messages" in data: 76 | return data["messages"][0]["text"]["body"] 77 | 78 | 79 | @staticmethod 80 | def get_message_id(data: Dict[Any, Any]) -> Union[str, None]: 81 | """ 82 | Extracts the message id of the sender from the data received from the webhook. 83 | 84 | Args: 85 | data[dict]: The data received from the webhook 86 | Returns: 87 | str: The message id of the sender 88 | Example: 89 | >>> from whatsapp import WhatsApp 90 | >>> whatsapp = WhatsApp(token, phone_number_id) 91 | >>> message_id = whatsapp.get_message_id(data) 92 | """ 93 | data = data["entry"][0]["changes"][0]["value"] 94 | if "messages" in data: 95 | return data["messages"][0]["id"] 96 | 97 | 98 | @staticmethod 99 | def get_message_timestamp(data: Dict[Any, Any]) -> Union[str, None]: 100 | """ " 101 | Extracts the timestamp of the message from the data received from the webhook. 102 | 103 | Args: 104 | data[dict]: The data received from the webhook 105 | Returns: 106 | str: The timestamp of the message 107 | Example: 108 | >>> from whatsapp import WhatsApp 109 | >>> whatsapp = WhatsApp(token, phone_number_id) 110 | >>> whatsapp.get_message_timestamp(data) 111 | """ 112 | data = data["entry"][0]["changes"][0]["value"] 113 | if "messages" in data: 114 | return data["messages"][0]["timestamp"] 115 | 116 | 117 | @staticmethod 118 | def get_interactive_response(data: Dict[Any, Any]) -> Union[Dict, None]: 119 | """ 120 | Extracts the response of the interactive message from the data received from the webhook. 121 | 122 | Args: 123 | data[dict]: The data received from the webhook 124 | Returns: 125 | dict: The response of the interactive message 126 | 127 | Example: 128 | >>> from whatsapp import WhatsApp 129 | >>> whatsapp = WhatsApp(token, phone_number_id) 130 | >>> response = whatsapp.get_interactive_response(data) 131 | >>> interactive_type = response.get("type") 132 | >>> message_id = response[interactive_type]["id"] 133 | >>> message_text = response[interactive_type]["title"] 134 | """ 135 | data = data["entry"][0]["changes"][0]["value"] 136 | if "messages" in data: 137 | if "interactive" in data["messages"][0]: 138 | return data["messages"][0]["interactive"] 139 | 140 | 141 | @staticmethod 142 | def get_location(data: Dict[Any, Any]) -> Union[Dict, None]: 143 | """ 144 | Extracts the location of the sender from the data received from the webhook. 145 | 146 | Args: 147 | data[dict]: The data received from the webhook 148 | 149 | Returns: 150 | dict: The location of the sender 151 | 152 | Example: 153 | >>> from whatsapp import WhatsApp 154 | >>> whatsapp = WhatsApp(token, phone_number_id) 155 | >>> whatsapp.get_location(data) 156 | """ 157 | data = data["entry"][0]["changes"][0]["value"] 158 | if "messages" in data: 159 | if "location" in data["messages"][0]: 160 | return data["messages"][0]["location"] 161 | 162 | 163 | @staticmethod 164 | def get_image(data: Dict[Any, Any]) -> Union[Dict, None]: 165 | """ " 166 | Extracts the image of the sender from the data received from the webhook. 167 | 168 | Args: 169 | data[dict]: The data received from the webhook 170 | Returns: 171 | dict: The image_id of an image sent by the sender 172 | 173 | Example: 174 | >>> from whatsapp import WhatsApp 175 | >>> whatsapp = WhatsApp(token, phone_number_id) 176 | >>> image_id = whatsapp.get_image(data) 177 | """ 178 | data = data["entry"][0]["changes"][0]["value"] 179 | if "messages" in data: 180 | if "image" in data["messages"][0]: 181 | return data["messages"][0]["image"] 182 | 183 | 184 | @staticmethod 185 | def get_sticker(data: Dict[Any, Any]) -> Union[Dict, None]: 186 | """ " 187 | Extracts the sticker of the sender from the data received from the webhook. 188 | 189 | Args: 190 | data[dict]: The data received from the webhook 191 | Returns: 192 | dict: The sticker_id of an sticker sent by the sender 193 | 194 | Example: 195 | >>> from whatsapp import WhatsApp 196 | >>> whatsapp = WhatsApp(token, phone_number_id) 197 | >>> sticker_id = whatsapp.get_sticker(data) 198 | """ 199 | data = data["entry"][0]["changes"][0]["value"] 200 | if "messages" in data: 201 | if "sticker" in data["messages"][0]: 202 | return data["messages"][0]["sticker"] 203 | 204 | 205 | @staticmethod 206 | def get_document(data: Dict[Any, Any]) -> Union[Dict, None]: 207 | """ " 208 | Extracts the document of the sender from the data received from the webhook. 209 | 210 | Args: 211 | data[dict]: The data received from the webhook 212 | Returns: 213 | dict: The document_id of an image sent by the sender 214 | 215 | Example: 216 | >>> from whatsapp import WhatsApp 217 | >>> whatsapp = WhatsApp(token, phone_number_id) 218 | >>> document_id = whatsapp.get_document(data) 219 | """ 220 | data = data["entry"][0]["changes"][0]["value"] 221 | if "messages" in data: 222 | if "document" in data["messages"][0]: 223 | return data["messages"][0]["document"] 224 | 225 | 226 | @staticmethod 227 | def get_audio(data: Dict[Any, Any]) -> Union[Dict, None]: 228 | """ 229 | Extracts the audio of the sender from the data received from the webhook. 230 | 231 | Args: 232 | data[dict]: The data received from the webhook 233 | 234 | Returns: 235 | dict: The audio of the sender 236 | 237 | Example: 238 | >>> from whatsapp import WhatsApp 239 | >>> whatsapp = WhatsApp(token, phone_number_id) 240 | >>> whatsapp.get_audio(data) 241 | """ 242 | data = data["entry"][0]["changes"][0]["value"] 243 | if "messages" in data: 244 | if "audio" in data["messages"][0]: 245 | return data["messages"][0]["audio"] 246 | 247 | 248 | @staticmethod 249 | def get_video(data: Dict[Any, Any]) -> Union[Dict, None]: 250 | """ 251 | Extracts the video of the sender from the data received from the webhook. 252 | 253 | Args: 254 | data[dict]: The data received from the webhook 255 | 256 | Returns: 257 | dict: Dictionary containing the video details sent by the sender 258 | 259 | Example: 260 | >>> from whatsapp import WhatsApp 261 | >>> whatsapp = WhatsApp(token, phone_number_id) 262 | >>> whatsapp.get_video(data) 263 | """ 264 | data = data["entry"][0]["changes"][0]["value"] 265 | if "messages" in data: 266 | if "video" in data["messages"][0]: 267 | return data["messages"][0]["video"] 268 | 269 | 270 | @staticmethod 271 | def get_message_type(data: Dict[Any, Any]) -> Union[str, None]: 272 | """ 273 | Gets the type of the message sent by the sender from the data received from the webhook. 274 | 275 | 276 | Args: 277 | data [dict]: The data received from the webhook 278 | 279 | Returns: 280 | str: The type of the message sent by the sender 281 | 282 | Example: 283 | >>> from whatsapp import WhatsApp 284 | >>> whatsapp = WhatsApp(token, phone_number_id) 285 | >>> whatsapp.get_message_type(data) 286 | """ 287 | data = data["entry"][0]["changes"][0]["value"] 288 | if "messages" in data: 289 | return data["messages"][0]["type"] 290 | 291 | 292 | @staticmethod 293 | def get_delivery(data: Dict[Any, Any]) -> Union[Dict, None]: 294 | """ 295 | Extracts the delivery status of the message from the data received from the webhook. 296 | Args: 297 | data [dict]: The data received from the webhook 298 | 299 | Returns: 300 | dict: The delivery status of the message and message id of the message 301 | """ 302 | data = data["entry"][0]["changes"][0]["value"] 303 | if "statuses" in data: 304 | return data["statuses"][0]["status"] 305 | 306 | 307 | @staticmethod 308 | def changed_field(data: Dict[Any, Any]) -> str: 309 | """ 310 | Helper function to check if the field changed in the data received from the webhook. 311 | 312 | Args: 313 | data [dict]: The data received from the webhook 314 | 315 | Returns: 316 | str: The field changed in the data received from the webhook 317 | 318 | Example: 319 | >>> from whatsapp import WhatsApp 320 | >>> whatsapp = WhatsApp(token, phone_number_id) 321 | >>> whatsapp.changed_field(data) 322 | """ 323 | return data["entry"][0]["changes"][0]["field"] 324 | 325 | 326 | @staticmethod 327 | def get_author(data: Dict[Any, Any]) -> Union[str, None]: 328 | try: 329 | return data["entry"][0]["changes"][0]["value"]["messages"][0]["from"] 330 | except Exception: 331 | return None 332 | --------------------------------------------------------------------------------