赞
踩
功能是实现 web 转api 对接wxbot用,
直接上代码,
- def get_register_websocket():
- # 请求头
- url = "https://chat.openai.com/backend-api/register-websocket"
-
- payload = {}
- headers = {
- 'Authorization': 'Bearer eyJhbGxxxxxxxxxxxxxxxxxP89g',
- 'User-Agent': 'PostmanRuntime/7.36.3',
- 'Cookie':'__cf_bm=IH7tNQ0qLZkExG1S.9bR8UWdTyUJnvwLVW1hWWAZnjs-1709515826-1.0.1.1-NpxvrgB8g61jflrQqxxxxxxxxxx4w9.McqlfewwIgDg; __cflb=0H28vVfFxgNcKEuU2yRkHrTNV; _cfuvid=VBhrtMcQ4dxRz1xNPv4WWk1.c-1709461045475-0.0.1.1-604800000'
- }
-
- response = requests.request("POST", url, headers=headers, data=payload, allow_redirects=False)
-
- # 将文本内容转换为Python字典/列表
- try:
- json_data = json.loads(response.text)
- except json.JSONDecodeError:
- print("无法将响应内容解析为JSON格式")
- else:
- return json_data['wss_url']
返回信息
- import asyncio
- import websockets
- import base64
- import json
- import os
- from urllib.parse import urlparse, parse_qs
- import requests
- os.environ["http_proxy"] = "http://127.0.0.1:1080"
- os.environ["https_proxy"] = "http://127.0.0.1:1080"
-
- def get_register_websocket():
- # 请求头
- url = "https://chat.openai.com/backend-api/register-websocket"
-
- payload = {}
- headers = {
- 'Authorization': 'Bearer eyJ***********9g',
- 'User-Agent': 'PostmanRuntime/7.36.3',
- 'Cookie':'__cf_bm=IH****9515826-1.0.1.1-NpxvrgB8g61jflrQqvaxwnF*******2M1bSfmWkqmJpuyy4w9.McqlfewwIgDg; __cflb=0H28vVfF4aAyg2*yRkHrTNV; _cfuvid=VBhrtMcQ4d***iIs1nWA1Rz1xNPv4WWk1.c-1709461045475-0.0.1.1-604800000'
- }
-
- response = requests.request("POST", url, headers=headers, data=payload, allow_redirects=False)
-
- # 将文本内容转换为Python字典/列表
- try:
- json_data = json.loads(response.text)
- except json.JSONDecodeError:
- print("无法将响应内容解析为JSON格式")
- else:
-
- return json_data['wss_url']
-
-
- async def listen_to_websocket(url, access_token):
- headers = {'Authorization': f'Bearer {access_token}'}
- final_message = "" # 初始化空字符串用于累积信息
-
- async with websockets.connect(url, extra_headers=headers) as websocket:
- while True:
- try:
- message = await websocket.recv()
- # 解析消息为JSON
- message_data = json.loads(message)
- # 提取并解码body字段
- body_encoded = message_data.get("body", "")
- body_decoded = base64.b64decode(body_encoded).decode('utf-8')
-
- # 移除前缀"data: ",然后解析JSON
- message_data_json = json.loads(body_decoded[6:])
-
- # 提取parts
- parts = message_data_json["message"]["content"]["parts"][0]
-
- # 这里不再直接打印parts,而是更新final_message
- final_message = parts # 更新最后一条消息
-
- except websockets.exceptions.ConnectionClosedOK:
- print("Connection closed successfully.")
- #break
- except Exception as e:
- print(f"Error occurred: {e}")
- break
-
- # 循环结束后,打印最后一次更新的信息
- print(final_message)
-
-
- if __name__ == "__main__":
-
- url = get_register_websocket()
- print(url)
- parsed_url = urlparse(get_register_websocket())
- query_params = parse_qs(parsed_url.query)
-
- # 提取 access_token 的值
- access_token_value = query_params['access_token'][0]
-
- asyncio.get_event_loop().run_until_complete(listen_to_websocket(get_register_websocket(), access_token_value))
- import requests
- import json
- import os
- import uuid
- import asyncio
- import websockets
- import base64
- import json
- import os
- os.environ["http_proxy"] = "http://127.0.0.1:1080"
- os.environ["https_proxy"] = "http://127.0.0.1:1080"
- url = "https://chat.openai.com/backend-api/conversation"
-
- def askgpt(prompt, conversation_id=None):
- # 基本请求结构
- message_structure = {
- "id": str(uuid.uuid4()),
- "author": {"role": "user"},
- "content": {"content_type": "text", "parts": [prompt]},
- "metadata": {}
- }
-
- # 初始化请求payload
- payload = {
- "action": "next",
- "messages": [message_structure],
- "model": "text-davinci-002-render-sha",
- "timezone_offset_min": -480,
- "suggestions": [],
- "history_and_training_disabled": False,
- "conversation_mode": {"kind": "primary_assistant"},
- "force_paragen": False,
- "force_rate_limit": False
- }
-
- # 根据是否提供conversation_id调整payload
- if conversation_id:
- payload["conversation_id"] = conversation_id
- payload["parent_message_id"] = str(uuid.uuid4()) # 假设每次调用都有新的parent_message_id
- # 特定于长对话的字段
- payload["websocket_request_id"] = "5e3e28e1-5943-4fce-ae81-8cc0710e61c0"
- else:
- payload["parent_message_id"] = str(uuid.uuid4()) # 第一次对话的parent_message_id
-
- # 请求头
- headers = {
- 'Authorization': 'Bearer eyJhb********************P89g',
- 'User-Agent': 'PostmanRuntime/7.36.3',
- 'Content-Type': 'application/json',
- 'Cookie':'__cf_bm=IH7tNQ0qLZkExG1S.9bR8UWdTyUJnvwLVW1hWWAZnjs-1709515826-1.0.1.1-NpxvrgB8g61jflr*********wIgDg; __cflb=0H28*V; _cfuvid=VBhrtMcQ4d******WWk1.c-1709461045475-0.0.1.1-604800000'
- }
-
-
-
- response = requests.post( url, headers=headers, json=payload, allow_redirects=False)
-
- print(response.text)
-
- conversation_id = None # conversation ID here
-
- #conversation_id = str(uuid.uuid4())
- #askgpt("10+1",conversation_id)
- askgpt("你的模型","4af92768-50c4-425b-b63e-35e3eaede0ce")
在监听窗口可以获取到gpt3.5回答的广播信息
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。