Skip to content

Instantly share code, notes, and snippets.

@ChenYFan
Last active February 24, 2024 14:17
Show Gist options
  • Save ChenYFan/c4db3e9f1d1686da49d0d1e8d8335a7a to your computer and use it in GitHub Desktop.
Save ChenYFan/c4db3e9f1d1686da49d0d1e8d8335a7a to your computer and use it in GitHub Desktop.
<span id="ChatHistory"></span>
<span><input type="text" id="ChatInput" /><button id="ChatSend">发送</button></span>
<script src="https://registry.npmmirror.com/marked/12.0.0/files/marked.min.js"></script>
<script>
function RealCozeAPIClient(url) {
this.ws = new WebSocket(url)
this.ready = false
this.callbacks = {}
this.ChatHistory = [
{
"role": 2,
"content": "Atri,你认得我吗"
},
{
"role": 1,
"content": "夏生先生!当然认得了!有什么事吗?夜深了,这么晚还不休息?"
}
]
this.GnerateUUID = () => {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == "x" ? r : (r & 3 | 8);
return v.toString(16);
});
}
this.addChatListener = (uuid, callback) => {
this.callbacks[uuid] = callback
}
this.mainListener = (data) => {
if (!data.success && data.errmsg.match(/regional restrictions/)) {
try { this.ws.close() } catch (e) { }
//触发了Worker诡异的出口问题,等待一秒后重连
Settimeout(() => {
this.ws = new WebSocket(url)
}, 1000)
}
}
this.ws.onopen = () => { this.ready = true }
this.ws.onmessage = (e) => {
const data = JSON.parse(e.data)
if (data.uuid === "main-thread") return this.mainListener(data)
if (typeof this.callbacks[data.uuid] === "function") this.callbacks[data.uuid](data.data)
if (!data.data.continue) {
delete this.callbacks[data.uuid]
this.ChatHistory.push({ role: 2, content: data.data.content })
}
}
this.send = (content, callback) => {
this.ChatHistory.push({ role: 1, content })
const uuid = this.GnerateUUID()
this.addChatListener(uuid, callback)
this.ws.send(JSON.stringify({
uuid,
data: this.ChatHistory
}))
}
}
const BackendAPI = new URL("")
BackendAPI = BackendAPI.url.replace(/^https:/, "wss:")
const RealCozeAPI = new RealCozeAPIClient(BackendAPI)
document.getElementById("ChatSend").addEventListener("click", () => {
const $H = document.getElementById("ChatHistory")
const $B = document.getElementById("ChatSend")
$B.disabled = true
const inputContent = document.getElementById("ChatInput").value
const $me = document.createElement("p")
$me.innerText = `Me> ${inputContent}`
$H.appendChild($me)
const $Atri = document.createElement("p")
$Atri.innerText = `Atri> ...`
$H.appendChild($Atri)
RealCozeAPI.send(inputContent, (data) => {
$Atri.innerText = `Atri> ${marked.parse(data.content)}`
if (!data.continue) $B.disabled = false
})
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment