> For the complete documentation index, see [llms.txt](https://docs.ggwp.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ggwp.com/chinese-simplified/ggwp-ke-hu-duan-sdk/qi-ta-zhi-chi-de-ji-cheng/liao-tian-discord-she-jiao-sdk.md).

# 聊天：Discord 社交 SDK

*本文档介绍了将 GGWP 与 Discord Social SDK 集成用于聊天服务的不同方法。*&#x20;

有三种方式可以使用 Discord Social SDK 将 GGWP Chat API 集成到游戏中。

**注意：** 方法（1）和（2）的审核能力有限（详见下文），而方法（3）提供完整的审核支持。

## 方法 1：Discord Webhooks - 直接集成

1. 登录你的 Discord 开发者门户并前往 [应用程序页面](https://discord.com/developers/applications)

   <figure><img src="/files/6d1f2344d2a3a081d47b635def8f0be698b69148" alt=""><figcaption></figcaption></figure>
2. 选择在你的 Social SDK 集成中使用的应用程序

   <figure><img src="/files/12053fcdb771fc51970629169dc66a8dc1a6c0b6" alt=""><figcaption></figcaption></figure>
3. 从 `基本信息` 下的 `设置`中，复制 `应用程序 ID` 和 `公钥` 并与你的 GGWP 客户经理共享。

   <figure><img src="/files/e7cdebd0efb62a04f09da70c5efb11ce618da4b7" alt=""><figcaption></figcaption></figure>
4. GGWP 团队会在其系统中配置你的应用，并共享一个 `端点 URL`
5. 选择 `Webhook` 在 `设置` 下方左侧，并将 GGWP 提供的 URL 填入 `端点 URL` 字段

   <figure><img src="/files/9efe8fea907239c5fe48cfbfadf79aec821742c7" alt=""><figcaption></figcaption></figure>
6. 切换 `事件` 开关为启用状态，并勾选 `大厅消息创建`&#x20;

   <figure><img src="/files/95ee6e55ad5059850ce2c8f89a845e044570224a" alt=""><figcaption></figcaption></figure>

### **要点**

1. 零代码数据接入！
2. 自定义 [过滤强度](https://docs.ggwp.com/api-docs-chat/standard-package/chat-api#headers) 按房间、组或社区划分不受支持。GGWP Chat 服务将使用全局 [内容过滤器配置](https://docs.ggwp.com/dashboard-user-guide/admin-features#content-filter-configuration).
3. 由于 Discord Social SDK 目前仅支持 [仅在客户端进行审核](https://discord.com/developers/docs/discord-social-sdk/how-to/integrate-moderation).
4. 一旦激活 GGWP Automod，就可以通过 GGWP webhooks 强制执行用户处罚，但你需要负责处理游戏客户端上的通信并采取适当的操作。

### **消息流程**

<figure><img src="/files/1d58026b85bffbba589961dead34cd473ed27f7b" alt=""><figcaption></figcaption></figure>

## 方法 2：Discord Webhooks - 自主管理

1. 遵循 Discord [Webhook 事件指南](https://discord.com/developers/docs/events/webhook-events) 在你的服务器中实现 webhook。
2. 通过 Discord webhook 调用接收到消息后 [GGWP Chat API](https://docs.ggwp.com/api-docs-chat/standard-package/chat-api) 使用 GGWP 共享 API 密钥。

### **要点**

1. 由于你是直接调用 Chat API，因此可以使用大厅 ID 或频道 ID 等属性为每个房间、组或社区设置过滤强度。如果你未指定，则会使用全局 [内容过滤设置](https://docs.ggwp.com/dashboard-user-guide/admin-features#content-filter-configuration) 。
2. 由于 Discord Social SDK 目前仅支持 [仅在客户端进行审核](https://discord.com/developers/docs/discord-social-sdk/how-to/integrate-moderation).
3. 一旦激活 GGWP Automod，就可以通过 GGWP webhooks 强制执行用户处罚，但你需要负责处理游戏客户端上的通信并采取适当的操作。

### 消息流程

<figure><img src="/files/2ea9efe347b5323f7833b4fe7a55926b0669b210" alt=""><figcaption></figcaption></figure>

## 方法 3：使用 GGWP SDK

1. 需要客户端侧集成。SDK 初始化完成后，它将负责：
   1. 使用短期动态令牌进行安全身份验证
   2. 将消息发送到 GGWP 进行审核
   3. 防止有害消息出现在 Social SDK 中
2. 需要在你的服务器上构建一个 API 来处理 GGWP SDK 身份验证

   该 API 将使用 `x-api-key` 与 GGWP 服务器通信进行身份验证。作为响应，你会收到一个认证代码，该代码有效期为 5 分钟，并可兑换为临时访问令牌。

### **要点**

1. 可在客户端侧针对任意房间、组或社区控制过滤强度。
2. 防止有害消息显示
3. 一旦激活 GGWP Automod，用户处罚即可直接通过 SDK 处理和执行

### 消息流程

<figure><img src="/files/b0acd19c687b813e00f79ff602305650637f8a9a" alt=""><figcaption></figcaption></figure>

### 集成指南 - Unity

在集成 SDK 之前，请确保你的服务端已配置为支持通过以下方式进行身份验证： [动态令牌](/chinese-simplified/ggwp-ke-hu-duan-sdk/ren-zheng.md#dynamic-tokens).

GGWP 的聊天产品通过客户端 SDK 得到完整支持。一旦在客户端完成 SDK 初始化，就可以如下访问 Chat API：

```csharp
GGWPSDK.Instance?.InitializeSDK("user_id", "username");

if (GGWPSDK.Instance?.ChatAPI != null)
{
    // Chat API 已可使用
}
```

关于此主题，需要了解两个方面：

1. 消息替换和过滤强度配置 - 决定消息应如何被评估以及应如何处理结果。
2. 调用 Chat 服务 - 实际将消息发送到 GGWP 的服务器

#### 消息替换和过滤强度配置

**设置过滤强度**

可以为发送到 GGWP 的消息设置过滤强度，以决定评估应多严格/多宽松。配置过滤强度是 **完全可选的**。如果你不设置，系统会自动使用默认值。默认值可以 [通过仪表板更新](/chinese-simplified/kong-zhi-tai-yong-hu-zhi-nan/guan-li-yuan-gong-neng.md#content-filter-configuration).

[这里 ](/chinese-simplified/api-wen-dang-liao-tian/biao-zhun-tao-can/liao-tian-api-v2-jiu-ban.md#headers)是 GGWP 提供的可用选项列表。在客户端上，可以通过 `SetSanitizationConfig` .&#x20;

**消息替换策略**

当消息被 GGWP 服务处理后，响应中会返回该消息的多个版本。 `messageReplacementConfig` 设置决定在你调用 `ReplaceMessage`.&#x20;

时 SDK 使用哪个版本。以下是可用的消息版本，以及在客户端设置替换策略时要使用的标识符

* **original\_message**
  * 定义：用户发送的原始消息。
  * 标识符： `UseOriginal`
* **filtered\_message**
  * 定义：已过滤掉标记术语的消息版本。
    * 对于以空格分隔的语言（例如英语），会过滤整个单词。例如 `你是个混蛋` --> `你是个 *****`
    * 对于没有明确词边界的语言（例如韩语、日语、中文），只会过滤检测到的词语本身。" 例如 `좆까고 있네`--> `*****고 있네`
  * （默认）标识符： `UseFiltered`
* **replaced\_message**
  * 定义：用于替代原始消息的安全或幽默替代版本。
  * 标识符：  `UseReplaced`
* **recommended\_message**
  * 定义：建议传递给客户端的消息版本。对于活跃用户，该值默认为 `filtered_message`。对于已静音用户， `recommended_message` 将为空字符串。
  * 标识符： `UseRecommended`

还有一个额外的策略 - `DropMessage` 它将确保没有任何内容上行发送到 Discord Social SDK。如果你不希望在 GGWP 判定消息有害时将任何消息发送到 Discord Social，请使用此策略。

以下代码片段展示了如何设置消息替换策略和过滤强度：

```csharp
using GGWP.Chat;

GGWPSDK.Instance?.ChatAPI.SetSanitizationConfig(new SanitizationConfigUpdate
{
    client = new GGWP.Chat.Impl.SanitizationClientConfig
    {
        // 选择在调用 ReplaceMessage 时要使用的消息版本
        messageReplacementConfig = ReplacementStrategy.UseFiltered  // 默认：使用 filtered_message
        // messageReplacementConfig = ReplacementStrategy.UseReplaced  // 使用 replaced_message
        // messageReplacementConfig = ReplacementStrategy.UseRecommended  // 使用 recommended_message
        // messageReplacementConfig = ReplacementStrategy.UseOriginal  // 使用 original_message
        // messageReplacementConfig = ReplacementStrategy.DropMessage  // 直接丢弃消息
    },
    service = new GGWP.Chat.Impl.SanitizationServiceConfig
    {
        violence = ConfigOptionSetting.High,
        sexualContent = ConfigOptionSetting.High,
        verbalAbuse = ConfigOptionSetting.High,
        identityHate = ConfigOptionSetting.High,
        profanity = ConfigOptionSetting.High,
        linkSharing = ConfigOptionSetting.High,
        drugs = ConfigOptionToggle.On,
        spam = ConfigOptionToggle.On,
        selfHarm = ConfigOptionToggle.Off,
        pii = ConfigOptionToggle.On,
        replace = ConfigOptionToggle.On,
    }
});
```

**消息替换策略如何影响消息处理**

你选择的替换策略会影响你调用时返回的消息文本 `ReplaceMessage`。下面是一个实际示例，展示相同的攻击性输入会如何根据你选择的策略而以不同方式处理：

```csharp
// 原始用户输入
string userMessage = "you stupid idiot go away";

// 当你调用 ReplaceMessage 时，返回的消息取决于你的策略：
var replaced = await GGWPSDK.Instance?.ChatAPI.ReplaceMessage(
    new ChatMessage { message = userMessage }
);

// 使用 UseFiltered（默认）："you ****** ***** go away"
// 使用 UseReplaced："you silly person go away"  
// 使用 UseRecommended：服务的 AI 会为此特定消息选择最佳版本
// 使用 UseOriginal："you stupid idiot go away"
```

你选择的策略会在你使用时自动应用，因此 `ReplaceMessage`，你无需每次都指定它。你可以随时通过再次调用 `SetSanitizationConfig` 并使用新的 `messageReplacementConfig` 值来更改策略。

**检索当前配置**

获取当前的净化配置，包括你选择的替换策略和服务默认值：

```csharp
var config = await GGWPSDK.Instance?.ChatAPI.GetSanitizationConfig();

// 访问客户端配置以查看当前激活的替换策略
var replacementStrategy = config.client.messageReplacementConfig;
Debug.Log($"当前策略：{replacementStrategy}");

// 访问服务端配置
if (config.service != null)
{
    var spamSetting = config.service.Value.spam;
    var selfHarmSetting = config.service.Value.selfHarm;
}
```

#### 从客户端调用 GGWP 的 Chat 服务

**净化消息**

净化一条消息以检查其中是否包含有害内容。无论你的替换策略设置如何，此方法始终返回该消息的所有版本：

```csharp
using GGWP.Chat;

string userMessage = "用户的消息在这里";

var sanitized = await GGWPSDK.Instance?.ChatAPI.SanitizeMessage(
    new ChatMessage { message = userMessage }
);

// 你可以访问所有版本，查看消息是如何被处理的
string original = sanitized.messageDetails.originalMessage;
string filtered = sanitized.messageDetails.filteredMessage;
string replaced = sanitized.messageDetails.replacedMessage;

Debug.Log($"原始：{original}");
Debug.Log($"过滤后：{filtered}");
Debug.Log($"替换后：{replaced}");
```

**订阅已净化消息**

实时监控所有已净化消息。此订阅会为每条已净化消息提供所有消息版本，让你完全了解净化流程：

```csharp
using GGWP.Utils.Async;
using GGWP.Chat;

var sanitizedSubscriber = new Subscriber<SanitizationResponse>(
    GGWPSDK.Instance?.ChatAPI.SubscribeSanitizedMessages()
);

await foreach (var sanitized in sanitizedSubscriber.GetStream())
{
    string original = sanitized.messageDetails.originalMessage;
    string filtered = sanitized.messageDetails.filteredMessage;
    string replaced = sanitized.messageDetails.replacedMessage;
    
    // 处理净化后的消息
    Debug.Log($"收到净化消息：{filtered}");
}
```

**替换消息**

用其净化版本替换一条消息。具体使用哪个版本取决于你配置的 `messageReplacementConfig` 策略。这通常是你在构建聊天系统时最常使用的方法，因为它会自动应用你选择的过滤方式：

```csharp
string userMessage = "用户的消息在这里";

var replaced = await GGWPSDK.Instance?.ChatAPI.ReplaceMessage(
    new ChatMessage { message = userMessage }
);

if (replaced != null)
{
    // 消息已根据你的策略成功替换
    // messageDetails 将包含由 ReplacementStrategy 选择的消息版本
    string messageToDisplay = replaced.messageDetails.replacedMessage;
    Debug.Log($"要显示的消息：{messageToDisplay}");
}
else
{
    // 消息已被丢弃（可能由于处罚）
    Debug.Log("消息已被丢弃");
}
```

<details>

<summary><strong>重要：由于处罚导致的消息丢弃</strong></summary>

当用户被处罚（静音）时，无论替换策略如何，他们的消息都会被丢弃。 `ReplaceMessage` 方法返回 null，以表示该消息不应发送：

```csharp
// 如果用户在聊天频道中被静音
var replaced = await GGWPSDK.Instance?.ChatAPI.ReplaceMessage(
    new ChatMessage { message = "任何消息" }
);

if (replaced == null)
{
    Debug.Log("用户已被静音，消息被丢弃");
}
```

</details>

## 参考资料

1. [GGWP 全局内容过滤器配置](https://docs.ggwp.com/dashboard-user-guide/admin-features#content-filter-configuration)
2. [GGWP 中可用的过滤设置](https://docs.ggwp.com/api-docs-chat/standard-package/chat-api#headers)
3. [使用 Discord Social SDK 进行审核](https://discord.com/developers/docs/discord-social-sdk/how-to/integrate-moderation)
4. [在你的 Social SDK 应用中启用 Discord Webhooks](https://discord.com/developers/docs/events/webhook-events)
