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,111 @@
1
+ """
2
+ Image message handler
3
+ """
4
+
5
+ import logging
6
+ import os
7
+ from typing import Union, List, Dict, Any
8
+ from whatsapp_chatbot_python import Notification
9
+ from .base import MessageHandler
10
+ from ..config import is_image_capable_model
11
+
12
+ logger = logging.getLogger('whatsapp_chatgpt_python.handlers.image')
13
+
14
+
15
+ class ImageMessageHandler(MessageHandler):
16
+ SUPPORTED_FORMATS = ['png', 'jpg', 'jpeg', 'gif', 'webp']
17
+
18
+ def can_handle(self, notification: Notification) -> bool:
19
+ """
20
+ Check if this handler can process the message
21
+
22
+ Args:
23
+ notification: The notification object
24
+
25
+ Returns:
26
+ True if this is an image message
27
+ """
28
+ message_type = self.get_message_type(notification)
29
+ logger.debug(f"ImageMessageHandler checking message type: '{message_type}'")
30
+ return message_type == "imageMessage"
31
+
32
+ def _is_supported_format(self, file_name: str, mime_type: str) -> bool:
33
+ if file_name:
34
+ extension = os.path.splitext(file_name)[1].lower().lstrip('.')
35
+ if extension not in self.SUPPORTED_FORMATS:
36
+ return False
37
+
38
+ if mime_type:
39
+ mime_parts = mime_type.lower().split('/')
40
+ if len(mime_parts) == 2:
41
+ if mime_parts[0] == 'image':
42
+ sub_type = mime_parts[1]
43
+ if sub_type in self.SUPPORTED_FORMATS or sub_type == 'jpg':
44
+ return True
45
+
46
+ if not file_name and mime_type:
47
+ return True
48
+
49
+ if file_name:
50
+ extension = os.path.splitext(file_name)[1].lower().lstrip('.')
51
+ return extension in self.SUPPORTED_FORMATS
52
+
53
+ return False
54
+
55
+ async def process_message(
56
+ self,
57
+ notification: Notification,
58
+ openai_client=None,
59
+ model=None
60
+ ) -> Union[str, List[Dict[str, Any]]]:
61
+ """
62
+ Process the image message with format validation
63
+
64
+ Args:
65
+ notification: The notification object
66
+ openai_client: OpenAI client instance
67
+ model: Model name to check image capability
68
+
69
+ Returns:
70
+ For vision-capable models: A list of content items (text + image) if format is supported
71
+ For other models or unsupported formats: A text description of the image
72
+ """
73
+ supports_images = is_image_capable_model(model) if model else False
74
+ logger.debug(f"Processing image with model {model}, supports images: {supports_images}")
75
+
76
+ message_data = notification.get_message_data()
77
+ logger.debug(f"Image message data: {message_data and 'fileMessageData' in message_data}")
78
+
79
+ if not message_data or "fileMessageData" not in message_data:
80
+ return "[The user sent an image but I couldn't access it]"
81
+
82
+ file_data = message_data.get("fileMessageData", {})
83
+ download_url = file_data.get("downloadUrl", "")
84
+ caption = file_data.get("caption", "")
85
+ file_name = file_data.get("fileName", "")
86
+ mime_type = file_data.get("mimeType", "")
87
+
88
+ logger.debug(
89
+ f"Image details - URL: {bool(download_url)}, Caption: '{caption}', File: '{file_name}', MIME: '{mime_type}'")
90
+
91
+ if not download_url:
92
+ return "[The user sent an image but I couldn't access it]"
93
+
94
+ is_supported = self._is_supported_format(file_name, mime_type)
95
+ logger.debug(f"Image format supported by OpenAI: {is_supported}")
96
+
97
+ if not supports_images or not is_supported:
98
+ reason = ""
99
+ if supports_images and not is_supported:
100
+ reason = " (unsupported format for AI analysis)"
101
+
102
+ caption_text = f' with caption: "{caption}"' if caption else ""
103
+ file_text = f' ({file_name})' if file_name else ""
104
+
105
+ return f"[The user sent an image{file_text}{caption_text}{reason}]"
106
+
107
+ logger.debug("Returning multimodal content for vision model")
108
+ return [
109
+ {"type": "text", "text": caption if caption else "Analyzing this image"},
110
+ {"type": "image_url", "image_url": {"url": download_url}}
111
+ ]
@@ -0,0 +1,45 @@
1
+ """
2
+ Location message handler
3
+ """
4
+
5
+ from whatsapp_chatbot_python import Notification
6
+ from .base import MessageHandler
7
+
8
+ class LocationMessageHandler(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 location message
18
+ """
19
+ message_type = self.get_message_type(notification)
20
+ return message_type == "locationMessage"
21
+
22
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
23
+ """
24
+ Process the location message
25
+
26
+ Args:
27
+ notification: The notification object
28
+
29
+ Returns:
30
+ A text description of the location
31
+ """
32
+ message_data = notification.get_message_data()
33
+ if not message_data or "locationMessageData" not in message_data:
34
+ return "[The user shared a location but I couldn't access it]"
35
+
36
+ location_data = message_data.get("locationMessageData", {})
37
+ name = location_data.get("nameLocation", "unnamed location")
38
+ address = location_data.get("address", "")
39
+ latitude = location_data.get("latitude", 0)
40
+ longitude = location_data.get("longitude", 0)
41
+
42
+ address_text = f" ({address})" if address else ""
43
+ coords = f"{latitude}, {longitude}"
44
+
45
+ return f"[The user shared a location: \"{name}\"{address_text} at coordinates: {coords}]"
@@ -0,0 +1,69 @@
1
+ """
2
+ Poll message handler
3
+ """
4
+
5
+ from whatsapp_chatbot_python import Notification
6
+ from .base import MessageHandler
7
+
8
+ class PollMessageHandler(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 poll message
18
+ """
19
+ message_type = self.get_message_type(notification)
20
+ return message_type in ["pollMessage", "pollUpdateMessage"]
21
+
22
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
23
+ """
24
+ Process the poll message
25
+
26
+ Args:
27
+ notification: The notification object
28
+
29
+ Returns:
30
+ A text description of the poll
31
+ """
32
+ message_data = notification.get_message_data()
33
+ if not message_data:
34
+ return "[The user interacted with a poll but I couldn't access it]"
35
+
36
+ message_type = message_data.get("typeMessage", "")
37
+
38
+ if message_type == "pollMessage":
39
+ poll_data = message_data.get("pollMessageData", {})
40
+ if not poll_data:
41
+ return "[The user created a poll but I couldn't access it]"
42
+
43
+ name = poll_data.get("name", "unnamed poll")
44
+ options = poll_data.get("options", [])
45
+ option_names = [opt.get("optionName", "") for opt in options if "optionName" in opt]
46
+
47
+ options_text = ", ".join(f'"{opt}"' for opt in option_names) if option_names else "no options"
48
+
49
+ return f"[The user created a poll: \"{name}\" with options: {options_text}]"
50
+
51
+ elif message_type == "pollUpdateMessage":
52
+ poll_update_data = message_data.get("pollMessageData", {})
53
+ if not poll_update_data:
54
+ return "[The user voted in a poll but I couldn't access the details]"
55
+
56
+ poll_name = poll_update_data.get("name", "unnamed poll")
57
+ votes = poll_update_data.get("votes", [])
58
+
59
+ vote_info = []
60
+ for vote in votes:
61
+ voters = len(vote.get("optionVoters", []))
62
+ option_name = vote.get("optionName", "unknown option")
63
+ vote_info.append(f'"{option_name}" ({voters} vote{"s" if voters != 1 else ""})')
64
+
65
+ vote_text = ", ".join(vote_info) if vote_info else "no votes"
66
+
67
+ return f"[The user voted in poll: \"{poll_name}\" with results: {vote_text}]"
68
+
69
+ return "[The user interacted with a poll]"
@@ -0,0 +1,128 @@
1
+ """
2
+ Message handler registry
3
+ """
4
+
5
+ import logging
6
+ import asyncio
7
+ from typing import List, Any, Type
8
+ from whatsapp_chatbot_python import Notification
9
+
10
+ from .base import MessageHandler, FallbackMessageHandler
11
+ from .text import TextMessageHandler
12
+ from .image import ImageMessageHandler
13
+ from .audio import AudioMessageHandler
14
+ from .video import VideoMessageHandler
15
+ from .document import DocumentMessageHandler
16
+ from .location import LocationMessageHandler
17
+ from .contact import ContactMessageHandler
18
+ from .poll import PollMessageHandler
19
+
20
+ logger = logging.getLogger('whatsapp_chatgpt_python.handlers')
21
+
22
+ class MessageHandlerRegistry:
23
+ def __init__(self, openai_client, model):
24
+ """
25
+ Initialize the message handler registry
26
+
27
+ Args:
28
+ openai_client: OpenAI client instance
29
+ model: Model name
30
+ """
31
+ self.handlers: List[MessageHandler] = []
32
+ self.openai_client = openai_client
33
+ self.model = model
34
+ self.register_default_handlers()
35
+
36
+ def register_default_handlers(self):
37
+ """Register the default set of message handlers"""
38
+ self.handlers = [
39
+ TextMessageHandler(),
40
+ ImageMessageHandler(),
41
+ AudioMessageHandler(),
42
+ VideoMessageHandler(),
43
+ DocumentMessageHandler(),
44
+ LocationMessageHandler(),
45
+ ContactMessageHandler(),
46
+ PollMessageHandler(),
47
+ FallbackMessageHandler()
48
+ ]
49
+
50
+ def register_handler(self, handler: MessageHandler, index: int = None):
51
+ """
52
+ Register a custom message handler
53
+
54
+ Args:
55
+ handler: The handler to register
56
+ index: Optional position to insert the handler (default: before fallback)
57
+ """
58
+ if index is not None:
59
+ self.handlers.insert(index, handler)
60
+ else:
61
+ self.handlers.insert(len(self.handlers) - 1, handler)
62
+
63
+ def replace_handler(self, handler_type: Type[MessageHandler], new_handler: MessageHandler) -> bool:
64
+ """
65
+ Replace a handler of a specific type with a new handler
66
+
67
+ Args:
68
+ handler_type: The handler class to replace
69
+ new_handler: The new handler instance
70
+
71
+ Returns:
72
+ True if replacement succeeded, False otherwise
73
+ """
74
+ for i, handler in enumerate(self.handlers):
75
+ if isinstance(handler, handler_type):
76
+ self.handlers[i] = new_handler
77
+ return True
78
+ return False
79
+
80
+ async def process_message(self, notification: Notification) -> Any:
81
+ """
82
+ Process a message using the appropriate handler (async version)
83
+
84
+ Args:
85
+ notification: The notification object
86
+
87
+ Returns:
88
+ Processed message content
89
+ """
90
+ message_type = ""
91
+ for handler in self.handlers:
92
+ try:
93
+ message_type = handler.get_message_type(notification)
94
+ if handler.can_handle(notification):
95
+ logger.debug(f"Using handler {handler.__class__.__name__} for message type {message_type}")
96
+
97
+ if isinstance(handler, ImageMessageHandler):
98
+ return await handler.process_message(notification, self.openai_client, self.model)
99
+
100
+ return await handler.process_message(notification, self.openai_client)
101
+ except Exception as e:
102
+ logger.error(f"Error in handler {handler.__class__.__name__}: {e}", exc_info=True)
103
+ continue
104
+
105
+ logger.warning(f"No handler matched message type '{message_type}', using fallback")
106
+
107
+ fallback = self.handlers[-1]
108
+ return await fallback.process_message(notification, self.openai_client)
109
+
110
+ def process_message_sync(self, notification: Notification) -> Any:
111
+ """
112
+ Process a message using the appropriate handler (sync version)
113
+
114
+ Args:
115
+ notification: The notification object
116
+
117
+ Returns:
118
+ Processed message content
119
+ """
120
+ try:
121
+ loop = asyncio.new_event_loop()
122
+ asyncio.set_event_loop(loop)
123
+ result = loop.run_until_complete(self.process_message(notification))
124
+ loop.close()
125
+ return result
126
+ except Exception as e:
127
+ logger.error(f"Error in process_message_sync: {e}", exc_info=True)
128
+ return "[Error processing message]"
@@ -0,0 +1,32 @@
1
+ """
2
+ Text message handler
3
+ """
4
+
5
+ from whatsapp_chatbot_python import Notification
6
+ from .base import MessageHandler
7
+
8
+ class TextMessageHandler(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 text or extended text message
18
+ """
19
+ message_type = self.get_message_type(notification)
20
+ return message_type in ["textMessage", "extendedTextMessage"]
21
+
22
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
23
+ """
24
+ Process the message and return the text content
25
+
26
+ Args:
27
+ notification: The notification object
28
+
29
+ Returns:
30
+ The message text or "Empty message" if none
31
+ """
32
+ return notification.message_text or "Empty message"
@@ -0,0 +1,43 @@
1
+ """
2
+ Video message handler
3
+ """
4
+
5
+ from whatsapp_chatbot_python import Notification
6
+ from .base import MessageHandler
7
+
8
+ class VideoMessageHandler(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 video message
18
+ """
19
+ message_type = self.get_message_type(notification)
20
+ return message_type == "videoMessage"
21
+
22
+ async def process_message(self, notification: Notification, *args, **kwargs) -> str:
23
+ """
24
+ Process the video message
25
+
26
+ Args:
27
+ notification: The notification object
28
+
29
+ Returns:
30
+ A text description of the video
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 video but I couldn't access it]"
35
+
36
+ file_data = message_data.get("fileMessageData", {})
37
+ file_name = file_data.get("fileName", "")
38
+ caption = file_data.get("caption", "")
39
+
40
+ caption_text = f' with caption: "{caption}"' if caption else ""
41
+ file_text = f' ({file_name})' if file_name else ""
42
+
43
+ return f"[The user sent a video{file_text}{caption_text}]"
@@ -0,0 +1,36 @@
1
+ """
2
+ Logger utilities to prevent duplicate log handlers
3
+ """
4
+ import logging
5
+
6
+ _CONFIGURED_LOGGERS = set()
7
+
8
+
9
+ def get_logger(name):
10
+ """
11
+ Get a logger with a single handler to prevent duplication
12
+
13
+ Args:
14
+ name: Name of the logger to configure
15
+
16
+ Returns:
17
+ Configured logger instance
18
+ """
19
+ logger = logging.getLogger(name)
20
+
21
+ if name in _CONFIGURED_LOGGERS:
22
+ return logger
23
+
24
+ for handler in logger.handlers[:]:
25
+ logger.removeHandler(handler)
26
+
27
+ handler = logging.StreamHandler()
28
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
29
+ handler.setFormatter(formatter)
30
+ logger.addHandler(handler)
31
+
32
+ logger.propagate = False
33
+
34
+ _CONFIGURED_LOGGERS.add(name)
35
+
36
+ return logger
@@ -0,0 +1,6 @@
1
+ """
2
+ Middleware components for WhatsApp GPT Bot
3
+ """
4
+
5
+ from .base import ProcessMessageMiddleware, ProcessResponseMiddleware
6
+ from .manager import MiddlewareManager
@@ -0,0 +1,55 @@
1
+ """
2
+ Base middleware types
3
+ """
4
+
5
+ from typing import Protocol, Dict, List, Any, TypeVar
6
+ from whatsapp_chatbot_python import Notification
7
+ from ..models import GPTSessionData
8
+
9
+ MessageContent = Any
10
+ Messages = List[Dict[str, Any]]
11
+ T = TypeVar('T')
12
+
13
+
14
+ class ProcessMessageMiddleware(Protocol):
15
+ """
16
+ Protocol for message processing middleware
17
+
18
+ Args:
19
+ notification (Notification): The notification object
20
+ message_content (Any): The processed message content
21
+ messages (List[Dict[str, Any]]): The current conversation history
22
+ session_data (GPTSessionData): The session data
23
+
24
+ Returns:
25
+ Dict[str, Any]: Dict with updated message_content and messages
26
+ """
27
+
28
+ def __call__(
29
+ self,
30
+ notification: Notification,
31
+ message_content: MessageContent,
32
+ messages: Messages,
33
+ session_data: GPTSessionData
34
+ ) -> Dict[str, Any]: ...
35
+
36
+
37
+ class ProcessResponseMiddleware(Protocol):
38
+ """
39
+ Protocol for response processing middleware
40
+
41
+ Args:
42
+ response: The response text from OpenAI
43
+ messages: The current conversation history
44
+ session_data: The session data
45
+
46
+ Returns:
47
+ Dict with updated response and messages
48
+ """
49
+
50
+ def __call__(
51
+ self,
52
+ response: str,
53
+ messages: Messages,
54
+ session_data: GPTSessionData
55
+ ) -> Dict[str, Any]: ...
@@ -0,0 +1,111 @@
1
+ """
2
+ Middleware manager
3
+ """
4
+
5
+ import logging
6
+ from typing import List, Dict, Any
7
+
8
+ from whatsapp_chatbot_python import Notification
9
+ from .base import ProcessMessageMiddleware, ProcessResponseMiddleware
10
+ from ..models import GPTSessionData
11
+
12
+ logger = logging.getLogger('whatsapp_chatgpt_python.middleware')
13
+
14
+
15
+ class MiddlewareManager:
16
+ def __init__(self):
17
+ self.message_middlewares: List[ProcessMessageMiddleware] = []
18
+ self.response_middlewares: List[ProcessResponseMiddleware] = []
19
+
20
+ def add_message_middleware(self, middleware: ProcessMessageMiddleware) -> None:
21
+ """
22
+ Add middleware to process messages before sending to OpenAI
23
+
24
+ Args:
25
+ middleware: The middleware function to add
26
+ """
27
+ self.message_middlewares.append(middleware)
28
+
29
+ def add_response_middleware(self, middleware: ProcessResponseMiddleware) -> None:
30
+ """
31
+ Add middleware to process responses before sending to the user
32
+
33
+ Args:
34
+ middleware: The middleware function to add
35
+ """
36
+ self.response_middlewares.append(middleware)
37
+
38
+ def process_message(
39
+ self,
40
+ notification: Notification,
41
+ message_content: Any,
42
+ messages: List[Dict[str, Any]],
43
+ session_data: GPTSessionData
44
+ ) -> Dict[str, Any]:
45
+ """
46
+ Process a message through all message middlewares
47
+
48
+ Args:
49
+ notification: The notification object
50
+ message_content: The initial message content
51
+ messages: The current conversation history
52
+ session_data: The session data
53
+
54
+ Returns:
55
+ Dict with processed message_content and messages
56
+ """
57
+ result = {
58
+ "message_content": message_content,
59
+ "messages": messages.copy() # Copy to avoid modifying the original
60
+ }
61
+
62
+ for middleware in self.message_middlewares:
63
+ try:
64
+ middleware_result = middleware(
65
+ notification,
66
+ result["message_content"],
67
+ result["messages"],
68
+ session_data
69
+ )
70
+ if middleware_result:
71
+ result = middleware_result
72
+ except Exception as e:
73
+ logger.error(f"Error in message middleware: {e}", exc_info=True)
74
+
75
+ return result
76
+
77
+ def process_response(
78
+ self,
79
+ response: str,
80
+ messages: List[Dict[str, Any]],
81
+ session_data: GPTSessionData
82
+ ) -> Dict[str, Any]:
83
+ """
84
+ Process a response through all response middlewares
85
+
86
+ Args:
87
+ response: The initial response from OpenAI
88
+ messages: The current conversation history
89
+ session_data: The session data
90
+
91
+ Returns:
92
+ Dict with processed response and messages
93
+ """
94
+ result = {
95
+ "response": response,
96
+ "messages": messages.copy() # Copy to avoid modifying the original
97
+ }
98
+
99
+ for middleware in self.response_middlewares:
100
+ try:
101
+ middleware_result = middleware(
102
+ result["response"],
103
+ result["messages"],
104
+ session_data
105
+ )
106
+ if middleware_result:
107
+ result = middleware_result
108
+ except Exception as e:
109
+ logger.error(f"Error in response middleware: {e}", exc_info=True)
110
+
111
+ return result
@@ -0,0 +1,19 @@
1
+ """
2
+ Data models
3
+ """
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import List, Dict, Any
7
+ import time
8
+
9
+
10
+ @dataclass
11
+ class GPTSessionData:
12
+ """Session data for GPT conversations"""
13
+ messages: List[Dict[str, Any]] = field(default_factory=list)
14
+ last_activity: int = field(default_factory=lambda: int(time.time()))
15
+ user_data: Dict[str, Any] = field(default_factory=dict)
16
+ context: Dict[str, Any] = field(default_factory=dict)
17
+
18
+ def update_activity(self):
19
+ self.last_activity = int(time.time())