whatsapp-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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Antonio Ventilii
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 all
13
+ 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.
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.1
2
+ Name: whatsapp_wrapper
3
+ Version: 0.1.0
4
+ Summary: Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.
5
+ Home-page: https://github.com/AntonioVentilii/whatsapp-wrapper
6
+ Author: Antonio Ventilii
7
+ Author-email: antonioventilii@gmail.com
8
+ License: MIT
9
+ Project-URL: Source Code, https://github.com/AntonioVentilii/whatsapp-wrapper
10
+ Project-URL: Issue Tracker, https://github.com/AntonioVentilii/whatsapp-wrapper/issues
11
+ Keywords: WhatsApp,Firestore,API,integration,messaging
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+
25
+ # whatsapp-wrapper
26
+
27
+ Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.
28
+
29
+ ## WhatsApp Documentation
30
+
31
+ - [API Endpoint References](https://developers.facebook.com/docs/whatsapp/cloud-api/reference)
32
+ - [Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages)
33
+ - [API Error Codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes)
34
+ - [Override Callback URL](https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks/#overriding-the-callback-url)
35
+
36
+ ## Graph API Documentation
37
+
38
+ - [WhatsApp Business Account](https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/)
@@ -0,0 +1,14 @@
1
+ # whatsapp-wrapper
2
+
3
+ Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.
4
+
5
+ ## WhatsApp Documentation
6
+
7
+ - [API Endpoint References](https://developers.facebook.com/docs/whatsapp/cloud-api/reference)
8
+ - [Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages)
9
+ - [API Error Codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes)
10
+ - [Override Callback URL](https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks/#overriding-the-callback-url)
11
+
12
+ ## Graph API Documentation
13
+
14
+ - [WhatsApp Business Account](https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/)
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,39 @@
1
+ from setuptools import find_packages, setup
2
+
3
+ setup(
4
+ name='whatsapp_wrapper',
5
+ version='0.1.0',
6
+ author='Antonio Ventilii',
7
+ author_email='antonioventilii@gmail.com',
8
+ license='MIT',
9
+ description='Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.',
10
+ long_description=open('README.md').read(),
11
+ long_description_content_type='text/markdown',
12
+ url='https://github.com/AntonioVentilii/whatsapp-wrapper',
13
+ project_urls={
14
+ 'Source Code': 'https://github.com/AntonioVentilii/whatsapp-wrapper',
15
+ 'Issue Tracker': 'https://github.com/AntonioVentilii/whatsapp-wrapper/issues',
16
+ },
17
+ packages=find_packages(),
18
+ classifiers=[
19
+ 'Development Status :: 3 - Alpha',
20
+ 'Intended Audience :: Developers',
21
+ 'Topic :: Software Development :: Libraries :: Python Modules',
22
+ 'License :: OSI Approved :: MIT License',
23
+ 'Programming Language :: Python :: 3',
24
+ 'Programming Language :: Python :: 3.8',
25
+ 'Programming Language :: Python :: 3.9',
26
+ 'Programming Language :: Python :: 3.10',
27
+ 'Programming Language :: Python :: 3.11',
28
+ ],
29
+ keywords='WhatsApp, Firestore, API, integration, messaging',
30
+ install_requires=[
31
+ 'requests',
32
+ 'firestore-wrapper'
33
+ ],
34
+ python_requires='>=3.8',
35
+ entry_points={
36
+ 'console_scripts': [
37
+ ],
38
+ },
39
+ )
@@ -0,0 +1 @@
1
+ from .core import WhatsAppAPI
@@ -0,0 +1,22 @@
1
+ import os
2
+ import tempfile
3
+
4
+ BASE_URL = 'https://graph.facebook.com'
5
+
6
+ LAST_API_VERSION = 'v19.0'
7
+
8
+ """
9
+ When CONTEXT_AS_CHAIN is True, the user needs to reply to the last message in the conversation chain of answer and
10
+ replies, in order to continue the conversation. If the user sends a new message without replying, the conversation
11
+ chain will be reset.
12
+ When CONTEXT_AS_CHAIN is False and CONTEXT_HISTORY_DURATION is a positive non-null number, the bot considers the entire
13
+ conversation history as context for generating a reply, starting from the message that was CONTEXT_HISTORY_DURATION
14
+ seconds ago.
15
+ In all other cases, the bot will generate a reply without any context.
16
+ """
17
+ CONTEXT_AS_CHAIN = True
18
+ CONTEXT_HISTORY_DURATION = 24 * 60 * 60 # 24 hours
19
+
20
+ CACHE_DIR = os.path.join(tempfile.gettempdir(), "whatsapp_wrapper_cache")
21
+ if not os.path.exists(CACHE_DIR):
22
+ os.makedirs(CACHE_DIR)
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ import warnings
5
+ from typing import Any, Callable, Optional
6
+
7
+ import requests
8
+ from requests import Response
9
+
10
+ from .configs import BASE_URL, LAST_API_VERSION
11
+ from .exceptions import WhatsAppAPIWarning
12
+ from .media_utilities import check_media_type_supported, save_media_to_temp_cache
13
+ from .message_object import MessageObject
14
+ from .whatsapp_db import DatabaseConfig, WhatsAppDB, configure_database
15
+
16
+ ErrorHandlerType = Callable[[Response, dict], Optional[Any]]
17
+
18
+
19
+ def _default_error_handler(response: Response, data: dict):
20
+ status_code = response.status_code
21
+ error_message = (
22
+ f"Request was failed with status code: {status_code}."
23
+ f" Data: {data}"
24
+ )
25
+ raise Exception(error_message)
26
+
27
+
28
+ class WhatsAppAPI:
29
+ BASE_URL = BASE_URL
30
+ DEFAULT_API_VERSION = LAST_API_VERSION
31
+
32
+ _MESSAGE_URI = 'messages'
33
+ _MEDIA_URI = 'media'
34
+
35
+ def __init__(self, mobile_id: str, api_token: str, version: str = LAST_API_VERSION,
36
+ database_config: DatabaseConfig = None, error_handler: ErrorHandlerType = None):
37
+ self.mobile_id = mobile_id
38
+ self.bearer_token = api_token
39
+ self.version = version or self.DEFAULT_API_VERSION
40
+ if database_config is None:
41
+ self._db = None
42
+ txt = "Database configuration is not provided. Chats will not be saved."
43
+ warnings.warn(txt, WhatsAppAPIWarning)
44
+ else:
45
+ self._db = configure_database(database_config)
46
+ self.error_handler: Callable[[Response, dict | None], Any | None] = error_handler or _default_error_handler
47
+
48
+ @property
49
+ def db(self) -> WhatsAppDB:
50
+ return self._db
51
+
52
+ @property
53
+ def base_url(self):
54
+ return f'{self.BASE_URL}/{self.version}'
55
+
56
+ @property
57
+ def mobile_url(self):
58
+ return f'{self.base_url}/{self.mobile_id}'
59
+
60
+ @property
61
+ def headers(self):
62
+ return {'Authorization': f'Bearer {self.bearer_token}'}
63
+
64
+ def request(self, method: str, uri: str, params: dict = None, data: dict = None, base_url: str = None,
65
+ headers: dict = None) -> Response:
66
+ method = method.upper()
67
+ if method not in ['GET', 'POST']:
68
+ raise ValueError(f"Invalid method: {method}")
69
+ elif method == 'GET':
70
+ if data:
71
+ raise ValueError(f"Data is not allowed for GET requests")
72
+ elif method == 'POST':
73
+ if params:
74
+ raise ValueError(f"Params is not allowed for POST requests")
75
+ if not data:
76
+ raise ValueError(f"Data is required for POST requests")
77
+
78
+ base_url = base_url or self.base_url
79
+ url = f"{base_url}/{uri}"
80
+ headers = headers or self.headers
81
+
82
+ if method == 'GET':
83
+ r = requests.request(method, url, headers=headers, params=params)
84
+ else:
85
+ r = requests.request(method, url, headers=headers, json=data)
86
+
87
+ if r.status_code != 200:
88
+ r = self.error_handler(r, data)
89
+
90
+ return r
91
+
92
+ def get_request(self, uri: str, params: dict = None, base_url: str = None, headers: dict = None):
93
+ return self.request('GET', uri=uri, params=params, base_url=base_url, headers=headers)
94
+
95
+ def post_request(self, uri: str, data: dict = None, base_url: str = None, headers: dict = None):
96
+ return self.request('POST', uri=uri, data=data, base_url=base_url, headers=headers)
97
+
98
+ def get_media_details(self, media_id: str) -> dict:
99
+ r = self.get_request(media_id)
100
+ ret = r.json()
101
+ return ret
102
+
103
+ def get_media_data(self, media_url: str) -> bytes:
104
+ r = requests.get(media_url, headers=self.headers)
105
+ if r.status_code != 200:
106
+ raise Exception(f"Failed to get media data! Status code: {r.status_code} - Reason: {r.reason}")
107
+ ret = r.content
108
+ return ret
109
+
110
+ def get_media_file(self, media_url: str, mime_type: str) -> str:
111
+ check_media_type_supported(mime_type, raise_error=True)
112
+ media = self.get_media_data(media_url)
113
+ file = save_media_to_temp_cache(mime_type, media)
114
+ return file
115
+
116
+ def get_media(self, media_id: str) -> str:
117
+ metadata = self.get_media_details(media_id)
118
+ url = metadata['url']
119
+ mime_type = metadata['mime_type']
120
+ file = self.get_media_file(url, mime_type)
121
+ return file
122
+
123
+ def save_message_to_db(self, data: dict, wa_id: str):
124
+ if self.db is None:
125
+ txt = f"Database configuration is not provided. Message {data} will not be saved."
126
+ warnings.warn(txt, WhatsAppAPIWarning)
127
+ else:
128
+ self.db.add_chat_message(data, wa_id)
129
+
130
+ def _send_message(self, data: dict, save_to_db: bool = True) -> dict:
131
+ base_url = self.mobile_url
132
+ uri = self._MESSAGE_URI
133
+ r = self.post_request(uri, data=data, base_url=base_url)
134
+ ret = r.json()
135
+ ret['data'] = data
136
+ if save_to_db:
137
+ ret['data']['id'] = ret['messages'][0]['id']
138
+ ret['data']['timestamp'] = time.time()
139
+ self.save_message_to_db(ret['data'], data['to'])
140
+ return ret
141
+
142
+ def mark_as_read(self, message_id: str) -> dict:
143
+ data = {
144
+ "messaging_product": "whatsapp",
145
+ "status": "read",
146
+ "message_id": message_id,
147
+ }
148
+ ret = self._send_message(data)
149
+ return ret
150
+
151
+ def send_text(self, to: str, message: str, preview_url: bool = False,
152
+ reply_to_message_id: str = None, save_to_db: bool = True) -> dict:
153
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
154
+ payload = message_obj.text(message, preview_url=preview_url)
155
+ ret = self._send_message(payload, save_to_db=save_to_db)
156
+ return ret
157
+
158
+ def send_reaction(self, to: str, reply_to_message_id: str, emoji: str, save_to_db: bool = True) -> dict:
159
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
160
+ payload = message_obj.reaction(emoji)
161
+ ret = self._send_message(payload, save_to_db=save_to_db)
162
+ return ret
163
+
164
+ def send_audio(self, to: str, audio_id_or_url: str, reply_to_message_id: str = None,
165
+ save_to_db: bool = True) -> dict:
166
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
167
+ payload = message_obj.audio(audio_id_or_url)
168
+ ret = self._send_message(payload, save_to_db=save_to_db)
169
+ return ret
170
+
171
+ def send_document(self, to: str, document_id_or_url: str, caption: str = None, filename: str = None,
172
+ reply_to_message_id: str = None, save_to_db: bool = True) -> dict:
173
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
174
+ payload = message_obj.document(document_id_or_url, caption=caption, filename=filename)
175
+ ret = self._send_message(payload, save_to_db=save_to_db)
176
+ return ret
177
+
178
+ def send_image(self, to: str, image_id_or_url: str, caption: str = None, reply_to_message_id: str = None,
179
+ save_to_db: bool = True) -> dict:
180
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
181
+ payload = message_obj.image(image_id_or_url, caption=caption)
182
+ ret = self._send_message(payload, save_to_db=save_to_db)
183
+ return ret
184
+
185
+ def send_sticker(self, to: str, sticker_id_or_url: str, reply_to_message_id: str = None,
186
+ save_to_db: bool = True) -> dict:
187
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
188
+ payload = message_obj.sticker(sticker_id_or_url)
189
+ ret = self._send_message(payload, save_to_db=save_to_db)
190
+ return ret
191
+
192
+ def send_video(self, to: str, video_id_or_url: str, caption: str = None, reply_to_message_id: str = None,
193
+ save_to_db: bool = True) -> dict:
194
+ message_obj = MessageObject(to, reply_to_message_id=reply_to_message_id)
195
+ payload = message_obj.video(video_id_or_url, caption=caption)
196
+ ret = self._send_message(payload, save_to_db=save_to_db)
197
+ return ret
@@ -0,0 +1,2 @@
1
+ class WhatsAppAPIWarning(Warning):
2
+ pass
@@ -0,0 +1,66 @@
1
+ import os
2
+ import uuid
3
+ from datetime import datetime, timedelta
4
+ from mimetypes import guess_extension
5
+
6
+ from .configs import CACHE_DIR
7
+
8
+ supported_types = {
9
+ 'audio': ['audio/aac', 'audio/mp4', 'audio/mpeg', 'audio/amr', 'audio/ogg'],
10
+ 'document': ['text/plain', 'application/pdf', 'application/vnd.ms-powerpoint', 'application/msword',
11
+ 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
12
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
13
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
14
+ 'image': ['image/jpeg', 'image/png'],
15
+ 'video': ['video/mp4', 'video/3gp'],
16
+ 'sticker': ['image/webp'],
17
+ }
18
+ flat_supported_types = [item for sublist in supported_types.values() for item in sublist]
19
+
20
+ type_to_extension = {
21
+ 'audio/ogg': '.ogg',
22
+ }
23
+
24
+
25
+ def check_media_type_supported(mime_type: str, raise_error: bool = False) -> bool:
26
+ check = mime_type in flat_supported_types
27
+ if not check and raise_error:
28
+ raise ValueError(f"MIME type '{mime_type}' is not supported.")
29
+ return check
30
+
31
+
32
+ def delete_old_files_in_cache(cache_dir: str = None):
33
+ cache_dir = cache_dir or CACHE_DIR
34
+
35
+ if not os.path.exists(cache_dir):
36
+ print("Cache directory does not exist.")
37
+ return
38
+
39
+ threshold_date = datetime.now() - timedelta(weeks=1)
40
+
41
+ for filename in os.listdir(cache_dir):
42
+ file_path = os.path.join(cache_dir, filename)
43
+
44
+ mod_time = os.path.getmtime(file_path)
45
+ file_date = datetime.fromtimestamp(mod_time)
46
+
47
+ if file_date < threshold_date:
48
+ os.remove(file_path)
49
+ print(f"Deleted old file: {filename}")
50
+
51
+
52
+ def save_media_to_temp_cache(mime_type: str, binary_data: bytes) -> str:
53
+ cache_dir = CACHE_DIR
54
+ delete_old_files_in_cache(cache_dir)
55
+
56
+ file_extension = type_to_extension.get(mime_type, guess_extension(mime_type) or '.bin')
57
+ while True:
58
+ file_name = f"{uuid.uuid4()}{file_extension}"
59
+ file_path = os.path.join(cache_dir, file_name)
60
+ if not os.path.exists(file_path):
61
+ break
62
+
63
+ with open(file_path, "wb") as file:
64
+ file.write(binary_data)
65
+
66
+ return file_path
@@ -0,0 +1,228 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class MessageObject:
5
+ """
6
+ A class to construct message objects for sending via the WhatsApp Cloud API.
7
+
8
+ Attributes:
9
+ to (str): The recipient's identifier.
10
+ reply_to_message_id (str, optional): The ID of the message to reply to. Default is None.
11
+ messaging_product (str, optional): The messaging product, default is 'whatsapp'.
12
+
13
+ Methods:
14
+ base_data: Returns the base data structure for a message.
15
+ text: Constructs a text message payload.
16
+ reaction: Constructs a reaction message payload.
17
+ audio: Constructs an audio message payload.
18
+ document: Constructs a document message payload.
19
+ image: Constructs an image message payload.
20
+ sticker: Constructs a sticker message payload.
21
+ video: Constructs a video message payload.
22
+ location: Constructs a location message payload.
23
+ contacts: Constructs a contacts message payload (not implemented).
24
+ interactive: Constructs an interactive message payload (not implemented).
25
+ template: Constructs a template message payload (not implemented).
26
+ """
27
+
28
+ def __init__(self, to: str, reply_to_message_id: str = None, messaging_product: str = 'whatsapp'):
29
+ """
30
+ Initializes the MessageObject with recipient information and optional reply context.
31
+
32
+ Parameters:
33
+ to (str): The recipient's phone number ID.
34
+ reply_to_message_id (str, optional): ID of the message being replied to.
35
+ messaging_product (str, optional): The messaging product, default is 'whatsapp'.
36
+ """
37
+ self.to = to
38
+ self.reply_to_message_id = reply_to_message_id
39
+ self.messaging_product = messaging_product
40
+ self.recipient_type = 'individual'
41
+
42
+ @property
43
+ def base_data(self):
44
+ """
45
+ Constructs the base data structure common to all messages.
46
+
47
+ Returns:
48
+ dict: The base data structure for a message.
49
+ """
50
+ data = {
51
+ 'to': str(self.to),
52
+ 'messaging_product': self.messaging_product,
53
+ 'recipient_type': self.recipient_type,
54
+ 'context': {
55
+ 'message_id': self.reply_to_message_id
56
+ }
57
+ }
58
+ return data
59
+
60
+ def text(self, text: str, preview_url: bool = True) -> dict:
61
+ """
62
+ Constructs a payload for sending a text message.
63
+
64
+ Parameters:
65
+ text (str): The message body.
66
+ preview_url (bool, optional): Whether to preview URLs in the message. Defaults to True.
67
+
68
+ Returns:
69
+ dict: The payload for a text message.
70
+ """
71
+ data = self.base_data
72
+ data['type'] = 'text'
73
+ data['text'] = {
74
+ 'preview_url': preview_url,
75
+ 'body': text
76
+ }
77
+ return data
78
+
79
+ def reaction(self, emoji: str) -> dict:
80
+ """
81
+ Constructs a payload for sending a reaction to a message.
82
+
83
+ Parameters:
84
+ emoji (str): The emoji used for the reaction.
85
+
86
+ Returns:
87
+ dict: The payload for a reaction message.
88
+
89
+ Raises:
90
+ ValueError: If `reply_to_message_id` is None, as it's required for reaction messages.
91
+ """
92
+ if self.reply_to_message_id is None:
93
+ raise ValueError('reply_to_message_id is required for reaction message type.')
94
+ data = self.base_data
95
+ data.pop('context')
96
+ data['type'] = 'reaction'
97
+ data['reaction'] = {
98
+ 'message_id': self.reply_to_message_id,
99
+ 'emoji': emoji
100
+ }
101
+ return data
102
+
103
+ def _media(self, media_type: str, media_id_or_url: str, caption: str = None, filename: str = None) -> dict:
104
+ """
105
+ Internal method to construct a payload for sending a media message.
106
+
107
+ Parameters:
108
+ media_type (str): The type of media (audio, document, image, sticker, video).
109
+ media_id_or_url (str): The ID or URL of the media.
110
+ caption (str, optional): The caption for the media. Default is None.
111
+ filename (str, optional): The filename for the media. Default is None.
112
+
113
+ Returns:
114
+ dict: The payload for a media message.
115
+ """
116
+ data = self.base_data
117
+ handle_type = 'link' if 'https' in media_id_or_url else 'id'
118
+ data['type'] = media_type
119
+ data[media_type] = {
120
+ handle_type: media_id_or_url
121
+ }
122
+ if caption:
123
+ data['image']['caption'] = caption
124
+ if filename:
125
+ data['image']['filename'] = filename
126
+ return data
127
+
128
+ def audio(self, audio_id_or_url: str) -> dict:
129
+ """
130
+ Constructs a payload for sending an audio message.
131
+
132
+ Parameters:
133
+ audio_id_or_url (str): The ID or URL of the audio to send.
134
+
135
+ Returns:
136
+ dict: The payload for an audio message.
137
+ """
138
+ data = self._media('audio', audio_id_or_url)
139
+ return data
140
+
141
+ def document(self, document_id_or_url: str, caption: str = None, filename: str = None) -> dict:
142
+ """
143
+ Constructs a payload for sending a document message.
144
+
145
+ Parameters:
146
+ document_id_or_url (str): The ID or URL of the document to send.
147
+ caption (str, optional): The caption for the document. Default is None.
148
+ filename (str, optional): The filename for the document. Default is None.
149
+
150
+ Returns:
151
+ dict: The payload for a document message.
152
+ """
153
+ data = self._media('document', document_id_or_url, caption, filename)
154
+ return data
155
+
156
+ def image(self, image_id_or_url: str, caption: str = None) -> dict:
157
+ """
158
+ Constructs a payload for sending an image message.
159
+
160
+ Parameters:
161
+ image_id_or_url (str): The ID or URL of the image to send.
162
+ caption (str, optional): The caption for the image. Default is None.
163
+
164
+ Returns:
165
+ dict: The payload for an image message.
166
+ """
167
+ data = self._media('image', image_id_or_url, caption)
168
+ return data
169
+
170
+ def sticker(self, sticker_id_or_url: str) -> dict:
171
+ """
172
+ Constructs a payload for sending a sticker message.
173
+
174
+ Parameters:
175
+ sticker_id_or_url (str): The ID or URL of the sticker to send.
176
+
177
+ Returns:
178
+ dict: The payload for a sticker message.
179
+ """
180
+ data = self._media('sticker', sticker_id_or_url)
181
+ return data
182
+
183
+ def video(self, video_id_or_url: str, caption: str = None) -> dict:
184
+ """
185
+ Constructs a payload for sending a video message.
186
+
187
+ Parameters:
188
+ video_id_or_url (str): The ID or URL of the video to send.
189
+ caption (str, optional): The caption for the video. Default is None.
190
+
191
+ Returns:
192
+ dict: The payload for a video message.
193
+ """
194
+ data = self._media('video', video_id_or_url, caption)
195
+ return data
196
+
197
+ def location(self, latitude: float, longitude: float, name: str, address: str) -> dict:
198
+ """
199
+ Constructs a payload for sending a location message.
200
+
201
+ Parameters:
202
+ latitude (float): The latitude of the location.
203
+ longitude (float): The longitude of the location.
204
+ name (str): The name of the location.
205
+ address (str): The address of the location.
206
+
207
+ Returns:
208
+ dict: The payload for a location message.
209
+ """
210
+ data = self.base_data
211
+ data['type'] = 'location'
212
+ data['location'] = {
213
+ 'latitude': latitude,
214
+ 'longitude': longitude,
215
+ 'name': name,
216
+ 'address': address
217
+ }
218
+ return data
219
+
220
+ def contacts(self, contacts: list[dict]) -> dict:
221
+ # TODO: match the contacts format with schema
222
+ raise NotImplementedError('This method is not implemented yet!')
223
+
224
+ def interactive(self) -> dict:
225
+ raise NotImplementedError('This method is not implemented yet!')
226
+
227
+ def template(self) -> dict:
228
+ raise NotImplementedError('This method is not implemented yet!')
@@ -0,0 +1,200 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import os
5
+ import time
6
+ from typing import Optional, TypedDict
7
+
8
+ from firestore_wrapper import FirestoreDB
9
+
10
+ from .configs import CACHE_DIR
11
+
12
+
13
+ class DatabaseConfig(TypedDict, total=False):
14
+ credential_path: Optional[str]
15
+ credential_encoded_json: Optional[str]
16
+ database: Optional[str]
17
+ backup_folder: Optional[str]
18
+
19
+
20
+ CHAT_COLLECTION = 'chats'
21
+ BANNED_USERS_COLLECTION = 'banned_users'
22
+ COLLECTIONS = [
23
+ CHAT_COLLECTION,
24
+ BANNED_USERS_COLLECTION,
25
+ ]
26
+
27
+
28
+ def encoded_credentials_to_json(encoded_str: str) -> str:
29
+ json_data = base64.b64decode(encoded_str).decode('utf-8')
30
+ file = os.path.join(CACHE_DIR, 'firestore_credentials.json')
31
+ with open(file, 'w') as json_file:
32
+ json_file.write(json_data)
33
+ return file
34
+
35
+
36
+ def json_to_encoded_credentials(file: str) -> str:
37
+ if os.path.exists(file):
38
+ with open(file, 'r') as json_file:
39
+ json_data = json_file.read()
40
+ encoded_json = base64.b64encode(json_data.encode('utf-8')).decode('utf-8')
41
+ else:
42
+ raise ValueError(f'Credentials file {file} not found')
43
+ return encoded_json
44
+
45
+
46
+ def clean_chat_data(messages: dict) -> list[dict]:
47
+ cleaned_messages = [
48
+ {
49
+ 'body': message['text']['body'],
50
+ 'from': message.get('from'),
51
+ 'to': message.get('to'),
52
+ 'timestamp': message['timestamp'],
53
+ } for message in messages.values() if message.get('type') == 'text'
54
+ ]
55
+ return cleaned_messages
56
+
57
+
58
+ def find_message_chain(messages: dict, message_id: str) -> list[dict]:
59
+ if message_id not in messages:
60
+ return []
61
+
62
+ message = messages[message_id]
63
+
64
+ if message.get('type') != 'text':
65
+ return []
66
+
67
+ message_info = {
68
+ 'body': message['text']['body'],
69
+ 'from': message.get('from'),
70
+ 'to': message.get('to'),
71
+ 'timestamp': message['timestamp'],
72
+ }
73
+
74
+ result = [message_info]
75
+
76
+ if 'context' in message:
77
+ context = message['context']
78
+ next_message_id = context.get('id', context.get('message_id'))
79
+ if message_id is None:
80
+ raise ValueError(f"Message ID not found in context for message {message_id}")
81
+ previous_messages = find_message_chain(messages, next_message_id)
82
+ result = previous_messages + result
83
+
84
+ return result
85
+
86
+
87
+ def configure_database(config: DatabaseConfig) -> WhatsAppDB:
88
+ credential_path = config.get('credential_path')
89
+ credential_encoded_json = config.get('credential_encoded_json')
90
+ if credential_path is None and credential_encoded_json is None:
91
+ raise ValueError("Database configuration requires either a credential path or encoded JSON.")
92
+ if credential_path and credential_encoded_json:
93
+ print("Both credential path and encoded JSON are provided. Using credential path.")
94
+ credential_path = credential_path or encoded_credentials_to_json(credential_encoded_json)
95
+ database = config.get('database')
96
+ backup_folder = config.get('backup_folder')
97
+ db = WhatsAppDB(credentials_path=credential_path, database=database, backup_folder=backup_folder)
98
+ return db
99
+
100
+
101
+ class WhatsAppDB(FirestoreDB):
102
+
103
+ def __init__(self, credentials_path: str, database: str = None, backup_folder: str = None):
104
+ super().__init__(credentials_path, database=database, collections=COLLECTIONS, backup_folder=backup_folder)
105
+
106
+ def add_chat_message(self, message: dict, wa_id: str) -> str:
107
+ message_id = message['id']
108
+ data = {message_id: message}
109
+ chat_id = self.update_document(CHAT_COLLECTION, wa_id, data, create_if_missing=True)
110
+ return chat_id
111
+
112
+ def add_banned_user(self, data: dict, user_id: str) -> str:
113
+ token_id = self.add_document(BANNED_USERS_COLLECTION, data, document_name=user_id)
114
+ return token_id
115
+
116
+ def update_banned_user(self, user_id: str, data: dict):
117
+ self.update_document(BANNED_USERS_COLLECTION, user_id, data)
118
+
119
+ def delete_chat(self, wa_id: str):
120
+ self.delete_document(CHAT_COLLECTION, wa_id)
121
+
122
+ def delete_banned_user(self, user_id: str):
123
+ self.delete_document(BANNED_USERS_COLLECTION, user_id)
124
+
125
+ def get_chat(self, wa_id: str) -> dict:
126
+ return self.get_document_data(CHAT_COLLECTION, wa_id)
127
+
128
+ def get_filtered_chat(self, wa_id: str, filters: list[tuple[str, str, str | float]]) -> dict:
129
+ chat = self.get_chat(wa_id)
130
+ filtered_chat = {}
131
+ for message_id, message in chat.items():
132
+ for field, operator, value in filters:
133
+ if field not in message:
134
+ continue
135
+ message_value = message[field]
136
+ if isinstance(value, float) and not isinstance(message_value, float):
137
+ try:
138
+ message_value = float(message_value)
139
+ except ValueError:
140
+ continue
141
+ if isinstance(message_value, float) and not isinstance(value, float):
142
+ try:
143
+ value = float(value)
144
+ except ValueError:
145
+ continue
146
+ if operator == '==' and message_value == value:
147
+ filtered_chat[message_id] = message
148
+ elif operator == '!=' and message_value != value:
149
+ filtered_chat[message_id] = message
150
+ elif operator == '>' and message_value > value:
151
+ filtered_chat[message_id] = message
152
+ elif operator == '<' and message_value < value:
153
+ filtered_chat[message_id] = message
154
+ elif operator == '>=' and message_value >= value:
155
+ filtered_chat[message_id] = message
156
+ elif operator == '<=' and message_value <= value:
157
+ filtered_chat[message_id] = message
158
+ return filtered_chat
159
+
160
+ def list_banned_user_names(self) -> list[str]:
161
+ return self.get_document_names(BANNED_USERS_COLLECTION)
162
+
163
+ def list_banned_users(self, with_id: bool = False, as_dict: bool = False) -> list[dict] | dict[str, dict]:
164
+ ret = self.get_collection_data(BANNED_USERS_COLLECTION, with_id=with_id)
165
+ if as_dict:
166
+ ret = {x['id']: x for x in ret}
167
+ return ret
168
+
169
+ def get_banned_user(self, user_id: str, with_id: bool = False) -> dict:
170
+ return self.get_document_data(BANNED_USERS_COLLECTION, user_id, with_id=with_id)['access_token']
171
+
172
+ def get_conversation_chain(self, wa_id: str, message_id: str) -> list[dict]:
173
+ chat = self.get_chat(wa_id)
174
+ message_ids = list(chat.keys())
175
+ if message_id not in message_ids:
176
+ raise ValueError(f"Message ID {message_id} not found in chat history for {wa_id}")
177
+ chain = find_message_chain(chat, message_id)
178
+ return chain
179
+
180
+ def get_conversation_history(self, wa_id: str, since_seconds_ago: int = None) -> list[dict]:
181
+ if since_seconds_ago is not None and since_seconds_ago > 0:
182
+ start_time = time.time() - since_seconds_ago
183
+ chat = self.get_filtered_chat(wa_id, [('timestamp', '>=', start_time)])
184
+ else:
185
+ chat = self.get_chat(wa_id)
186
+ # TODO: remove the cleanup part to accept all messages
187
+ cleaned_chat = clean_chat_data(chat)
188
+ chat_as_list = cleaned_chat # list(chat.values())
189
+ sorted_chat = sorted(chat_as_list, key=lambda x: int(x['timestamp']))
190
+ return sorted_chat
191
+
192
+ def get_conversation(self, wa_id: str, since_seconds_ago: int = None, chain_mode: bool = False,
193
+ message_id: str = None) -> list[dict]:
194
+ if chain_mode:
195
+ if message_id is None:
196
+ raise ValueError("Message ID is required in chain mode")
197
+ chat = self.get_conversation_chain(wa_id, message_id)
198
+ else:
199
+ chat = self.get_conversation_history(wa_id, since_seconds_ago=since_seconds_ago)
200
+ return chat
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.1
2
+ Name: whatsapp-wrapper
3
+ Version: 0.1.0
4
+ Summary: Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.
5
+ Home-page: https://github.com/AntonioVentilii/whatsapp-wrapper
6
+ Author: Antonio Ventilii
7
+ Author-email: antonioventilii@gmail.com
8
+ License: MIT
9
+ Project-URL: Source Code, https://github.com/AntonioVentilii/whatsapp-wrapper
10
+ Project-URL: Issue Tracker, https://github.com/AntonioVentilii/whatsapp-wrapper/issues
11
+ Keywords: WhatsApp,Firestore,API,integration,messaging
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+
25
+ # whatsapp-wrapper
26
+
27
+ Integration layer for WhatsApp Cloud API with Firestore for easy message storage and management.
28
+
29
+ ## WhatsApp Documentation
30
+
31
+ - [API Endpoint References](https://developers.facebook.com/docs/whatsapp/cloud-api/reference)
32
+ - [Messages](https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages)
33
+ - [API Error Codes](https://developers.facebook.com/docs/whatsapp/cloud-api/support/error-codes)
34
+ - [Override Callback URL](https://developers.facebook.com/docs/whatsapp/embedded-signup/webhooks/#overriding-the-callback-url)
35
+
36
+ ## Graph API Documentation
37
+
38
+ - [WhatsApp Business Account](https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/)
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ whatsapp_wrapper/__init__.py
5
+ whatsapp_wrapper/configs.py
6
+ whatsapp_wrapper/core.py
7
+ whatsapp_wrapper/exceptions.py
8
+ whatsapp_wrapper/media_utilities.py
9
+ whatsapp_wrapper/message_object.py
10
+ whatsapp_wrapper/whatsapp_db.py
11
+ whatsapp_wrapper.egg-info/PKG-INFO
12
+ whatsapp_wrapper.egg-info/SOURCES.txt
13
+ whatsapp_wrapper.egg-info/dependency_links.txt
14
+ whatsapp_wrapper.egg-info/requires.txt
15
+ whatsapp_wrapper.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ requests
2
+ firestore-wrapper
@@ -0,0 +1 @@
1
+ whatsapp_wrapper