实战-快速对接ChatGPT
60行代码0成本实现一个ChatGPT企业微信机器人
信息
3月1日,OpenAI 正式开放了 GPT-3.5-turbo 的 API。
GPT-3.5-turbo 不但具备 GPT-3 的全部能力,并针对聊天对话场景进行了优化,支持基于上下文的追问式聊天。
最重要的是,它的速度非常快,不愧是 Turbo 版的,再也不需要忍受“打字式”聊天了。
下面是一些基于 GPT-3.5-turbo 的网站。
https://chat.tgbot.co (反应快)
https://ai.ls (反应快)
https://ai.ci (反应快)
https://desk.im (反应快)
https://freegpt.one (反应快)
https://haoai.dev(反应快)
https://chatforai.com (反应快)
https://www.545852.xyz (反应慢)
https://www.scyu.app (反应慢)
https://chatgpt-local.vercel.app (反应慢)
自行提取ChatGPT接口 这里我只抓了一个接口进行对接企业微信
信息
import asyncio
from asyncio.proactor_events import _ProactorDuplexPipeTransport
import json
import random
import requests
import websockets
SERCIVE_TOKEN = ""
SERCIVE_HOST = "10.10.88.88:8888"
def ChatGPTApi(src):
url = "https://haoai.dev/api/generate"
data = {"messages": [{"role": "user", "content": src}]}
re_data = requests.post(url, data=data, timeout=(60, 60))
return re_data.text()
def new_SendTextMsg(Uid, ToUserId, ToUserType, Content):
url = "http://{}/v1/WeWork/SendMsg?Uid={}&Token={}".format(
SERCIVE_HOST, Uid, SERCIVE_TOKEN
)
payload = {
"MsgType": 0,
"ToUserId": ToUserId,
"ToUserType": ToUserType,
"Content": Content,
}
re_data = requests.post(url, json=payload)
return re_data.json()
async def Wsdemo():
uri = "ws://{}/ws?Token={}".format(SERCIVE_HOST, SERCIVE_TOKEN)
try:
async with websockets.connect(uri) as websocket:
while True:
greeting = await websocket.recv()
EventJson = json.loads(greeting)
EventName = EventJson["CurrentPacket"]["EventName"]
EventData = EventJson["CurrentPacket"]["EventData"]
UserID = EventJson["CurrentUser"]["UserID"]
print(f"< {greeting} {EventName}")
if EventName == "ON_EVENT_TOKEN_EXPIRED": # Token过期关闭WebSocket
print(f"< {greeting} {EventName}")
return
if EventName == "ON_EVENT_NEW_MSG":
# print(f"< {greeting} {EventName}")
NewAddMsg = EventData
ToUserId = NewAddMsg["ToUserId"]
ToUserType = NewAddMsg["ToUserType"]
FromUserId = NewAddMsg["FromUserId"]
if NewAddMsg["MsgType"] == 0 or NewAddMsg["MsgType"] == 2:
if NewAddMsg["AtUserInfo"] != None: # 针对对机器AT的类型提问进行处理回答 不at机器人不回复
Content = ChatGPTApi(NewAddMsg["Content"])
new_SendTextMsg(
机器人Uid, ToUserId, ToUserType, Content
)
else:
continue
except Exception as e:
# 断线重连
t = random.randint(5, 8)
print(f"< 超时重连中... { t}", e)
await asyncio.sleep(t)
await Wsdemo()
asyncio.get_event_loop().run_until_complete(Wsdemo())
修改于 2023-03-11 02:48:40