django-whatsapp-api-wrapper 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Edivaldo Delgado
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.3
2
+ Name: django-whatsapp-api-wrapper
3
+ Version: 0.1.0
4
+ Summary:
5
+ License: MIT
6
+ Author: Your Name
7
+ Author-email: you@example.com
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Web Environment
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Provides-Extra: dev
23
+ Requires-Dist: build (==1.2.1) ; extra == "dev"
24
+ Requires-Dist: django (>=4.2)
25
+ Requires-Dist: dotenv (>=0.9.9,<0.10.0)
26
+ Requires-Dist: nox (==2024.4.15) ; extra == "dev"
27
+ Requires-Dist: python-dotenv (>=1.0,<2.0)
28
+ Requires-Dist: twine (==5.1.1) ; extra == "dev"
29
+ Description-Content-Type: text/markdown
30
+
31
+ # django-whatsapp-api-wrapper
@@ -0,0 +1 @@
1
+ # django-whatsapp-api-wrapper
@@ -0,0 +1,41 @@
1
+ [tool.poetry]
2
+ name = "django-whatsapp-api-wrapper"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Your Name <you@example.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ include = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 4 - Beta",
11
+ "Environment :: Web Environment",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Programming Language :: Python :: Implementation :: CPython",
18
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ ]
21
+
22
+ [[tool.poetry.packages]]
23
+ include = "django_whatsapp_api_wrapper"
24
+ from = "src"
25
+
26
+ [tool.poetry.dependencies]
27
+ python = "^3.11"
28
+ django = ">=4.2"
29
+ build = { version = "1.2.1", optional = true }
30
+ nox = { version = "2024.4.15", optional = true }
31
+ twine = { version = "5.1.1", optional = true }
32
+ python-dotenv = "^1.0"
33
+ dotenv = "^0.9.9"
34
+
35
+ [tool.poetry.extras]
36
+ dev = ["build", "nox", "twine"]
37
+
38
+
39
+ [build-system]
40
+ requires = ["poetry-core"]
41
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,12 @@
1
+ # 1. Import Third Party Libraries
2
+ import logging
3
+ import requests
4
+
5
+ # 2. Import Local Libraries
6
+ from .messages import Message
7
+ from .client import WhatsApp
8
+
9
+ __all__ = ["WhatsApp", "Message"]
10
+
11
+
12
+
@@ -0,0 +1,3 @@
1
+ from django.contrib import admin
2
+
3
+ # Register your models here.
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DjangoWhatsappApiWrapperConfig(AppConfig):
5
+ default_auto_field = 'django.db.models.BigAutoField'
6
+ name = 'django_whatsapp_api_wrapper'
@@ -0,0 +1,51 @@
1
+ import logging
2
+ import requests
3
+ from django.conf import settings
4
+ from .messages import Message
5
+
6
+
7
+ class WhatsApp:
8
+ def __init__(
9
+ self,
10
+ token: str = settings.TOKEN,
11
+ phone_number_id: str = settings.PHONE_NUMBER_ID #Default to the phone number id from the settings,
12
+ ):
13
+ """
14
+ Initialize the WhatsApp Object
15
+
16
+ Args:
17
+ token[str]: Token for the WhatsApp cloud API
18
+ phone_number_id[str]: Phone number id for the WhatsApp cloud API
19
+ """
20
+
21
+ if token == "":
22
+ logging.error("Token not provided")
23
+ raise ValueError("Token not provided but required")
24
+ if phone_number_id == "":
25
+ logging.error("Phone number ID not provided")
26
+ raise ValueError("Phone number ID not provided but required")
27
+
28
+ self.PACKAGE_VERSION = settings.PACKAGE_VERSION # package version
29
+ self.API_VERSION = settings.API_VERSION # api version
30
+
31
+ self.token = token
32
+ self.phone_number_id = phone_number_id
33
+ self.base_url = f"https://graph.facebook.com/{self.API_VERSION}"
34
+ self.url = f"{self.base_url}/{phone_number_id}/messages"
35
+
36
+ self.headers = {
37
+ "Content-Type": "application/json",
38
+ "Authorization": f"Bearer {self.token}",
39
+ }
40
+
41
+ def build_message(self, **kwargs) -> Message:
42
+ """
43
+ Build a message object
44
+
45
+ Args:
46
+ data[dict]: The message data
47
+ content[str]: The message content
48
+ to[str]: The recipient
49
+ rec_type[str]: The recipient type (individual/group)
50
+ """
51
+ return Message(**kwargs, instance=self)
@@ -0,0 +1,60 @@
1
+ import logging
2
+ import requests
3
+
4
+ class Message:
5
+ # type: ignore
6
+ def __init__(
7
+ self,
8
+ messaging_product: str = "whatsapp",
9
+ to: str = "",
10
+ type: str = "",
11
+ data: dict = {},
12
+ instance: "WhatsApp" = None,
13
+ recipient_type: str = "individual",
14
+ ):
15
+ if instance is not None:
16
+ from .. import WhatsApp
17
+ assert isinstance(instance, WhatsApp)
18
+ self.instance = instance
19
+ self.type = type
20
+ self.data = data
21
+ self.messaging_product = messaging_product
22
+ self.recipient_type = recipient_type
23
+ self.to = to
24
+
25
+ def send(self) -> dict:
26
+ try:
27
+ sender = self.instance.phone_number_id
28
+ except:
29
+ logging.error("Phone number id not found")
30
+
31
+ payload = {
32
+ "messaging_product": "whatsapp",
33
+ "recipient_type": self.recipient_type,
34
+ "to": self.to,
35
+ }
36
+
37
+ if self.type == "text":
38
+ payload.update({
39
+ "type": "text",
40
+ "text": self.data,
41
+ })
42
+ elif self.type == "template":
43
+ payload.update({
44
+ "type": "template",
45
+ "template": self.data,
46
+ })
47
+
48
+ print(payload)
49
+
50
+ logging.info(f"Sending message to {self.to}")
51
+ r = requests.post(self.instance.url, headers=self.instance.headers, json=payload)
52
+ if r.status_code == 200:
53
+ logging.info(f"Message sent to {self.to}")
54
+ return r.json()
55
+ logging.info(f"Message not sent to {self.to}")
56
+ logging.info(f"Status code: {r.status_code}")
57
+ logging.error(f"Response: {r.json()}")
58
+ return r.json()
59
+
60
+
@@ -0,0 +1,8 @@
1
+ data = dict(
2
+ template=dict(
3
+ name="opa",
4
+ language=dict(
5
+ code="pt_BR"
6
+ )
7
+ )
8
+ )
@@ -0,0 +1,11 @@
1
+ def text(self, text: str, preview_url: bool = False) -> dict:
2
+
3
+ data = {
4
+ "messaging_product": "whatsapp",
5
+ "recipient_type": self.rec,
6
+ "to": self.to,
7
+ "type": "text",
8
+ "text": {"preview_url": preview_url, "body": self.content},
9
+ }
10
+
11
+ return data
@@ -0,0 +1,25 @@
1
+ #############################
2
+ #### SEND TEMPLATE ##########
3
+ #############################
4
+
5
+ from django_whatsapp_api_wrapper import *
6
+ wp = WhatsApp()
7
+
8
+ language = {"code": "pt_BR"}
9
+ template = {"name": "opa", "language": language}
10
+ data = template
11
+
12
+ m = wp.build_message(to = "5521980340830", type = "template", data=data)
13
+ m.send()
14
+
15
+
16
+ #############################
17
+ #### SEND MESSAGE ###########
18
+ #############################
19
+
20
+ from django_whatsapp_api_wrapper import *
21
+ wp = WhatsApp()
22
+
23
+ data = {"preview_url": False, "body": "oPA!!"}
24
+ m3 = wp.build_message(to = "+5521980340830", type = "text", data=data)
25
+ m3.send()
@@ -0,0 +1,3 @@
1
+ from django.test import TestCase
2
+
3
+ # Create your tests here.
@@ -0,0 +1,6 @@
1
+ from django.urls import path
2
+ from .views import whatsapp_webhook
3
+
4
+ urlpatterns = [
5
+ path("webhook/", whatsapp_webhook, name="whatsapp_webhook"),
6
+ ]
@@ -0,0 +1,38 @@
1
+ import json
2
+ from django.conf import settings
3
+ from django.http import HttpRequest, HttpResponse, JsonResponse
4
+ from django.views.decorators.csrf import csrf_exempt
5
+
6
+
7
+ @csrf_exempt
8
+ def whatsapp_webhook(request: HttpRequest) -> HttpResponse:
9
+ """
10
+ Webhook endpoint for WhatsApp Cloud API.
11
+
12
+ - GET: Verification handshake using hub.mode, hub.challenge, hub.verify_token
13
+ - POST: Receive event notifications (messages, status updates, etc.)
14
+ """
15
+ if request.method == "GET":
16
+ mode = request.GET.get("hub.mode")
17
+ token = request.GET.get("hub.verify_token")
18
+ challenge = request.GET.get("hub.challenge")
19
+
20
+ if mode == "subscribe" and token == getattr(settings, "WHATSAPP_VERIFY_TOKEN", None):
21
+ return HttpResponse(challenge or "", status=200)
22
+ return HttpResponse(status=403)
23
+
24
+ if request.method == "POST":
25
+ try:
26
+ payload = json.loads(request.body.decode("utf-8")) if request.body else {}
27
+ except json.JSONDecodeError:
28
+ return HttpResponse(status=400)
29
+
30
+ # Basic structure check per WhatsApp webhook format
31
+ # { object, entry: [ { changes: [ { field, value: { messaging_product, metadata, ... } } ] } ] }
32
+ # For now, echo 200 OK to acknowledge receipt.
33
+ # You can extend this to process messages, statuses, etc.
34
+ return JsonResponse({"status": "received"}, status=200)
35
+
36
+ return HttpResponse(status=405)
37
+
38
+