-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
424 lines (347 loc) · 13.4 KB
/
main.py
File metadata and controls
424 lines (347 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""
ChatGPT automation using undetected-chromedriver
Robust version with multiple fallback methods for interaction
"""
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import sys
def setup_browser():
"""Set up undetected Chrome browser"""
options = uc.ChromeOptions()
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
# Additional options to appear more human-like
options.add_argument("--disable-gpu")
options.add_argument("--window-size=1280,800")
options.add_argument("--start-maximized")
driver = uc.Chrome(options=options)
driver.execute_script(
"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
)
return driver
def wait_for_cloudflare(driver):
"""Wait for Cloudflare challenge to complete"""
print("Waiting for Cloudflare challenge to complete...")
print("(This should happen automatically)")
# Give Cloudflare time to load and complete
time.sleep(3)
# Check if we're on ChatGPT
current_url = driver.current_url
print(f"Current URL: {current_url}")
return "chatgpt.com" in current_url
def find_textarea_advanced(driver):
"""Find textarea using multiple methods"""
# Method 1: Try specific ID first (fastest)
try:
textarea = driver.find_element(By.ID, "prompt-textarea")
if textarea and textarea.is_displayed():
return textarea
except:
pass
# Method 2: Wait for any textarea to be present and clickable
try:
textarea = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.TAG_NAME, "textarea"))
)
if textarea and textarea.is_displayed() and textarea.is_enabled():
return textarea
except:
pass
# Method 3: Find by placeholder text
try:
textarea = driver.find_element(
By.XPATH,
"//textarea[contains(@placeholder, 'Message') or contains(@placeholder, 'Send') or contains(@placeholder, 'Type')]",
)
if textarea and textarea.is_displayed():
return textarea
except:
pass
# Method 4: Find all textareas and pick the visible one
try:
textareas = driver.find_elements(By.TAG_NAME, "textarea")
for ta in textareas:
if ta.is_displayed() and ta.is_enabled():
rect = ta.rect
if (
rect["width"] > 100 and rect["height"] > 20
): # Ensure it's reasonably sized
return ta
except:
pass
return None
def send_message_advanced(driver, message):
"""Send a message with multiple fallback methods"""
# Find the textarea
textarea = find_textarea_advanced(driver)
if not textarea:
# Last resort: JavaScript to find any textarea
try:
driver.execute_script(
"""
var textareas = document.querySelectorAll('textarea');
if (textareas.length > 0) {
textareas[0].scrollIntoView();
}
"""
)
time.sleep(1)
textarea = find_textarea_advanced(driver)
except:
pass
if not textarea:
return False, "Could not find message input box"
# Try to send the message
try:
# Method 1: Direct interaction
driver.execute_script("arguments[0].scrollIntoView(true);", textarea)
time.sleep(0.5)
# Click to focus
driver.execute_script("arguments[0].click();", textarea)
time.sleep(0.5)
# Clear and focus
textarea.clear()
textarea.click()
# Type the message quickly (faster approach)
textarea.send_keys(message)
time.sleep(0.1) # Small delay before sending
# Press Enter
textarea.send_keys(Keys.RETURN)
return True, "Message sent successfully"
except Exception as e:
# Fallback: Pure JavaScript
try:
driver.execute_script(
"""
var textarea = arguments[0];
var message = arguments[1];
// Set value
textarea.value = message;
textarea.focus();
// Trigger input event
var inputEvent = new Event('input', { bubbles: true });
textarea.dispatchEvent(inputEvent);
// Simulate Enter key
setTimeout(function() {
var enterEvent = new KeyboardEvent('keydown', {
key: 'Enter',
code: 'Enter',
keyCode: 13,
which: 13,
bubbles: true
});
textarea.dispatchEvent(enterEvent);
// Also try submitting the form if it exists
var form = textarea.closest('form');
if (form) {
form.submit();
}
}, 100);
""",
textarea,
message,
)
return True, "Message sent via JavaScript"
except Exception as js_error:
return False, f"Failed to send message: {str(js_error)}"
def wait_for_response(driver):
"""Wait for ChatGPT to respond"""
print("Waiting for response...")
# Store the initial state - get current messages or empty list
try:
initial_messages = driver.find_elements(
By.CSS_SELECTOR, "[data-message-author-role='assistant']"
)
initial_count = len(initial_messages)
initial_last_text = initial_messages[-1].text if initial_messages else ""
except:
initial_count = 0
initial_last_text = ""
# Fast polling for new content (check every 0.2 seconds)
max_wait = 30
start_time = time.time()
while time.time() - start_time < max_wait:
try:
# Check for new assistant messages
current_messages = driver.find_elements(
By.CSS_SELECTOR, "[data-message-author-role='assistant']"
)
# Check if we have a new message or if the last message changed
if len(current_messages) > initial_count:
# New message appeared - wait a tiny bit for it to start generating
time.sleep(0.3)
break
elif current_messages and len(current_messages) == initial_count:
# Check if the last message content changed (streaming response)
current_last_text = (
current_messages[-1].text if current_messages else ""
)
if current_last_text != initial_last_text and current_last_text:
# Content changed - response started
time.sleep(0.3)
break
# Also check for any "generating" indicators
generating_indicators = driver.find_elements(
By.XPATH, "//div[contains(@class, 'result-streaming')]"
)
if generating_indicators:
time.sleep(0.3)
break
except:
pass
# Short sleep before next check
time.sleep(0.2)
# Now wait for the response to complete
last_text = ""
stable_count = 0
while time.time() - start_time < 60:
try:
# Get current message text
messages = driver.find_elements(
By.CSS_SELECTOR, "[data-message-author-role='assistant']"
)
if messages:
current_text = messages[-1].text
# Check if text is stable (hasn't changed)
if current_text == last_text and current_text:
stable_count += 1
if stable_count >= 2: # Text stable for 0.4 seconds
# Response complete
return
else:
stable_count = 0
last_text = current_text
# Also check for stop button disappearing as a completion indicator
stop_buttons = driver.find_elements(
By.XPATH,
"//button[contains(@aria-label, 'Stop') or contains(., 'Stop')]",
)
if not stop_buttons and last_text:
# No stop button and we have text - likely done
time.sleep(0.2)
return
except:
pass
time.sleep(0.2)
# Get the response (optimized)
try:
# Primary method: Get assistant messages directly
messages = driver.find_elements(
By.CSS_SELECTOR, "[data-message-author-role='assistant']"
)
if messages:
last_message = messages[-1].text
if last_message:
return last_message
# Fallback: Try other selectors
selectors = [
".group:has([data-message-author-role='assistant'])",
"div[class*='assistant']",
".markdown",
]
for selector in selectors:
try:
messages = driver.find_elements(By.CSS_SELECTOR, selector)
if messages:
# Get the last message
last_message = messages[-1].text
if last_message and len(last_message) > 5: # Ensure it's not empty
return last_message
except:
continue
# Fallback: Get all text from potential message containers
containers = driver.find_elements(
By.XPATH,
"//div[contains(@class, 'markdown') or contains(@class, 'message')]",
)
if containers:
for container in reversed(containers):
text = container.text
if text and len(text) > 10 and "ChatGPT" not in text:
return text
except Exception as e:
print(f"Error getting response: {e}")
return "Could not retrieve response"
def main():
print("ChatGPT Automation (Enhanced Version)\n" + "=" * 50)
# Set up browser
driver = setup_browser()
try:
# Navigate to ChatGPT
print("Opening ChatGPT...")
driver.get("https://chatgpt.com")
# Wait for Cloudflare
if not wait_for_cloudflare(driver):
print("Warning: May not be on ChatGPT yet")
# Wait for user to log in
print("\nIMPORTANT: Please complete the following:")
print("1. If you see a Cloudflare challenge, wait for it to complete")
print("2. Log in to your ChatGPT account if needed")
print("3. Make sure you can see the chat interface")
print("\nPress Enter when ready to continue...")
input()
# Quick stabilization
time.sleep(0.5)
# Verify we can find the textarea
test_textarea = find_textarea_advanced(driver)
if test_textarea:
print("✓ Chat interface detected and ready!")
else:
print("⚠ Warning: Could not detect chat interface")
print("Trying to continue anyway...")
# Main interaction loop
print("\n" + "=" * 50)
print("You can now chat with ChatGPT!")
print("Type 'quit' to exit")
print("=" * 50)
while True:
try:
# Get user input
user_message = input("\nYou: ")
if user_message.lower() == "quit":
print("Exiting...")
break
if not user_message.strip():
continue
# Send message
print("Sending message...")
success, status = send_message_advanced(driver, user_message)
if not success:
print(f"Error: {status}")
print("Try refreshing the page or type 'quit' to exit")
continue
# Get response
wait_for_response(driver)
# Now get the actual response text
try:
messages = driver.find_elements(
By.CSS_SELECTOR, "[data-message-author-role='assistant']"
)
if messages:
response = messages[-1].text
print(f"\nChatGPT: {response}")
else:
print("\nChatGPT: [Could not retrieve response text]")
except Exception as e:
print(f"\nError getting response: {e}")
except KeyboardInterrupt:
print("\n\nInterrupted by user")
break
except Exception as e:
print(f"Error: {e}")
print("You can try again or type 'quit' to exit")
finally:
print("\nClosing browser...")
driver.quit()
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Fatal error: {e}")
sys.exit(1)