角色对话 API
角色对话 API - Convai 与 Roblox 集成的代码示例。
function my_functions.callConvai(msg, sessionID, apiKey, charID)
local httpSrv = game:GetService("HttpService")
local baseUrl = "https://api.convai.com/character/getResponse"
local gpt_response
local function request()
-- 如果以下值未正确设置,我们会限制发起不必要的调用
if apiKey == "" then
print("请提供有效的 API 密钥")
return
end
if charID == "" then
print("请输入有效的角色 ID")
return
end
-- REST API 调用
local response = httpSrv:RequestAsync({
Url = baseUrl,
Method = "POST",
Headers = {
-- 这是在 Roblox 中发送表单数据最方便的方式
["Content-Type"] = "application/x-www-form-urlencoded",
["CONVAI-API-KEY"] = apiKey
},
Body = string.format([[&userText=%s&sessionID=%s&charID=%s&voiceResponse=%s]], msg, sessionID, charID, 'False')
})
-- 检查响应表
if response.Success then
print("状态码:", response.StatusCode, response.StatusMessage)
print("响应正文:\n", response.Body)
local data = httpSrv:JSONDecode(response.Body)
print("响应文本:", data.text)
print("响应会话 ID:", data.sessionID)
gpt_response = response.Body --data.text
else
print("请求失败:", response.StatusCode, response.StatusMessage)
end
end
-- 将函数包裹在 'pcall' 中,以防请求失败时脚本崩溃
local success, message = pcall(request)
--print("状态码:", message)
if gpt_response == nil then
gpt_response = httpSrv:JSONEncode({sessionID = sessionID, text = "抱歉,我现在无法聊天。"})
end
return gpt_response
end
最后更新于
这有帮助吗?