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.
@@ -0,0 +1,35 @@
1
+ """
2
+ WhatsApp GPT Bot
3
+ A Python library for creating WhatsApp bots integrated with OpenAI GPT models.
4
+ Built on top of whatsapp-chatbot-python and GREEN-API.
5
+ """
6
+
7
+ from .bot import WhatsappGptBot
8
+ from .models import GPTSessionData
9
+ from .notification import ExtendedNotification
10
+ from .config import (
11
+ DEFAULT_MODEL,
12
+ GPT4_MODELS,
13
+ GPT4O_MODELS,
14
+ GPT35_MODELS,
15
+ O1_MODELS,
16
+ IMAGE_CAPABLE_MODELS,
17
+ ALL_MODELS,
18
+ is_image_capable_model
19
+ )
20
+ from .handlers import (
21
+ MessageHandler,
22
+ TextMessageHandler,
23
+ ImageMessageHandler,
24
+ AudioMessageHandler,
25
+ VideoMessageHandler,
26
+ DocumentMessageHandler,
27
+ LocationMessageHandler,
28
+ ContactMessageHandler,
29
+ PollMessageHandler,
30
+ FallbackMessageHandler
31
+ )
32
+ from .middleware import MiddlewareManager
33
+ from .utils import Utils
34
+
35
+ __version__ = "0.1.0"
@@ -0,0 +1,292 @@
1
+ """
2
+ Main WhatsApp GPT Bot class
3
+ """
4
+ import logging
5
+ import time
6
+ from typing import Dict, Type, Callable
7
+ import openai
8
+ from whatsapp_chatbot_python import GreenAPIBot, Notification
9
+
10
+ from .config import DEFAULT_MODEL, ALL_MODELS, is_image_capable_model
11
+ from .models import GPTSessionData
12
+ from .middleware import MiddlewareManager
13
+ from .handlers import MessageHandler, MessageHandlerRegistry
14
+ from .utils.router import setup_router_integration
15
+
16
+ logger = logging.getLogger('whatsapp_chatgpt_python')
17
+
18
+
19
+ class WhatsappGptBot(GreenAPIBot):
20
+ """WhatsApp bot with GPT integration"""
21
+
22
+ def __init__(
23
+ self,
24
+ id_instance: str,
25
+ api_token_instance: str,
26
+ openai_api_key: str,
27
+ model: str = DEFAULT_MODEL,
28
+ max_history_length: int = 10,
29
+ system_message: str = "",
30
+ temperature: float = 0.5,
31
+ error_message: str = "Sorry, I encountered an error processing your message. Please try again.",
32
+ session_timeout: int = 1800, # 30 minutes
33
+ **kwargs
34
+ ):
35
+ """
36
+ Initialize the WhatsApp GPT bot
37
+
38
+ Args:
39
+ id_instance: GREEN-API instance ID
40
+ api_token_instance: GREEN-API instance token
41
+ openai_api_key: OpenAI API key
42
+ model: OpenAI model to use (default: gpt-4o)
43
+ max_history_length: Maximum number of messages to keep in history
44
+ system_message: System message to set assistant behavior
45
+ temperature: Temperature for response generation
46
+ error_message: Message to send when an error occurs
47
+ session_timeout: Timeout for inactive sessions in seconds
48
+ **kwargs: Additional arguments to pass to GreenAPIBot
49
+ """
50
+ super().__init__(id_instance, api_token_instance, **kwargs)
51
+
52
+ if model not in ALL_MODELS:
53
+ logger.warning(f"Model {model} not in known models list. Using anyway, but may not work as expected.")
54
+
55
+ self.openai_client = openai.OpenAI(api_key=openai_api_key)
56
+ self.max_history_length = max_history_length
57
+ self.model = model
58
+ self.temperature = temperature
59
+ self.system_message = system_message
60
+ self.error_message = error_message
61
+ self.session_timeout = session_timeout
62
+ self.middleware = MiddlewareManager()
63
+ self.message_handlers = MessageHandlerRegistry(self.openai_client, self.model)
64
+ self.sessions: Dict[str, GPTSessionData] = {}
65
+ self._handled_messages = {}
66
+
67
+ setup_router_integration(self)
68
+
69
+ logger.info(f"WhatsApp GPT Bot initialized with model {model}")
70
+
71
+ def process_chat_sync(self, notification: Notification) -> None:
72
+ """
73
+ Synchronous wrapper for _process_chat to avoid issues with event loops
74
+ """
75
+ chat_id = notification.chat
76
+
77
+ try:
78
+ session_data = self.get_session_data(chat_id)
79
+ message_content = self.message_handlers.process_message_sync(notification)
80
+
81
+ if message_content is None:
82
+ logger.warning("No message content to process")
83
+ return
84
+
85
+ for middleware in self.middleware.message_middlewares:
86
+ try:
87
+ middleware_result = middleware(
88
+ notification, message_content, session_data.messages, session_data
89
+ )
90
+ if middleware_result:
91
+ message_content = middleware_result.get("message_content", message_content)
92
+ session_data.messages = middleware_result.get("messages", session_data.messages)
93
+ except Exception as e:
94
+ logger.error(f"Error in message middleware: {e}", exc_info=True)
95
+
96
+ if isinstance(message_content, str):
97
+ user_message = {
98
+ "role": "user",
99
+ "content": message_content
100
+ }
101
+ elif isinstance(message_content, list):
102
+ user_message = {
103
+ "role": "user",
104
+ "content": message_content
105
+ }
106
+ else:
107
+ logger.warning(f"Unsupported message content type: {type(message_content)}")
108
+ notification.answer(self.error_message)
109
+ return
110
+
111
+ messages = session_data.messages.copy()
112
+ messages.append(user_message)
113
+
114
+ from .utils import Utils
115
+ messages = Utils.trim_conversation_history(
116
+ messages,
117
+ self.max_history_length,
118
+ preserve_system=True
119
+ )
120
+
121
+ session_data.messages = messages
122
+
123
+ response = self.openai_client.chat.completions.create(
124
+ model=self.model,
125
+ messages=messages,
126
+ temperature=self.temperature
127
+ )
128
+
129
+ response_text = response.choices[0].message.content
130
+
131
+ messages.append({
132
+ "role": "assistant",
133
+ "content": response_text
134
+ })
135
+
136
+ # Run response middleware synchronously (no asyncio.run)
137
+ for middleware in self.middleware.response_middlewares:
138
+ try:
139
+ middleware_result = middleware(
140
+ response_text, messages, session_data
141
+ )
142
+ if middleware_result:
143
+ response_text = middleware_result.get("response", response_text)
144
+ except Exception as e:
145
+ logger.error(f"Error in response middleware: {e}", exc_info=True)
146
+
147
+ self.update_session_data(chat_id, session_data)
148
+
149
+ notification.answer(response_text)
150
+
151
+ except Exception as e:
152
+ logger.exception(f"Error processing message: {e}")
153
+ notification.answer(self.error_message)
154
+
155
+ def _process_with_gpt(self, notification: Notification) -> None:
156
+ """
157
+ Process a message with GPT (sync)
158
+ """
159
+ try:
160
+ message_type = ""
161
+ message_data = notification.get_message_data()
162
+ if message_data:
163
+ message_type = message_data.get("typeMessage", "unknown")
164
+
165
+ logger.debug(f"Processing {message_type} message with GPT")
166
+
167
+ self.process_chat_sync(notification)
168
+ except Exception as e:
169
+ logger.error(f"Error in _process_with_gpt: {e}", exc_info=True)
170
+ try:
171
+ notification.answer(self.error_message)
172
+ except Exception:
173
+ logger.error("Failed to send error message", exc_info=True)
174
+
175
+ def add_message_middleware(self, middleware: Callable) -> 'WhatsappGptBot':
176
+ """
177
+ Add middleware to process messages before sending to OpenAI
178
+
179
+ Args:
180
+ middleware: The middleware function
181
+
182
+ Returns:
183
+ Self for method chaining
184
+ """
185
+ self.middleware.add_message_middleware(middleware)
186
+ return self
187
+
188
+ def add_response_middleware(self, middleware: Callable) -> 'WhatsappGptBot':
189
+ """
190
+ Add middleware to process responses before sending to the user
191
+
192
+ Args:
193
+ middleware: The middleware function
194
+
195
+ Returns:
196
+ Self for method chaining
197
+ """
198
+ self.middleware.add_response_middleware(middleware)
199
+ return self
200
+
201
+ def register_message_handler(self, handler: MessageHandler, index: int = None) -> 'WhatsappGptBot':
202
+ """
203
+ Register a custom message handler
204
+
205
+ Args:
206
+ handler: The handler to register
207
+ index: Optional position to insert the handler
208
+
209
+ Returns:
210
+ Self for method chaining
211
+ """
212
+ self.message_handlers.register_handler(handler, index)
213
+ return self
214
+
215
+ def replace_handler(self, handler_class: Type[MessageHandler], new_handler: MessageHandler) -> 'WhatsappGptBot':
216
+ """
217
+ Replace a handler with a new one
218
+
219
+ Args:
220
+ handler_class: The class of handler to replace
221
+ new_handler: The new handler instance
222
+
223
+ Returns:
224
+ Self for method chaining
225
+ """
226
+ self.message_handlers.replace_handler(handler_class, new_handler)
227
+ return self
228
+
229
+ def get_session_data(self, chat_id: str) -> GPTSessionData:
230
+ """
231
+ Get session data for a chat
232
+
233
+ Args:
234
+ chat_id: Chat ID
235
+
236
+ Returns:
237
+ Session data
238
+ """
239
+ if chat_id not in self.sessions:
240
+ self.sessions[chat_id] = GPTSessionData()
241
+
242
+ if self.system_message:
243
+ self.sessions[chat_id].messages.append({
244
+ "role": "system",
245
+ "content": self.system_message
246
+ })
247
+
248
+ self.sessions[chat_id].update_activity()
249
+ return self.sessions[chat_id]
250
+
251
+ def update_session_data(self, chat_id: str, session_data: GPTSessionData) -> None:
252
+ """
253
+ Update session data for a chat
254
+
255
+ Args:
256
+ chat_id: Chat ID
257
+ session_data: New session data
258
+ """
259
+ self.sessions[chat_id] = session_data
260
+
261
+ def cleanup_sessions(self) -> None:
262
+ """
263
+ Remove expired sessions
264
+ """
265
+ current_time = int(time.time())
266
+ expired_chats = []
267
+
268
+ for chat_id, session in self.sessions.items():
269
+ if current_time - session.last_activity > self.session_timeout:
270
+ expired_chats.append(chat_id)
271
+
272
+ for chat_id in expired_chats:
273
+ logger.info(f"Removing expired session for chat {chat_id}")
274
+ del self.sessions[chat_id]
275
+
276
+ def get_model(self) -> str:
277
+ """
278
+ Get the current OpenAI model
279
+
280
+ Returns:
281
+ Model name
282
+ """
283
+ return self.model
284
+
285
+ def supports_images(self) -> bool:
286
+ """
287
+ Check if the current model supports image processing
288
+
289
+ Returns:
290
+ True if the model supports images
291
+ """
292
+ return is_image_capable_model(self.model)
@@ -0,0 +1,33 @@
1
+ """
2
+ Configuration and constants
3
+ """
4
+
5
+ DEFAULT_MODEL = "gpt-4o"
6
+
7
+ GPT4_MODELS = [
8
+ "gpt-4", "gpt-4-turbo", "gpt-4-turbo-preview",
9
+ "gpt-4-1106-preview", "gpt-4-0125-preview", "gpt-4-32k"
10
+ ]
11
+
12
+ GPT4O_MODELS = [
13
+ "gpt-4o", "gpt-4o-mini", "gpt-4o-2024-05-13"
14
+ ]
15
+
16
+ GPT35_MODELS = [
17
+ "gpt-3.5-turbo", "gpt-3.5-turbo-16k",
18
+ "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125"
19
+ ]
20
+
21
+ O1_MODELS = [
22
+ "o1", "o1-mini", "o1-preview"
23
+ ]
24
+
25
+ IMAGE_CAPABLE_MODELS = [
26
+ "gpt-4o", "gpt-4o-mini", "gpt-4-vision-preview",
27
+ "gpt-4-turbo", "gpt-4-turbo-preview"
28
+ ]
29
+
30
+ ALL_MODELS = GPT4_MODELS + GPT4O_MODELS + GPT35_MODELS + O1_MODELS
31
+
32
+ def is_image_capable_model(model: str) -> bool:
33
+ return model in IMAGE_CAPABLE_MODELS
@@ -0,0 +1,15 @@
1
+ """
2
+ Message handlers for WhatsApp GPT Bot
3
+ """
4
+
5
+ from .base import MessageHandler
6
+ from .text import TextMessageHandler
7
+ from .image import ImageMessageHandler
8
+ from .audio import AudioMessageHandler
9
+ from .video import VideoMessageHandler
10
+ from .document import DocumentMessageHandler
11
+ from .location import LocationMessageHandler
12
+ from .contact import ContactMessageHandler
13
+ from .poll import PollMessageHandler
14
+ from .base import FallbackMessageHandler
15
+ from .registry import MessageHandlerRegistry
@@ -0,0 +1,84 @@
1
+ """
2
+ Audio message handler
3
+ """
4
+
5
+ import logging
6
+ import os
7
+ import shutil
8
+
9
+ from whatsapp_chatbot_python import Notification
10
+ from .base import MessageHandler
11
+ from ..utils import Utils
12
+
13
+ logger = logging.getLogger('whatsapp_chatgpt_python.handlers.audio')
14
+
15
+
16
+ class AudioMessageHandler(MessageHandler):
17
+ def can_handle(self, notification: Notification) -> bool:
18
+ """
19
+ Check if this handler can process the message
20
+
21
+ Args:
22
+ notification: The notification object
23
+
24
+ Returns:
25
+ True if this is an audio message
26
+ """
27
+ message_type = self.get_message_type(notification)
28
+ return message_type == "audioMessage"
29
+
30
+ async def process_message(self, notification: Notification, openai_client=None, *args, **kwargs) -> str:
31
+ """
32
+ Process the audio message by transcribing it
33
+
34
+ Args:
35
+ notification: The notification object
36
+ openai_client: OpenAI client for transcription
37
+
38
+ Returns:
39
+ A string with the transcription or error message
40
+ """
41
+ try:
42
+ message_data = notification.get_message_data()
43
+ if not message_data or "fileMessageData" not in message_data:
44
+ return "[The user sent an audio message but I couldn't access it]"
45
+
46
+ file_data = message_data.get("fileMessageData", {})
47
+ download_url = file_data.get("downloadUrl", "")
48
+ mime_type = file_data.get("mimeType", "")
49
+
50
+ if not download_url:
51
+ return "[The user sent an audio message but I couldn't access it]"
52
+
53
+ temp_file = await Utils.download_media(download_url)
54
+
55
+ if not openai_client:
56
+ os.unlink(temp_file)
57
+ return "[The user sent an audio message but transcription is not available]"
58
+
59
+ is_whatsapp_voice = mime_type == "audio/ogg; codecs=opus"
60
+ if is_whatsapp_voice:
61
+ ogg_file = temp_file + ".ogg"
62
+ shutil.copy2(temp_file, ogg_file)
63
+
64
+ try:
65
+ with open(ogg_file, "rb") as audio_file:
66
+ transcription = openai_client.audio.transcriptions.create(
67
+ file=audio_file,
68
+ model="whisper-1"
69
+ )
70
+
71
+ os.unlink(temp_file)
72
+ os.unlink(ogg_file)
73
+
74
+ return f"[The user sent an audio message. Transcription: \"{transcription.text}\"]"
75
+ except Exception as e:
76
+ logger.warning(f"Failed to transcribe WhatsApp voice with .ogg extension: {e}")
77
+ os.unlink(ogg_file)
78
+
79
+ transcription = await Utils.transcribe_audio(temp_file, openai_client)
80
+ os.unlink(temp_file)
81
+ return f"[The user sent an audio message. Transcription: \"{transcription}\"]"
82
+ except Exception as e:
83
+ logger.error(f"Error processing audio: {e}", exc_info=True)
84
+ return "[The user sent an audio message that couldn't be transcribed]"
@@ -0,0 +1,63 @@
1
+ """
2
+ Base message handler class
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any
7
+ from whatsapp_chatbot_python import Notification
8
+
9
+ class MessageHandler(ABC):
10
+ @abstractmethod
11
+ def can_handle(self, notification: Notification) -> bool:
12
+ """
13
+ Check if this handler can process the message
14
+
15
+ Args:
16
+ notification: The notification object
17
+
18
+ Returns:
19
+ True if this handler can process the message, False otherwise
20
+ """
21
+ pass
22
+
23
+ @staticmethod
24
+ def get_message_type(notification: Notification) -> str:
25
+ """
26
+ Extract message type from notification
27
+
28
+ Args:
29
+ notification: The notification object
30
+
31
+ Returns:
32
+ Message type or empty string if not available
33
+ """
34
+ message_data = notification.get_message_data()
35
+ if not message_data:
36
+ return ""
37
+
38
+ return message_data.get("typeMessage", "")
39
+
40
+ @abstractmethod
41
+ async def process_message(self, notification: Notification, openai_client=None, model=None) -> Any:
42
+ """
43
+ Process the message and return content for OpenAI
44
+
45
+ Args:
46
+ notification: The notification object
47
+ openai_client: Optional OpenAI client instance
48
+ model: Optional model name
49
+
50
+ Returns:
51
+ Processed message content for OpenAI
52
+ """
53
+ pass
54
+
55
+ class FallbackMessageHandler(MessageHandler):
56
+ """Fallback handler for any message type not handled by other handlers"""
57
+
58
+ def can_handle(self, notification: Notification) -> bool:
59
+ return True
60
+
61
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
62
+ message_type = self.get_message_type(notification)
63
+ return f"[The user sent a {message_type or 'unknown'} message]"
@@ -0,0 +1,47 @@
1
+ """
2
+ Contact message handler
3
+ """
4
+
5
+ import re
6
+ from whatsapp_chatbot_python import Notification
7
+ from .base import MessageHandler
8
+
9
+ class ContactMessageHandler(MessageHandler):
10
+ def can_handle(self, notification: Notification) -> bool:
11
+ """
12
+ Check if this handler can process the message
13
+
14
+ Args:
15
+ notification: The notification object
16
+
17
+ Returns:
18
+ True if this is a contact message
19
+ """
20
+ message_type = self.get_message_type(notification)
21
+ return message_type == "contactMessage"
22
+
23
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
24
+ """
25
+ Process the contact message
26
+
27
+ Args:
28
+ notification: The notification object
29
+
30
+ Returns:
31
+ A text description of the contact
32
+ """
33
+ message_data = notification.get_message_data()
34
+ if not message_data or "contactMessageData" not in message_data:
35
+ return "[The user shared a contact but I couldn't access it]"
36
+
37
+ contact_data = message_data.get("contactMessageData", {})
38
+ display_name = contact_data.get("displayName", "unknown")
39
+ vcard = contact_data.get("vcard", "")
40
+
41
+ phone_number = None
42
+ if vcard:
43
+ phone_match = re.search(r'TEL(?:;[^:]+)?:([+\d\s-]+)', vcard)
44
+ phone_number = phone_match.group(1) if phone_match else None
45
+
46
+ phone_text = f"\nPhone: {phone_number}" if phone_number else ""
47
+ return f"[The user shared a contact: \"{display_name}\"{phone_text}]"
@@ -0,0 +1,42 @@
1
+ """
2
+ Document message handler
3
+ """
4
+
5
+ from whatsapp_chatbot_python import Notification
6
+ from .base import MessageHandler
7
+
8
+ class DocumentMessageHandler(MessageHandler):
9
+ def can_handle(self, notification: Notification) -> bool:
10
+ """
11
+ Check if this handler can process the message
12
+
13
+ Args:
14
+ notification: The notification object
15
+
16
+ Returns:
17
+ True if this is a document message
18
+ """
19
+ message_type = self.get_message_type(notification)
20
+ return message_type == "documentMessage"
21
+
22
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
23
+ """
24
+ Process the document message
25
+
26
+ Args:
27
+ notification: The notification object
28
+
29
+ Returns:
30
+ A text description of the document
31
+ """
32
+ message_data = notification.get_message_data()
33
+ if not message_data or "fileMessageData" not in message_data:
34
+ return "[The user sent a document but I couldn't access it]"
35
+
36
+ file_data = message_data.get("fileMessageData", {})
37
+ file_name = file_data.get("fileName", "unknown file")
38
+ caption = file_data.get("caption", "")
39
+
40
+ caption_text = f' with caption: "{caption}"' if caption else ""
41
+
42
+ return f"[The user sent a document: \"{file_name}\"{caption_text}]"