> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/other-integrations/roblox/code-example/character-conversation-api.md).

# 角色对话 API

下面这段代码是成功调用 Convai 服务器、在与角色的对话中获取回复的最关键部分。

{% hint style="info" %}
请参阅 [角色 API 文档](/api-docs/zh/api-can-kao/core-api-reference/character-crafting-apis/character-api.md) 以了解该端点的更多细节。
{% endhint %}

{% hint style="info" %}
这部分代码位于 **GlobalFunctions** 脚本中，位于 **Convai Roblox 集成演示** 中，也就是你在上一节刚刚尝试过的内容。

该调用由 **Chat\_Character** 文件处理，该文件位于游戏 Workspace 中的角色模型内。
{% endhint %}

```lua
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

```

上面的函数在演示游戏的聊天框实现中被调用。下面简要说明每一部分的作用：

```lua
function my_functions.callConvai(msg, sessionID, apiKey, charID)
```

该函数接收 **message** 我们从用户那里获取的内容。我们会将其与 **sessionID 和 characterID 一起发送。** 我们还会传入 **API 密钥** ，也就是我们之前设置好的值。

```lua
local httpSrv = game:GetService("HttpService")
```

HttpService 允许从游戏服务器发送 HTTP 请求。 [详细信息](https://create.roblox.com/docs/reference/engine/classes/HttpService).

现在来看代码中最重要的部分：

```lua
-- 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')
}
```

{% hint style="info" %}
注意 **Content-Type** 被设置为 **"application/x-www-form-urlencoded"**。这是在 Roblox 中发送表单数据的唯一可接受方式。由于该端点只接受表单数据，我们必须将数据解析为合适的格式，以便发送到服务器。
{% endhint %}

而 **Body** 看起来可能像一个复杂的字符串，但实际上非常简单。将其拆解为简单组件后，可以表示为：

```json
{
    'userText': '<msg>',
    'sessionID': '<session-id>',
    'charID': '<character-id>',
    'voiceResponse': 'False'
}
```

{% hint style="info" %}
的值为 **voiceResponse** 被设置为 **False。** 由于我们并不需要服务器将生成的音频数据，所以直接跳过了音频生成。原因已经在 **限制** 前面提到过。
{% endhint %}

其余部分只是简单的响应处理代码。由于我们收到的响应是 JSON 数据，因此必须在客户端对其进行解码，才能读取其中的内容：

```lua
local data = httpSrv:JSONDecode(response.Body)
print("响应文本：", data.text)
print("响应会话 ID：", data.sessionID)
```

至此，我们关于 **/getResponse** API 的讨论就结束了。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/other-integrations/roblox/code-example/character-conversation-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
