> 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

角色对话 API——Convai 与 Roblox 集成的代码示例。

以下这段代码是成功调用 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 密钥")
			返回
		end
		if charID == "" then
			print("请输入有效的角色 ID")
			返回
		end
		
		-- REST API 调用
		local response = httpSrv:RequestAsync({
			Url = baseUrl,
			Method = "POST",
			Headers = {
				-- 这是在 Roblox 中发送 form-data 的最便捷方式
				["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)
```

该函数接受 **消息** 我们从用户那里获取的消息。我们将其与 **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 中发送 form-data 的最便捷方式
		["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 中发送 form-data 的唯一可接受方式。由于该端点只接受表单数据，我们不得不将数据解析为合适的格式再发送到服务器。
{% endhint %}

虽然 **身体** 请求的这部分看起来像一个复杂的字符串，但实际上很简单。将其拆解为简单组成部分后，可以表示为：

```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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
