撸chatgpt3.5 api backend-api 对接wxbot

功能是实现 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()
                # 解析消息为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))

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": {}
    }

    # 初始化请求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回答的广播信息 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三块钱0794

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值