> 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 文档](https://docs.convai.com/api-docs/zh/api-can-kao/core-api-reference/character-crafting-apis/character-api.md) 。
{% endhint %}

{% hint style="info" %}
这部分代码位于上一节中刚刚试用过的 **GlobalFunctions** 脚本中，该脚本属于 **Convai Roblox 集成演示** 。

此调用由游戏 Workspace 中角色模型内的 **Chat\_Character** 文件处理。
{% 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("Please provide a valid API Key")
			return
		end
		if charID == "" then
			print("Please enter a valid Character 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("Status code:", response.StatusCode, response.StatusMessage)
			print("Response body:\n", response.Body)
			local data = httpSrv:JSONDecode(response.Body)
			print("Response Text: ", data.text)
			print("Response Session ID: ", data.sessionID)
			gpt_response = response.Body --data.text
		else
			print("The request failed:", response.StatusCode, response.StatusMessage)
		end
	end

	-- 使用 'pcall' 包装函数，避免请求失败时脚本中断
	local success, message = pcall(request)
	--print("Status code: ", message)
	if gpt_response == nil then
		gpt_response = httpSrv:JSONEncode({sessionID = sessionID, text = "Sorry, I can't chat right now."})
	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 中发送表单数据最方便的方式
		["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("Response Text: ", data.text)
print("Response Session 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.
