whatsapp-chatgpt-python 1.0.0__py3-none-any.whl
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.
- whatsapp_chatgpt_python/__init__.py +35 -0
- whatsapp_chatgpt_python/bot.py +292 -0
- whatsapp_chatgpt_python/config.py +33 -0
- whatsapp_chatgpt_python/handlers/__init__.py +15 -0
- whatsapp_chatgpt_python/handlers/audio.py +84 -0
- whatsapp_chatgpt_python/handlers/base.py +63 -0
- whatsapp_chatgpt_python/handlers/contact.py +47 -0
- whatsapp_chatgpt_python/handlers/document.py +42 -0
- whatsapp_chatgpt_python/handlers/image.py +111 -0
- whatsapp_chatgpt_python/handlers/location.py +45 -0
- whatsapp_chatgpt_python/handlers/poll.py +69 -0
- whatsapp_chatgpt_python/handlers/registry.py +128 -0
- whatsapp_chatgpt_python/handlers/text.py +32 -0
- whatsapp_chatgpt_python/handlers/video.py +43 -0
- whatsapp_chatgpt_python/logger.py +36 -0
- whatsapp_chatgpt_python/middleware/__init__.py +6 -0
- whatsapp_chatgpt_python/middleware/base.py +55 -0
- whatsapp_chatgpt_python/middleware/manager.py +111 -0
- whatsapp_chatgpt_python/models.py +19 -0
- whatsapp_chatgpt_python/notification.py +68 -0
- whatsapp_chatgpt_python/utils/__init__.py +31 -0
- whatsapp_chatgpt_python/utils/conversation.py +56 -0
- whatsapp_chatgpt_python/utils/media.py +54 -0
- whatsapp_chatgpt_python/utils/router.py +159 -0
- whatsapp_chatgpt_python-1.0.0.dist-info/LICENSE +21 -0
- whatsapp_chatgpt_python-1.0.0.dist-info/METADATA +678 -0
- whatsapp_chatgpt_python-1.0.0.dist-info/RECORD +29 -0
- whatsapp_chatgpt_python-1.0.0.dist-info/WHEEL +5 -0
- whatsapp_chatgpt_python-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Extended notification class
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from whatsapp_chatbot_python import Notification as BaseNotification
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger('whatsapp_chatgpt_python')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ExtendedNotification(BaseNotification):
|
|
12
|
+
"""
|
|
13
|
+
Extended notification class with GPT processing capability
|
|
14
|
+
|
|
15
|
+
This subclass adds a method to process a message with GPT
|
|
16
|
+
after it's been handled by a handler.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, event, api, state_manager, gpt_bot=None):
|
|
20
|
+
"""
|
|
21
|
+
Initialize an extended notification
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
event: The event data
|
|
25
|
+
api: The GreenAPI instance
|
|
26
|
+
state_manager: The state manager
|
|
27
|
+
gpt_bot: Reference to the WhatsappGptBot instance
|
|
28
|
+
"""
|
|
29
|
+
super().__init__(event, api, state_manager)
|
|
30
|
+
self.gpt_bot = gpt_bot
|
|
31
|
+
self._already_processed = False
|
|
32
|
+
|
|
33
|
+
def process_with_gpt(self, custom_message=None) -> None:
|
|
34
|
+
"""
|
|
35
|
+
Process this message with GPT
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
custom_message: Optional custom message to send to GPT instead of the original message
|
|
39
|
+
"""
|
|
40
|
+
if not self.gpt_bot:
|
|
41
|
+
logger.warning("Cannot process with GPT: No GPT bot reference available")
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
if self._already_processed:
|
|
45
|
+
logger.debug("Skipping duplicate GPT processing")
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
logger.debug(f"Processing message from {self.sender} with GPT (handler requested)")
|
|
49
|
+
self._already_processed = True
|
|
50
|
+
|
|
51
|
+
if custom_message is not None:
|
|
52
|
+
modified_event = self.event.copy()
|
|
53
|
+
|
|
54
|
+
if 'messageData' in modified_event:
|
|
55
|
+
if modified_event['messageData']['typeMessage'] == 'textMessage':
|
|
56
|
+
modified_event['messageData']['textMessageData']['textMessage'] = custom_message
|
|
57
|
+
elif modified_event['messageData']['typeMessage'] in ['extendedTextMessage', 'quotedMessage']:
|
|
58
|
+
modified_event['messageData']['extendedTextMessageData']['text'] = custom_message
|
|
59
|
+
|
|
60
|
+
custom_notification = BaseNotification(
|
|
61
|
+
modified_event,
|
|
62
|
+
self.api,
|
|
63
|
+
self.state_manager
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
self.gpt_bot._process_with_gpt(custom_notification)
|
|
67
|
+
else:
|
|
68
|
+
self.gpt_bot._process_with_gpt(self)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utility functions for WhatsApp GPT Bot
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .media import download_media, transcribe_audio
|
|
6
|
+
from .conversation import trim_conversation_history, estimate_tokens
|
|
7
|
+
from .router import setup_router_integration
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Utils:
|
|
11
|
+
"""Unified utility class providing access to all utility functions"""
|
|
12
|
+
|
|
13
|
+
@staticmethod
|
|
14
|
+
async def download_media(url):
|
|
15
|
+
"""Download media from URL to a temporary file"""
|
|
16
|
+
return await download_media(url)
|
|
17
|
+
|
|
18
|
+
@staticmethod
|
|
19
|
+
async def transcribe_audio(file_path, openai_client):
|
|
20
|
+
"""Transcribe audio using OpenAI Whisper API"""
|
|
21
|
+
return await transcribe_audio(file_path, openai_client)
|
|
22
|
+
|
|
23
|
+
@staticmethod
|
|
24
|
+
def trim_conversation_history(messages, max_messages, preserve_system=True):
|
|
25
|
+
"""Trim conversation history while preserving system message"""
|
|
26
|
+
return trim_conversation_history(messages, max_messages, preserve_system)
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def estimate_tokens(messages):
|
|
30
|
+
"""Estimate the number of tokens in a message list"""
|
|
31
|
+
return estimate_tokens(messages)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Conversation management utilities
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import List, Dict, Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def trim_conversation_history(
|
|
9
|
+
messages: List[Dict[str, Any]],
|
|
10
|
+
max_messages: int,
|
|
11
|
+
preserve_system: bool = True
|
|
12
|
+
) -> List[Dict[str, Any]]:
|
|
13
|
+
"""
|
|
14
|
+
Trim conversation history to the specified number of messages
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
messages: List of conversation messages
|
|
18
|
+
max_messages: Maximum number of messages to keep
|
|
19
|
+
preserve_system: Whether to preserve system message
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
Trimmed list of messages
|
|
23
|
+
"""
|
|
24
|
+
if len(messages) <= max_messages:
|
|
25
|
+
return messages
|
|
26
|
+
|
|
27
|
+
if preserve_system and messages and messages[0].get("role") == "system":
|
|
28
|
+
return [messages[0]] + messages[-(max_messages - 1):]
|
|
29
|
+
else:
|
|
30
|
+
return messages[-max_messages:]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def estimate_tokens(messages: List[Dict[str, Any]]) -> int:
|
|
34
|
+
"""
|
|
35
|
+
Estimate the number of tokens in a conversation (rough estimation)
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
messages: List of conversation messages
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
Estimated token count
|
|
42
|
+
"""
|
|
43
|
+
total = 0
|
|
44
|
+
for message in messages:
|
|
45
|
+
content = message.get("content", "")
|
|
46
|
+
# Very rough estimation: 1 token ~= 4 characters
|
|
47
|
+
if isinstance(content, str):
|
|
48
|
+
total += len(content) // 4
|
|
49
|
+
elif isinstance(content, list):
|
|
50
|
+
for item in content:
|
|
51
|
+
if isinstance(item, dict) and "text" in item:
|
|
52
|
+
total += len(item["text"]) // 4
|
|
53
|
+
if isinstance(item, dict) and "image_url" in item:
|
|
54
|
+
total += 50 # Rough estimate for image presence
|
|
55
|
+
|
|
56
|
+
return total
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Media handling utilities
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def download_media(url: str) -> str:
|
|
11
|
+
"""
|
|
12
|
+
Download media from URL to a temporary file
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
url: URL to download from
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
Path to the downloaded file
|
|
19
|
+
|
|
20
|
+
Raises:
|
|
21
|
+
Exception: If download fails
|
|
22
|
+
"""
|
|
23
|
+
response = requests.get(url)
|
|
24
|
+
if response.status_code != 200:
|
|
25
|
+
raise Exception(f"Failed to download: {response.status_code}")
|
|
26
|
+
|
|
27
|
+
fd, temp_path = tempfile.mkstemp(suffix=".tmp")
|
|
28
|
+
with os.fdopen(fd, 'wb') as f:
|
|
29
|
+
f.write(response.content)
|
|
30
|
+
|
|
31
|
+
return temp_path
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def transcribe_audio(file_path: str, openai_client) -> str:
|
|
35
|
+
"""
|
|
36
|
+
Transcribe audio using OpenAI Whisper API
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
file_path: Path to the audio file
|
|
40
|
+
openai_client: OpenAI client instance
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Transcribed text
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
Exception: If transcription fails
|
|
47
|
+
"""
|
|
48
|
+
with open(file_path, "rb") as audio_file:
|
|
49
|
+
transcription = openai_client.audio.transcriptions.create(
|
|
50
|
+
file=audio_file,
|
|
51
|
+
model="whisper-1"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return transcription.text
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Router integration utilities
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from whatsapp_chatbot_python import Notification as BaseNotification
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger('whatsapp_chatgpt_python')
|
|
9
|
+
_logger_configured = False
|
|
10
|
+
|
|
11
|
+
def setup_router_integration(bot):
|
|
12
|
+
"""
|
|
13
|
+
Set up router integration for the WhatsappGptBot
|
|
14
|
+
|
|
15
|
+
This function adds tracking of handler execution and implements
|
|
16
|
+
GPT processing based on whether handlers matched.
|
|
17
|
+
|
|
18
|
+
Logic:
|
|
19
|
+
1. If no handler handles a message, process with GPT
|
|
20
|
+
2. If a handler handles a message, don't process with GPT by default
|
|
21
|
+
3. A handler can explicitly request GPT processing by calling process_with_gpt()
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
bot: The WhatsappGptBot instance
|
|
25
|
+
"""
|
|
26
|
+
from ..notification import ExtendedNotification
|
|
27
|
+
|
|
28
|
+
global _logger_configured
|
|
29
|
+
if not _logger_configured:
|
|
30
|
+
for handler in logger.handlers[:]:
|
|
31
|
+
logger.removeHandler(handler)
|
|
32
|
+
_logger_configured = True
|
|
33
|
+
|
|
34
|
+
original_propagate_event = bot.router.message.propagate_event
|
|
35
|
+
|
|
36
|
+
handled_messages = {}
|
|
37
|
+
processed_messages = {}
|
|
38
|
+
|
|
39
|
+
def notification_process_with_gpt(self, custom_message=None):
|
|
40
|
+
"""
|
|
41
|
+
Request GPT processing for this notification
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
custom_message: Optional custom message to process instead of the original
|
|
45
|
+
"""
|
|
46
|
+
if not hasattr(self, 'sender'):
|
|
47
|
+
logger.warning("Cannot process with GPT: notification has no sender attribute")
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
if self.sender in processed_messages:
|
|
51
|
+
processed_messages[self.sender] = True
|
|
52
|
+
|
|
53
|
+
if custom_message is not None:
|
|
54
|
+
if not hasattr(bot, 'process_chat_sync'):
|
|
55
|
+
logger.warning("Cannot process with GPT: bot has no process_chat_sync method")
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
modified_notification = BaseNotification(
|
|
59
|
+
self.event.copy(), # Make a copy to avoid modifying the original
|
|
60
|
+
self.api,
|
|
61
|
+
self.state_manager
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
bot._process_with_gpt(modified_notification)
|
|
65
|
+
else:
|
|
66
|
+
bot._process_with_gpt(self)
|
|
67
|
+
|
|
68
|
+
original_process_with_gpt = getattr(BaseNotification, "process_with_gpt", None)
|
|
69
|
+
|
|
70
|
+
if not hasattr(BaseNotification, "process_with_gpt"):
|
|
71
|
+
BaseNotification.process_with_gpt = notification_process_with_gpt
|
|
72
|
+
|
|
73
|
+
def propagate_event_wrapper():
|
|
74
|
+
chat_id = None
|
|
75
|
+
if bot.router.message.event and 'senderData' in bot.router.message.event:
|
|
76
|
+
chat_id = bot.router.message.event['senderData'].get('chatId')
|
|
77
|
+
|
|
78
|
+
if chat_id:
|
|
79
|
+
handled_messages[chat_id] = False
|
|
80
|
+
processed_messages[chat_id] = False
|
|
81
|
+
|
|
82
|
+
from whatsapp_chatbot_python.manager.handler import Handler
|
|
83
|
+
original_execute_handler = Handler.execute_handler
|
|
84
|
+
|
|
85
|
+
def execute_handler_wrapper(self, observer):
|
|
86
|
+
notification = BaseNotification(
|
|
87
|
+
observer.event, observer.router.api, observer.state_manager
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
should_handle = self.check_event(notification)
|
|
91
|
+
if not should_handle:
|
|
92
|
+
logger.debug("Event does not match filters.")
|
|
93
|
+
return False
|
|
94
|
+
|
|
95
|
+
ext_notification = ExtendedNotification(
|
|
96
|
+
observer.event, observer.router.api, observer.state_manager,
|
|
97
|
+
gpt_bot=bot
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
if notification.chat and notification.chat in handled_messages:
|
|
101
|
+
handled_messages[notification.chat] = True
|
|
102
|
+
|
|
103
|
+
logger.debug("Event matches filters. Handling event.")
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
self.handler(ext_notification)
|
|
107
|
+
|
|
108
|
+
if notification.chat and notification.chat in processed_messages:
|
|
109
|
+
if hasattr(ext_notification, '_already_processed'):
|
|
110
|
+
processed_messages[notification.chat] = ext_notification._already_processed
|
|
111
|
+
except Exception as e:
|
|
112
|
+
logger.error(f"Error in handler: {e}", exc_info=True)
|
|
113
|
+
|
|
114
|
+
return True
|
|
115
|
+
|
|
116
|
+
for handler in bot.router.message.handlers:
|
|
117
|
+
handler.__class__.execute_handler = execute_handler_wrapper
|
|
118
|
+
|
|
119
|
+
original_propagate_event()
|
|
120
|
+
|
|
121
|
+
for handler in bot.router.message.handlers:
|
|
122
|
+
handler.__class__.execute_handler = original_execute_handler
|
|
123
|
+
|
|
124
|
+
if chat_id:
|
|
125
|
+
was_handled = handled_messages.get(chat_id, False)
|
|
126
|
+
already_processed = processed_messages.get(chat_id, False)
|
|
127
|
+
|
|
128
|
+
if not was_handled and not already_processed:
|
|
129
|
+
logger.debug(f"Processing unhandled message from {chat_id} with GPT")
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
notification = BaseNotification(
|
|
133
|
+
bot.router.message.event,
|
|
134
|
+
bot.router.api,
|
|
135
|
+
bot.router.message.state_manager
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
bot._process_with_gpt(notification)
|
|
139
|
+
except Exception as e:
|
|
140
|
+
logger.error(f"Error processing message with GPT: {e}", exc_info=True)
|
|
141
|
+
|
|
142
|
+
if chat_id in handled_messages:
|
|
143
|
+
del handled_messages[chat_id]
|
|
144
|
+
if chat_id in processed_messages:
|
|
145
|
+
del processed_messages[chat_id]
|
|
146
|
+
|
|
147
|
+
bot.router.message.propagate_event = propagate_event_wrapper
|
|
148
|
+
|
|
149
|
+
def cleanup():
|
|
150
|
+
bot.router.message.propagate_event = original_propagate_event
|
|
151
|
+
|
|
152
|
+
if original_process_with_gpt:
|
|
153
|
+
BaseNotification.process_with_gpt = original_process_with_gpt
|
|
154
|
+
elif hasattr(BaseNotification, "process_with_gpt"):
|
|
155
|
+
delattr(BaseNotification, "process_with_gpt")
|
|
156
|
+
|
|
157
|
+
bot._cleanup_router = cleanup
|
|
158
|
+
|
|
159
|
+
logger.info("GPT router integration setup completed")
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Green API
|
|
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.
|