功能是實現 web ?轉api 對接wxbot用,
直接上代碼,
1.獲取wss url
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']
返回信息
2.監聽wss
?
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()# 解析消息為JSONmessage_data = json.loads(message)# 提取并解碼body字段body_encoded = message_data.get("body", "")body_decoded = base64.b64decode(body_encoded).decode('utf-8')# 移除前綴"data: ",然后解析JSONmessage_data_json = json.loads(body_decoded[6:])# 提取partsparts = message_data_json["message"]["content"]["parts"][0]# 這里不再直接打印parts,而是更新final_messagefinal_message = parts # 更新最后一條消息except websockets.exceptions.ConnectionClosedOK:print("Connection closed successfully.")#breakexcept 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))
3.發送問題給gpt
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": {}}# 初始化請求payloadpayload = {"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調整payloadif conversation_id:payload["conversation_id"] = conversation_idpayload["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回答的廣播信息?