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,678 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: whatsapp-chatgpt-python
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A modern WhatsApp bot library with OpenAI GPT integration on Python
|
|
5
|
+
Home-page: https://github.com/green-api/whatsapp-chatgpt-python
|
|
6
|
+
Author: GREEN-API
|
|
7
|
+
Author-email: support@green-api.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.7
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: whatsapp-chatbot-python>=0.9.6
|
|
16
|
+
Requires-Dist: openai>=1.66.3
|
|
17
|
+
Requires-Dist: requests>=2.32.3
|
|
18
|
+
Dynamic: author
|
|
19
|
+
Dynamic: author-email
|
|
20
|
+
Dynamic: classifier
|
|
21
|
+
Dynamic: description
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: license
|
|
25
|
+
Dynamic: requires-dist
|
|
26
|
+
Dynamic: requires-python
|
|
27
|
+
Dynamic: summary
|
|
28
|
+
|
|
29
|
+
# WhatsApp GPT Bot Library for Python
|
|
30
|
+
|
|
31
|
+
- [Документация на русском языке](./README.ru.md)
|
|
32
|
+
|
|
33
|
+
A modern, state-based WhatsApp bot library with OpenAI GPT integration, built on top of whatsapp-chatbot-python and
|
|
34
|
+
GREEN-API.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- OpenAI GPT model integration for intelligent responses
|
|
39
|
+
- Support for multiple GPT models (GPT-3.5, GPT-4, GPT-4o, o1)
|
|
40
|
+
- Multimodal capabilities with image processing support
|
|
41
|
+
- Voice message transcription using Whisper API
|
|
42
|
+
- Comprehensive message handling for various WhatsApp media types
|
|
43
|
+
- Middleware architecture for customizing message and response processing
|
|
44
|
+
- Built-in conversation history management
|
|
45
|
+
- State-based conversation flow inherited from base library
|
|
46
|
+
- Python type hints and comprehensive docstrings
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install whatsapp-chatgpt-python
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The dependencies (`openai`, `whatsapp-chatbot-python`, and `requests`) will be installed automatically.
|
|
55
|
+
|
|
56
|
+
### Prerequisites
|
|
57
|
+
|
|
58
|
+
Before using the bot, you'll need:
|
|
59
|
+
|
|
60
|
+
1. A registered account with [GREEN-API](https://green-api.com/)
|
|
61
|
+
2. An instance ID and API token from your GREEN-API account
|
|
62
|
+
3. An OpenAI API key for GPT access
|
|
63
|
+
|
|
64
|
+
## Quick Start
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from whatsapp_chatgpt_python import WhatsappGptBot
|
|
68
|
+
|
|
69
|
+
# Initialize the bot
|
|
70
|
+
bot = WhatsappGptBot(
|
|
71
|
+
id_instance="your-instance-id",
|
|
72
|
+
api_token_instance="your-api-token",
|
|
73
|
+
openai_api_key="your-openai-api-key",
|
|
74
|
+
model="gpt-4o",
|
|
75
|
+
system_message="You are a helpful assistant."
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Start the bot
|
|
79
|
+
bot.run_forever()
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Core Components
|
|
83
|
+
|
|
84
|
+
### Bot Configuration
|
|
85
|
+
|
|
86
|
+
The bot inherits all configuration options from the base `GreenAPIBot` including the ability to customize GREEN-API
|
|
87
|
+
instance settings.
|
|
88
|
+
|
|
89
|
+
Complete configuration options for the WhatsappGptBot:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
bot = WhatsappGptBot(
|
|
93
|
+
# Required parameters
|
|
94
|
+
id_instance="your-instance-id",
|
|
95
|
+
api_token_instance="your-api-token",
|
|
96
|
+
openai_api_key="your-openai-api-key",
|
|
97
|
+
|
|
98
|
+
# Optional GPT-specific parameters
|
|
99
|
+
model="gpt-4o", # Default model
|
|
100
|
+
max_history_length=10, # Maximum messages in conversation history
|
|
101
|
+
system_message="You are a helpful assistant.", # System message to set behavior
|
|
102
|
+
temperature=0.5, # Temperature for response generation
|
|
103
|
+
error_message="Sorry, I couldn't process your request. Please try again.",
|
|
104
|
+
session_timeout=1800, # Session timeout in seconds (30 minutes)
|
|
105
|
+
|
|
106
|
+
# Optional parameters from base bot
|
|
107
|
+
bot_debug_mode=False, # Enable debug logs
|
|
108
|
+
debug_mode=False, # Enable API debug mode
|
|
109
|
+
raise_errors=True, # Whether to raise API errors
|
|
110
|
+
settings={ # GREEN-API instance settings
|
|
111
|
+
"webhookUrl": "", # Custom webhook URL
|
|
112
|
+
"webhookUrlToken": "", # Webhook security token
|
|
113
|
+
"delaySendMessagesMilliseconds": 500, # Delay between messages
|
|
114
|
+
"markIncomingMessagesReaded": "yes", # Mark messages as read
|
|
115
|
+
"incomingWebhook": "yes", # Enable incoming webhooks
|
|
116
|
+
"keepOnlineStatus": "yes", # Keep WhatsApp online status
|
|
117
|
+
"pollMessageWebhook": "yes", # Enable poll message webhooks
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### WhatsappGptBot
|
|
123
|
+
|
|
124
|
+
Main class for creating and managing your OpenAI-powered WhatsApp bot:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from whatsapp_chatgpt_python import WhatsappGptBot
|
|
128
|
+
|
|
129
|
+
bot = WhatsappGptBot(
|
|
130
|
+
id_instance="your-instance-id",
|
|
131
|
+
api_token_instance="your-api-token",
|
|
132
|
+
openai_api_key="your-openai-api-key",
|
|
133
|
+
model="gpt-4o",
|
|
134
|
+
system_message="You are a helpful assistant specializing in customer support.",
|
|
135
|
+
max_history_length=15,
|
|
136
|
+
temperature=0.7,
|
|
137
|
+
settings={
|
|
138
|
+
"webhookUrl": "",
|
|
139
|
+
"markIncomingMessagesReaded": "yes",
|
|
140
|
+
"keepOnlineStatus": "yes",
|
|
141
|
+
"delaySendMessagesMilliseconds": 500,
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# Start the bot
|
|
146
|
+
bot.run_forever()
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Message Handling
|
|
150
|
+
|
|
151
|
+
The bot automatically handles different types of WhatsApp messages and converts them into a format understood by
|
|
152
|
+
OpenAI's models.
|
|
153
|
+
|
|
154
|
+
### Supported Message Types
|
|
155
|
+
|
|
156
|
+
- **Text**: Regular text messages
|
|
157
|
+
- **Image**: Photos with optional captions (supported in vision-capable models)
|
|
158
|
+
- **Audio**: Voice messages with automatic transcription
|
|
159
|
+
- **Video**: Video messages with captions
|
|
160
|
+
- **Document**: File attachments
|
|
161
|
+
- **Poll**: Poll messages and poll updates
|
|
162
|
+
- **Location**: Location sharing
|
|
163
|
+
- **Contact**: Contact sharing
|
|
164
|
+
|
|
165
|
+
### Message Handler Registry
|
|
166
|
+
|
|
167
|
+
The bot uses a registry of message handlers to process different message types:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
# Access the registry
|
|
171
|
+
registry = bot.message_handlers
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# Create a custom message handler
|
|
175
|
+
class CustomMessageHandler(MessageHandler):
|
|
176
|
+
def can_handle(self, notification):
|
|
177
|
+
return notification.get_message_type() == "custom-type"
|
|
178
|
+
|
|
179
|
+
async def process_message(self, notification, openai_client=None, model=None):
|
|
180
|
+
# Process the message
|
|
181
|
+
return "Processed content"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# Register the custom handler
|
|
185
|
+
bot.register_message_handler(CustomMessageHandler())
|
|
186
|
+
|
|
187
|
+
# Replace an existing handler
|
|
188
|
+
bot.replace_handler(TextMessageHandler, CustomTextHandler())
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Middleware System
|
|
192
|
+
|
|
193
|
+
The middleware system allows for customizing message processing before sending to GPT and response processing before
|
|
194
|
+
sending back to the user.
|
|
195
|
+
|
|
196
|
+
### Adding Message Middleware
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
# Process messages before sending to GPT
|
|
200
|
+
def custom_message_middleware(notification, message_content, messages, session_data):
|
|
201
|
+
# Add custom context to the conversation
|
|
202
|
+
if notification.get_message_type() == "textMessage" and notification.chat.endswith("@c.us"):
|
|
203
|
+
# Add context to the message
|
|
204
|
+
enhanced_content = f"[User message] {message_content}"
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
"message_content": enhanced_content,
|
|
208
|
+
"messages": messages
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
"message_content": message_content,
|
|
213
|
+
"messages": messages
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# Add the middleware
|
|
218
|
+
bot.add_message_middleware(custom_message_middleware)
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### Adding Response Middleware
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
# Process GPT responses before sending to user
|
|
225
|
+
def custom_response_middleware(response, messages, session_data):
|
|
226
|
+
# Format or modify the response
|
|
227
|
+
formatted_response = response.replace("GPT", "Assistant").strip()
|
|
228
|
+
|
|
229
|
+
# You can also modify the messages that will be saved in history
|
|
230
|
+
return {
|
|
231
|
+
"response": formatted_response,
|
|
232
|
+
"messages": messages
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# Add the middleware
|
|
237
|
+
bot.add_response_middleware(custom_response_middleware)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Session Data
|
|
241
|
+
|
|
242
|
+
The GPT bot extends the base session data with conversation-specific information:
|
|
243
|
+
|
|
244
|
+
```python
|
|
245
|
+
@dataclass
|
|
246
|
+
class GPTSessionData:
|
|
247
|
+
"""Session data for GPT conversations"""
|
|
248
|
+
messages: List[Dict[str, Any]] = field(default_factory=list)
|
|
249
|
+
last_activity: int = field(default_factory=lambda: int(time.time()))
|
|
250
|
+
user_data: Dict[str, Any] = field(default_factory=dict)
|
|
251
|
+
context: Dict[str, Any] = field(default_factory=dict)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
You can access and modify this data in your middleware:
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
def message_middleware(notification, content, messages, session_data):
|
|
258
|
+
# Set context variables
|
|
259
|
+
if "variables" not in session_data.context:
|
|
260
|
+
session_data.context["variables"] = {}
|
|
261
|
+
|
|
262
|
+
session_data.context["variables"]["last_interaction"] = int(time.time())
|
|
263
|
+
|
|
264
|
+
return {"message_content": content, "messages": messages}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Utilities
|
|
268
|
+
|
|
269
|
+
The library provides several utility functions for common tasks:
|
|
270
|
+
|
|
271
|
+
### Media Handling
|
|
272
|
+
|
|
273
|
+
```python
|
|
274
|
+
from whatsapp_chatgpt_python import Utils
|
|
275
|
+
|
|
276
|
+
# Download media from a URL
|
|
277
|
+
temp_file = await Utils.download_media("https://example.com/image.jpg")
|
|
278
|
+
|
|
279
|
+
# Transcribe audio
|
|
280
|
+
from openai import OpenAI
|
|
281
|
+
|
|
282
|
+
openai_client = OpenAI(api_key="your-openai-api-key")
|
|
283
|
+
transcript = await Utils.transcribe_audio("/path/to/audio.ogg", openai_client)
|
|
284
|
+
|
|
285
|
+
# Clean up after processing
|
|
286
|
+
import os
|
|
287
|
+
|
|
288
|
+
os.unlink(temp_file)
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### Conversation Management
|
|
292
|
+
|
|
293
|
+
```python
|
|
294
|
+
from whatsapp_chatgpt_python import Utils
|
|
295
|
+
|
|
296
|
+
# Trim conversation history
|
|
297
|
+
trimmed_messages = Utils.trim_conversation_history(
|
|
298
|
+
messages,
|
|
299
|
+
10, # max messages
|
|
300
|
+
True # preserve system message
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
# Estimate token usage
|
|
304
|
+
estimated_tokens = Utils.estimate_tokens(messages)
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## Supported OpenAI Models
|
|
308
|
+
|
|
309
|
+
The library supports a variety of OpenAI models:
|
|
310
|
+
|
|
311
|
+
### GPT-4 Models
|
|
312
|
+
|
|
313
|
+
- gpt-4
|
|
314
|
+
- gpt-4-turbo
|
|
315
|
+
- gpt-4-turbo-preview
|
|
316
|
+
- gpt-4-1106-preview
|
|
317
|
+
- gpt-4-0125-preview
|
|
318
|
+
- gpt-4-32k
|
|
319
|
+
|
|
320
|
+
### GPT-4o Models
|
|
321
|
+
|
|
322
|
+
- gpt-4o (default)
|
|
323
|
+
- gpt-4o-mini
|
|
324
|
+
- gpt-4o-2024-05-13
|
|
325
|
+
|
|
326
|
+
### GPT-3.5 Models
|
|
327
|
+
|
|
328
|
+
- gpt-3.5-turbo
|
|
329
|
+
- gpt-3.5-turbo-16k
|
|
330
|
+
- gpt-3.5-turbo-1106
|
|
331
|
+
- gpt-3.5-turbo-0125
|
|
332
|
+
|
|
333
|
+
### o1 Models
|
|
334
|
+
|
|
335
|
+
- o1
|
|
336
|
+
- o1-mini
|
|
337
|
+
- o1-preview
|
|
338
|
+
|
|
339
|
+
### Image-Capable Models
|
|
340
|
+
|
|
341
|
+
The following models can process images:
|
|
342
|
+
|
|
343
|
+
- gpt-4o
|
|
344
|
+
- gpt-4o-mini
|
|
345
|
+
- gpt-4-vision-preview
|
|
346
|
+
- gpt-4-turbo
|
|
347
|
+
- gpt-4-turbo-preview
|
|
348
|
+
|
|
349
|
+
## Advanced Configuration
|
|
350
|
+
|
|
351
|
+
### Custom Command Handling
|
|
352
|
+
|
|
353
|
+
Since the library is built on whatsapp-chatbot-python, you can use all the command/filter features of the base library:
|
|
354
|
+
|
|
355
|
+
```python
|
|
356
|
+
@bot.router.message(command="help")
|
|
357
|
+
def help_handler(notification):
|
|
358
|
+
help_text = (
|
|
359
|
+
"🤖 *WhatsApp GPT Bot* 🤖\n\n"
|
|
360
|
+
"Available commands:\n"
|
|
361
|
+
"• */help* - Show this help message\n"
|
|
362
|
+
"• */clear* - Clear conversation history\n"
|
|
363
|
+
"• */info* - Show bot information"
|
|
364
|
+
)
|
|
365
|
+
notification.answer(help_text)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# Clear conversation history command
|
|
369
|
+
@bot.router.message(command="clear")
|
|
370
|
+
def clear_history_handler(notification):
|
|
371
|
+
chat_id = notification.chat
|
|
372
|
+
|
|
373
|
+
# Get session data
|
|
374
|
+
session_data = bot.get_session_data(chat_id)
|
|
375
|
+
|
|
376
|
+
# Find system message if it exists
|
|
377
|
+
system_message = None
|
|
378
|
+
for msg in session_data.messages:
|
|
379
|
+
if msg.get("role") == "system":
|
|
380
|
+
system_message = msg
|
|
381
|
+
break
|
|
382
|
+
|
|
383
|
+
# Reset messages but keep system message
|
|
384
|
+
if system_message:
|
|
385
|
+
session_data.messages = [system_message]
|
|
386
|
+
else:
|
|
387
|
+
session_data.messages = []
|
|
388
|
+
|
|
389
|
+
# Update session
|
|
390
|
+
bot.update_session_data(chat_id, session_data)
|
|
391
|
+
|
|
392
|
+
notification.answer("🗑️ Conversation history cleared! Let's start fresh.")
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
### Bypassing GPT for Certain Commands
|
|
396
|
+
|
|
397
|
+
You can create handlers that don't process with GPT:
|
|
398
|
+
|
|
399
|
+
```python
|
|
400
|
+
@bot.router.message(command="weather")
|
|
401
|
+
def weather_handler(notification):
|
|
402
|
+
notification.answer(
|
|
403
|
+
"🌤️ This is a placeholder weather response from a custom handler.\n\n"
|
|
404
|
+
"In a real bot, this would fetch actual weather data from an API.\n\n"
|
|
405
|
+
"This handler demonstrates skipping GPT processing."
|
|
406
|
+
)
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
### Explicit GPT Processing
|
|
410
|
+
|
|
411
|
+
You can explicitly request GPT processing after handling a message:
|
|
412
|
+
|
|
413
|
+
```python
|
|
414
|
+
@bot.router.message(text_message="recommend")
|
|
415
|
+
def recommend_handler(notification):
|
|
416
|
+
# Add a prefix message
|
|
417
|
+
notification.answer("I'll give you a recommendation. Let me think...")
|
|
418
|
+
# Request GPT processing as well
|
|
419
|
+
notification.process_with_gpt()
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
You can also modify the message before sending it to GPT using the `custom_message` parameter:
|
|
423
|
+
|
|
424
|
+
```python
|
|
425
|
+
# Echo handler that forwards a modified message to GPT
|
|
426
|
+
@bot.router.message(command="echo")
|
|
427
|
+
def echo_handler(notification):
|
|
428
|
+
# Get the rest of the message after the command
|
|
429
|
+
message_text = notification.message_text
|
|
430
|
+
command_parts = message_text.split(maxsplit=1)
|
|
431
|
+
|
|
432
|
+
if len(command_parts) > 1:
|
|
433
|
+
echo_text = command_parts[1]
|
|
434
|
+
notification.answer(f"You said: {echo_text}\n\nI'll ask GPT for more insights...")
|
|
435
|
+
|
|
436
|
+
# Process with GPT, but pass only the actual message (without the command)
|
|
437
|
+
notification.process_with_gpt(custom_message=echo_text)
|
|
438
|
+
else:
|
|
439
|
+
notification.answer("Please provide text after the /echo command.")
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
This is useful when you want to preprocess the message before it's sent to GPT, such as removing command prefixes,
|
|
443
|
+
formatting the input, or adding context.
|
|
444
|
+
|
|
445
|
+
### Advanced Message Processing
|
|
446
|
+
|
|
447
|
+
```python
|
|
448
|
+
# Check if current model supports images
|
|
449
|
+
if bot.supports_images():
|
|
450
|
+
# Handle image-based workflow
|
|
451
|
+
pass
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
## Complete Example Bot
|
|
455
|
+
|
|
456
|
+
Here's a complete example of a WhatsApp GPT bot with custom handlers and middleware:
|
|
457
|
+
|
|
458
|
+
```python
|
|
459
|
+
import os
|
|
460
|
+
import time
|
|
461
|
+
import logging
|
|
462
|
+
from whatsapp_chatgpt_python import (
|
|
463
|
+
WhatsappGptBot,
|
|
464
|
+
ImageMessageHandler,
|
|
465
|
+
TextMessageHandler
|
|
466
|
+
)
|
|
467
|
+
from dotenv import load_dotenv
|
|
468
|
+
|
|
469
|
+
# Load environment variables from .env file
|
|
470
|
+
load_dotenv()
|
|
471
|
+
# Set up logging
|
|
472
|
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
473
|
+
logger = logging.getLogger('whatsapp_chatgpt_python')
|
|
474
|
+
|
|
475
|
+
# Get environment variables
|
|
476
|
+
ID_INSTANCE = os.environ.get("INSTANCE_ID")
|
|
477
|
+
API_TOKEN = os.environ.get("INSTANCE_TOKEN")
|
|
478
|
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
|
479
|
+
|
|
480
|
+
# Initialize the bot
|
|
481
|
+
bot = WhatsappGptBot(
|
|
482
|
+
id_instance=ID_INSTANCE,
|
|
483
|
+
api_token_instance=API_TOKEN,
|
|
484
|
+
openai_api_key=OPENAI_API_KEY,
|
|
485
|
+
model="gpt-4o", # Uses the GPT-4o model (which supports images)
|
|
486
|
+
system_message="You are a helpful assistant. Be concise and friendly in your replies.",
|
|
487
|
+
max_history_length=15, # Keep last 15 messages in conversation history
|
|
488
|
+
temperature=0.7, # Slightly more creative responses
|
|
489
|
+
session_timeout=1800, # Sessions expire after 30 minutes of inactivity
|
|
490
|
+
error_message="Sorry, your message could not be processed.", # Custom error message
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
# Custom image handler that provides enhanced instructions for images
|
|
495
|
+
class EnhancedImageHandler(ImageMessageHandler):
|
|
496
|
+
async def process_message(self, notification, openai_client=None, model=None):
|
|
497
|
+
# Call the parent class method to get the base result
|
|
498
|
+
result = await super().process_message(notification, openai_client, model)
|
|
499
|
+
|
|
500
|
+
# For text-only responses (non-vision models)
|
|
501
|
+
if isinstance(result, str):
|
|
502
|
+
return result.replace(
|
|
503
|
+
"[The user sent an image",
|
|
504
|
+
"[The user sent an image. Analyze what might be in it based on any caption"
|
|
505
|
+
)
|
|
506
|
+
|
|
507
|
+
# For vision-capable models, enhance the text instruction
|
|
508
|
+
if isinstance(result, list) and len(result) > 0 and isinstance(result[0], dict):
|
|
509
|
+
if result[0].get('type') == 'text':
|
|
510
|
+
text = result[0].get('text', '')
|
|
511
|
+
if text == "Analyzing this image":
|
|
512
|
+
result[0]['text'] = "Describe this image in detail and what you see in it."
|
|
513
|
+
|
|
514
|
+
return result
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# Example of a custom text handler
|
|
518
|
+
class EnhancedTextHandler(TextMessageHandler):
|
|
519
|
+
async def process_message(self, notification, *args, **kwargs):
|
|
520
|
+
# Get the text message using the parent method
|
|
521
|
+
text = await super().process_message(notification, *args, **kwargs)
|
|
522
|
+
|
|
523
|
+
if not text:
|
|
524
|
+
return text
|
|
525
|
+
|
|
526
|
+
lower_text = text.lower()
|
|
527
|
+
|
|
528
|
+
if any(term in lower_text for term in ['code', 'function', 'script', 'program']):
|
|
529
|
+
return f"🧑💻 CODE REQUEST: {text}\n\n[I'll format my code response with proper syntax highlighting]"
|
|
530
|
+
|
|
531
|
+
elif text.endswith('?') or text.lower().startswith(
|
|
532
|
+
('what', 'why', 'how', 'when', 'where', 'who', 'can', 'could')):
|
|
533
|
+
return f"❓ QUESTION: {text}\n\n[I'll provide a clear and comprehensive answer]"
|
|
534
|
+
|
|
535
|
+
return text
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
# Replace the default handlers with our enhanced versions
|
|
539
|
+
bot.replace_handler(ImageMessageHandler, EnhancedImageHandler())
|
|
540
|
+
bot.replace_handler(TextMessageHandler, EnhancedTextHandler())
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
# Middleware to log all messages and add tracking information
|
|
544
|
+
def logging_middleware(notification, message_content, messages, session_data):
|
|
545
|
+
user_id = notification.sender
|
|
546
|
+
if isinstance(message_content, str):
|
|
547
|
+
content_display = message_content[:100] + "..." if len(message_content) > 100 else message_content
|
|
548
|
+
else:
|
|
549
|
+
content_display = "complex content (likely contains media)"
|
|
550
|
+
|
|
551
|
+
logger.info(f"Message from {user_id}: {content_display}")
|
|
552
|
+
|
|
553
|
+
# Add tracking information to session context
|
|
554
|
+
if not session_data.context.get("variables"):
|
|
555
|
+
session_data.context["variables"] = {}
|
|
556
|
+
|
|
557
|
+
session_data.context["variables"].update({
|
|
558
|
+
"last_interaction": int(time.time()),
|
|
559
|
+
"message_count": session_data.context.get("variables", {}).get("message_count", 0) + 1
|
|
560
|
+
})
|
|
561
|
+
|
|
562
|
+
# Return unchanged content and messages
|
|
563
|
+
return {"message_content": message_content, "messages": messages}
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# Middleware to format responses before sending to user
|
|
567
|
+
def formatting_middleware(response, messages, session_data):
|
|
568
|
+
# Format response by adding a signature at the end of longer messages
|
|
569
|
+
formatted_response = response.strip()
|
|
570
|
+
|
|
571
|
+
# Don't add signature to short responses
|
|
572
|
+
if len(formatted_response) > 100 and not formatted_response.endswith("_"):
|
|
573
|
+
message_count = session_data.context.get("variables", {}).get("message_count", 0)
|
|
574
|
+
formatted_response += f"\n\n_Message #{message_count} • Powered by GPT_"
|
|
575
|
+
|
|
576
|
+
return {"response": formatted_response, "messages": messages}
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
# Add the middleware
|
|
580
|
+
bot.add_message_middleware(logging_middleware)
|
|
581
|
+
bot.add_response_middleware(formatting_middleware)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
# Command handler for /clear to reset conversation history
|
|
585
|
+
@bot.router.message(command="clear")
|
|
586
|
+
def clear_history_handler(notification):
|
|
587
|
+
chat_id = notification.chat
|
|
588
|
+
|
|
589
|
+
# Get session data
|
|
590
|
+
session_data = bot.get_session_data(chat_id)
|
|
591
|
+
|
|
592
|
+
# Find system message if it exists
|
|
593
|
+
system_message = None
|
|
594
|
+
for msg in session_data.messages:
|
|
595
|
+
if msg.get("role") == "system":
|
|
596
|
+
system_message = msg
|
|
597
|
+
break
|
|
598
|
+
|
|
599
|
+
# Reset messages but keep system message
|
|
600
|
+
if system_message:
|
|
601
|
+
session_data.messages = [system_message]
|
|
602
|
+
else:
|
|
603
|
+
session_data.messages = []
|
|
604
|
+
|
|
605
|
+
# Update session
|
|
606
|
+
bot.update_session_data(chat_id, session_data)
|
|
607
|
+
|
|
608
|
+
notification.answer("🗑️ Conversation history cleared! Let's start fresh.")
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
# Command handler for /help to show available commands
|
|
612
|
+
@bot.router.message(command="help")
|
|
613
|
+
def help_handler(notification):
|
|
614
|
+
help_text = (
|
|
615
|
+
"🤖 *WhatsApp GPT Bot* 🤖\n\n"
|
|
616
|
+
"Available commands:\n"
|
|
617
|
+
"• */help* - Show this help message\n"
|
|
618
|
+
"• */clear* - Clear conversation history\n"
|
|
619
|
+
"• */info* - Show bot information\n"
|
|
620
|
+
"• */weather* - Example of a handler that skips GPT\n\n"
|
|
621
|
+
"You can send text, images, audio, and more. I'll respond intelligently to your messages."
|
|
622
|
+
)
|
|
623
|
+
notification.answer(help_text)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
# Add an info command
|
|
627
|
+
@bot.router.message(command="info")
|
|
628
|
+
def info_handler(notification):
|
|
629
|
+
chat_id = notification.chat
|
|
630
|
+
session_data = bot.get_session_data(chat_id)
|
|
631
|
+
|
|
632
|
+
# Get session statistics
|
|
633
|
+
message_count = len(session_data.messages) - 1 # Subtract system message
|
|
634
|
+
if message_count < 0:
|
|
635
|
+
message_count = 0
|
|
636
|
+
|
|
637
|
+
vision_capable = "Yes" if bot.supports_images() else "No"
|
|
638
|
+
|
|
639
|
+
info_text = (
|
|
640
|
+
"📊 *Bot Information* 📊\n\n"
|
|
641
|
+
f"Model: {bot.get_model()}\n"
|
|
642
|
+
f"Vision capable: {vision_capable}\n"
|
|
643
|
+
f"Messages in current session: {message_count}\n"
|
|
644
|
+
f"Max history length: {bot.max_history_length}\n"
|
|
645
|
+
f"Session timeout: {bot.session_timeout} seconds\n\n"
|
|
646
|
+
"To clear the current conversation, use */clear*"
|
|
647
|
+
)
|
|
648
|
+
notification.answer(info_text)
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
# Example weather handler that skips GPT processing
|
|
652
|
+
@bot.router.message(command="weather")
|
|
653
|
+
def weather_handler(notification):
|
|
654
|
+
notification.answer(
|
|
655
|
+
"🌤️ This is a placeholder weather response from a custom handler.\n\n"
|
|
656
|
+
"In a real bot, this would fetch actual weather data from an API.\n\n"
|
|
657
|
+
"This handler demonstrates skipping GPT processing."
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
# Start the bot
|
|
662
|
+
if __name__ == "__main__":
|
|
663
|
+
logger.info("Starting WhatsApp GPT Bot...")
|
|
664
|
+
logger.info(f"Using model: {bot.get_model()}")
|
|
665
|
+
bot.run_forever()
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
## License
|
|
669
|
+
|
|
670
|
+
MIT
|
|
671
|
+
|
|
672
|
+
## Technologies Used
|
|
673
|
+
|
|
674
|
+
This library is built on top of:
|
|
675
|
+
|
|
676
|
+
- [whatsapp-chatbot-python](https://github.com/green-api/whatsapp-chatbot-python) - The base WhatsApp bot library
|
|
677
|
+
- [GREEN-API](https://green-api.com/) - WhatsApp API service for bot integration
|
|
678
|
+
- [OpenAI API](https://openai.com/) - For GPT model integration
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
whatsapp_chatgpt_python/__init__.py,sha256=tB3IzJS8hxN6IPyJ7lsDOhgg3NpSsOVr0frBtCfDjRw,858
|
|
2
|
+
whatsapp_chatgpt_python/bot.py,sha256=BilsR0mKVkZwZhiVuBgSNghxPKAHtDYC0oVI8rAQEc4,10301
|
|
3
|
+
whatsapp_chatgpt_python/config.py,sha256=y73iei-zhY9knxuPWdGarKwC7pZfYUHH_NDlfM9pz64,734
|
|
4
|
+
whatsapp_chatgpt_python/logger.py,sha256=spkpwm1MZUQgfta3_iDkCjlY1uEZFJ6XYNU_DEkFhPk,801
|
|
5
|
+
whatsapp_chatgpt_python/models.py,sha256=buoqwi5sa6YWFli_3n0VBfZHZ82a-hBkveRXthuO66g,542
|
|
6
|
+
whatsapp_chatgpt_python/notification.py,sha256=ntWy7JNg-19gVleo8ORauGi2QwhuIbe7zLk2-W6nzFE,2370
|
|
7
|
+
whatsapp_chatgpt_python/handlers/__init__.py,sha256=7fPFyQHDFWsxjDLsAUk0BAnWVXEIInFQFvZPfTyG6tE,505
|
|
8
|
+
whatsapp_chatgpt_python/handlers/audio.py,sha256=UKq730tUmVPW2QejRufQ0ILTC93DsaaA1lIrqC_gL_k,3141
|
|
9
|
+
whatsapp_chatgpt_python/handlers/base.py,sha256=BZYs-YEh-LZkfRQRQjAB5H2GOMUA02J2dvtMublj5wg,1894
|
|
10
|
+
whatsapp_chatgpt_python/handlers/contact.py,sha256=x2Azg-QrGL5GtoUvCVkCOkRIoO3Q0slXjPY73Id9Z-k,1599
|
|
11
|
+
whatsapp_chatgpt_python/handlers/document.py,sha256=ASBk9rp8S2zfmo0wokxgjqvsWgy64SzRSchR3jNvqo4,1382
|
|
12
|
+
whatsapp_chatgpt_python/handlers/image.py,sha256=FtS6e_PPL-I1D9gommSa1BELGtLApv07Uk48eSnaYqI,4229
|
|
13
|
+
whatsapp_chatgpt_python/handlers/location.py,sha256=fXJNupss7NZpNEQTmIGwxmYjO6Qwv_bTZuydOJpwBlA,1568
|
|
14
|
+
whatsapp_chatgpt_python/handlers/poll.py,sha256=Ls8OSN3UrLQj_QsU7A5dBO-209rnW-Hel1zvjiX1Mb0,2604
|
|
15
|
+
whatsapp_chatgpt_python/handlers/registry.py,sha256=YRe5dMKxZAj9YpHjzztpl7ntnhu6EnDjEKQL5L91m_s,4539
|
|
16
|
+
whatsapp_chatgpt_python/handlers/text.py,sha256=9XIPeWbUpJp3sjSBQA4--dS029pEFMSIMPUC_0DcMnc,968
|
|
17
|
+
whatsapp_chatgpt_python/handlers/video.py,sha256=SAhb3NvPNExPvNMmUDAWlFmlpQ5r-iL168NfdZuWc4U,1400
|
|
18
|
+
whatsapp_chatgpt_python/middleware/__init__.py,sha256=E1w9E7kcs4M-aIgFVe4SqHRh6glvTMjCt2QkO4WzIwU,167
|
|
19
|
+
whatsapp_chatgpt_python/middleware/base.py,sha256=us0o8247l4Rd5vKhMh-GsQqZluNK88bqUmaESljUyqY,1461
|
|
20
|
+
whatsapp_chatgpt_python/middleware/manager.py,sha256=VvxNfHEzZ6uu17g7yapRs8xRmx6ghJzRUUxUup1ZsSA,3612
|
|
21
|
+
whatsapp_chatgpt_python/utils/__init__.py,sha256=55ugQcYfmF5mjTAi5JieMjDFY9vs05S9inYZrUdyLqs,1095
|
|
22
|
+
whatsapp_chatgpt_python/utils/conversation.py,sha256=lTTQOtBnRFZRPJd5aoULR22NfPuYc4St46n1MxVduPI,1669
|
|
23
|
+
whatsapp_chatgpt_python/utils/media.py,sha256=EhWSIp-Owq2KfvSq2MOaNf-WnXhBFylE5DsbHHH7qTU,1204
|
|
24
|
+
whatsapp_chatgpt_python/utils/router.py,sha256=J2E8T0nFMMlX5V9ZOqbTaa5bS82TjkTY_wmlCyqm3t8,5818
|
|
25
|
+
whatsapp_chatgpt_python-1.0.0.dist-info/LICENSE,sha256=Fx7WocB4M6b0-wEoSrt-j92c9rzp5fgMVdzKv1FaFyc,1087
|
|
26
|
+
whatsapp_chatgpt_python-1.0.0.dist-info/METADATA,sha256=kTFOZwqHoz6Gv0Gx3MNGbs3izBxf6Ia_4N4h8QHgSbk,21286
|
|
27
|
+
whatsapp_chatgpt_python-1.0.0.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
|
|
28
|
+
whatsapp_chatgpt_python-1.0.0.dist-info/top_level.txt,sha256=NhHzIpJKsASpoW3OHWVKTVcq1REPQ25kMtMFMbC0m1g,24
|
|
29
|
+
whatsapp_chatgpt_python-1.0.0.dist-info/RECORD,,
|