Вот минимальный рабочий пример моего кода:
Код: Выделить всё
from websocket import (
create_connection,
WebSocketTimeoutException,
)
time.sleep(1) # simulate user reading
# Build the WebSocket URL for /live
ws_url = (
f"wss://{urlparse(self.host).netloc}/live"
f"?participant_code={self.participant_code}"
f"&page_name=chat"
f"&page_index=8"
f"&session_code={self.session_code}"
f"&live_method_name=chat.live_method"
)
print(f"Connecting to WebSocket: {ws_url}")
# Build cookies
cookie_dict = self.client.cookies.get_dict()
cookie_header_str = "; ".join(f"{k}={v}" for k, v in cookie_dict.items())
headers = [f"Cookie: {cookie_header_str}"]
print("Cookies dict:", cookie_dict)
print("Headers:", headers)
try:
self.ws = create_connection(
ws_url, header=headers, timeout=30, sslopt={"cert_reqs": 0}
)
self.ws.settimeout(30) # Extend timeout for receive operations
# Send INIT
init_msg = {"init": True}
self.ws.send(json.dumps(init_msg))
print("Sent init. Waiting for GPT init reply...")
print("ws connected?", self.ws.connected)
try:
print("Inside the try block")
print("ws connected?", self.ws.connected)
reply1 = self.ws.recv()
print("GPT init reply:", reply1)
except WebSocketTimeoutException:
print("Timeout waiting for init reply")
except Exception as e:
print("Some other error while waiting for init reply:", e)
# Then WAIT a while to ensure the user remains on the page # Is this necessary??
time.sleep(5)
# Send TEXT
text_msg = {
"text": "We should stop supporting Ukraine and focus on domestic issues."
}
self.ws.send(json.dumps(text_msg))
print("Sent first real user message. Waiting for GPT text reply...")
try:
reply2 = self.ws.recv()
print("GPT second reply:", reply2)
except WebSocketTimeoutException:
print("Timeout waiting for second reply")
# Close
self.ws.close()
except Exception as e:
import traceback
traceback.print_exc()
print("Error during chat interaction:", e)
Код: Выделить всё
Connecting to WebSocket: wss://myapp.herokuapp.com/live?participant_code=cw1ptyf9&page_name=chat&page_index=8&session_code=Scientific_Experiment&live_method_name=chat.live_method
Cookies dict: {}
Headers: ['Cookie: ']
Sent init. Waiting for GPT init reply...
ws connected? True
Inside the try block
ws connected? True
В журналах сервера я вижу, что self.ws.send(json.dumps(init_msg)) отправил исходное сообщение успешно отправлено на сервер, но вызов Recv() зависает на неопределенный срок и не генерирует исключение WebSocketTimeoutException даже через 30 секунд. Являются ли проблемой отсутствие файлов cookie? Почему они вообще отсутствуют?
Я проверил инструменты разработчика своего браузера, чтобы убедиться, что соединение WebSocket работает должным образом при доступе через браузер.
Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-python