Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove/fast api #37

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Upload Python Package to PyPI when a Release is Created

on:
release:
types: [created]

jobs:
pypi-publish:
name: Publish release to PyPI
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/p/whatsapp-python-cloud-api
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel
- name: Build package
run: |
python setup.py sdist bdist_wheel # Could also be python -m build
- name: Publish package distributions to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
18 changes: 9 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name="whatsapp-python"
authors = [{name="Filippo Romani", email="mail@filipporomani.it"}]
name="whatsapp-python-cloud-api"
authors = [{name="Yoandre Saavedra", email="mail@filipporomani.it"}]
description="Open source Python wrapper for the WhatsApp Cloud API"
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -31,19 +31,19 @@ classifiers=[
dynamic = [
"version"
]
dependencies = ["fastapi", "uvicorn", "requests_toolbelt", "requests", "python-dotenv"]
dependencies = ["requests_toolbelt", "requests", "python-dotenv"]

[project.urls]
Homepage = "https://github.com/filipporomani/whatsapp-python"
Docs = "https://github.com/filipporomani/whatsapp-python/wiki"
"Issues Reporting" = "https://github.com/filipporomani/whatsapp-python/issues"
Download = "https://github.com/filipporomani/whatsapp-python/releases/latest"
Changelog = "https://github.com/filipporomani/whatsapp-python/releases"
Homepage = "https://github.com/yoandresaav/whatsapp-python-cloud-api"
Docs = "https://github.com/yoandresaav/whatsapp-python-cloud-api/wiki"
"Issues Reporting" = "https://github.com/yoandresaav/whatsapp-python-cloud-api/issues"
Download = "https://github.com/yoandresaav/whatsapp-python-cloud-api/releases/latest"
Changelog = "https://github.com/yoandresaav/whatsapp-python-cloud-api/releases"


[tool.hatch.version]
path = "whatsapp/constants.py"
variable = "VERSION"

[tool.hatch.build.targets.wheel]
packages = ["whatsapp"]
packages = ["whatsapp-python-cloud-api"]
107 changes: 47 additions & 60 deletions whatsapp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@

import requests
import logging
from fastapi import FastAPI, HTTPException, Request
from uvicorn import run as _run
from .constants import VERSION
from .ext._property import authorized
from .ext._send_others import send_custom_json, send_contacts
Expand All @@ -33,23 +31,23 @@ def __init__(self, token: str = "", phone_number_id: str = "", logger: bool = Tr
logging.getLogger(__name__).addHandler(logging.NullHandler())

self.VERSION = VERSION
if update_check is True:
latest = str(requests.get(
"https://pypi.org/pypi/whatsapp-python/json").json()["info"]["version"])
if self.VERSION != latest:
try:
version_int = int(self.VERSION.replace(".", ""))
except:
version_int = 0
latest_int = int(latest.replace(".", ""))
# 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)
if version_int < latest_int:
if version_int == 0:
logging.critical(
f"There was an error while checking for updates, please update the package manually or report the issue on GitHub.")
else:
logging.critical(
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.")
# if update_check is True:
# latest = str(requests.get(
# "https://pypi.org/pypi/whatsapp-python/json").json()["info"]["version"])
# if self.VERSION != latest:
# try:
# version_int = int(self.VERSION.replace(".", ""))
# except:
# version_int = 0
# latest_int = int(latest.replace(".", ""))
# # 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)
# if version_int < latest_int:
# if version_int == 0:
# logging.critical(
# f"There was an error while checking for updates, please update the package manually or report the issue on GitHub.")
# else:
# logging.critical(
# 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.")

if token == "":
logging.error("Token not provided")
Expand Down Expand Up @@ -80,48 +78,40 @@ async def base(*args):
logging.disable(logging.DEBUG)
logging.disable(logging.ERROR)

self.app = FastAPI()

# Verification handler has 1 argument: challenge (str | bool): str if verification is successful, False if not

@self.app.get("/")
async def verify_endpoint(r: Request):
if r.query_params.get("hub.verify_token") == self.verify_token:
logging.debug("Webhook verified successfully")
challenge = r.query_params.get("hub.challenge")
self.verification_handler(challenge)
self.other_handler(challenge)
return int(challenge)
logging.error("Webhook Verification failed - token mismatch")
await self.verification_handler(False)
await self.other_handler(False)
return {"success": False}
async def verify_endpoint(self, query_params: dict):
if query_params.get("hub.verify_token") == self.verify_token:
logging.debug("Webhook verified successfully")
challenge = query_params.get("hub.challenge")
self.verification_handler(challenge)
self.other_handler(challenge)
return int(challenge)
logging.error("Webhook Verification failed - token mismatch")
await self.verification_handler(False)
await self.other_handler(False)
return {"success": False}

@self.app.post("/")
async def hook(r: Request):
try:
# Handle Webhook Subscriptions
data = await r.json()
if data is None:
return {"success": False}
data_str = json.dumps(data, indent=4)
# log the data received only if the log level is debug
logging.debug(f"Received webhook data: {data_str}")
async def hook(request: dict):
try:
# Handle Webhook Subscriptions
data = request.get('data')
if data is None:
return {"success": False}
data_str = json.dumps(data, indent=4)
# log the data received only if the log level is debug
logging.debug(f"Received webhook data: {data_str}")

changed_field = self.changed_field(data)
if changed_field == "messages":
new_message = self.is_message(data)
if new_message:
msg = Message(instance=self, data=data)
await self.message_handler(msg)
await self.other_handler(msg)
return {"success": True}
except Exception as e:
logging.error(f"Error parsing message: {e}")
raise HTTPException(status_code=500, detail={
"success": False,
"error": str(e)
})
changed_field = self.changed_field(data)
if changed_field == "messages":
new_message = self.is_message(data)
if new_message:
msg = Message(instance=self, data=data)
await self.message_handler(msg)
await self.other_handler(msg)
return {"success": True}
except Exception as e:
logging.error(f"Error parsing message: {e}")

# all the files starting with _ are imported here, and should not be imported directly.

Expand Down Expand Up @@ -200,9 +190,6 @@ def on_verification(self, handler: function):
"""
self.verification_handler = handler

def run(self, host: str = "localhost", port: int = 5000, **options):
_run(self.app, host=host, port=port, **options)


class Message(object):
def __init__(self, id: int = None, data: dict = {}, instance: WhatsApp = None, content: str = "", to: str = "", rec_type: str = "individual"): # type: ignore
Expand Down
Loading