> 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/liao-tian-wan-zheng-ji-cheng-shi-li.md).

# 聊天：完整集成示例

这是一个完整示例，展示了典型的 Unity SDK 用法，包括动态令牌认证、自定义替换策略、制裁监控以及重新认证处理：

{% code fullWidth="true" %}

```csharp
using UnityEngine;
using System.Threading.Tasks;
using GGWP.Chat;
using GGWP.Sanctions;
using GGWP.Utils.Async;

public class GGWPIntegration : MonoBehaviour
{
    private Subscriber<ChannelSanctionsState> sanctionsSubscriber;
    private Subscriber<SanitizationResponse> sanitizationSubscriber;
    private Subscriber<GGWP.Impl.AuthStatus> authSubscriber;

    async void Start()
    {
        await InitializeSDK();
        // 在订阅制裁之前先进行认证，以便立即建立 WebSocket 连接
        await AuthenticateUser();
        ConfigureReplacementStrategy();
        MonitorAuthentication();
        // 在认证后订阅制裁，以获取即时实时更新
        MonitorSanctions();
        MonitorSanitization();
    }

    async Task InitializeSDK()
    {
        if (GGWPSDK.Instance == null)
        {
            Debug.LogError("GGWPSDK 不可用");
            return;
        }

        // 使用客户 ID 和可选用户名进行初始化
        GGWPSDK.Instance.InitializeSDK("your_customer_id", "player_username");
        Debug.Log("SDK 已初始化");
    }

    async Task AuthenticateUser()
    {
        // 使用 OAuth 授权码交换认证（推荐）
        // 这也会建立用于制裁更新的 WebSocket 连接
        string authCode = GetAuthCodeFromBackend();
        
        try
        {
            var result = await GGWPSDK.Instance?.AuthManager.ExchangeAuthCode(authCode);

            if (result == GGWP.Impl.Result.Success)
            {
                Debug.Log("OAuth 认证成功");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"认证失败：{ex.Message}");
        }
    }

    void ConfigureReplacementStrategy()
    {
        // 可选：配置要使用的消息版本
        // 如果未设置，将使用服务默认的 UseFiltered 策略
        GGWPSDK.Instance?.ChatAPI.SetSanitizationConfig(new SanitizationConfigUpdate
        {
            client = new GGWP.Chat.Impl.SanitizationClientConfig
            {
                // 让 AI 为每条消息选择最佳替换策略
                messageReplacementConfig = ReplacementStrategy.UseRecommended
            },
            service = null  // 对过滤设置使用服务默认值
        });
    }

    async void MonitorAuthentication()
    {
        authSubscriber = new Subscriber<GGWP.Impl.AuthStatus>(
            GGWPSDK.Instance?.AuthManager.SubscribeAuthUpdates()
        );

        await foreach (var status in authSubscriber.GetStream())
        {
            switch (status.status)
            {
                case GGWP.Impl.AuthStatusName.CodeExchangeSession:
                    Debug.Log("OAuth 会话处于活动状态 - 刷新已自动处理");
                    break;
                    
                case GGWP.Impl.AuthStatusName.NoAuth:
                    // 非常罕见的情况：会话连续多次刷新失败
                    Debug.LogWarning("认证会话丢失 - 需要重新认证");
                    
                    if (status.error.ToNullable() != null)
                    {
                        Debug.LogError($"认证错误：{status.error.ToNullable()}");
                    }
                    
                    // 再次执行代码交换以恢复会话
                    await ReauthenticateUser();
                    break;
            }
        }
    }

    private async Task ReauthenticateUser()
    {
        try
        {
            Debug.Log("正在尝试重新认证用户...");
            
            // 从你的后端获取新的 auth code
            string newAuthCode = GetAuthCodeFromBackend();
            
            // 交换新代码以获取新的会话
            var result = await GGWPSDK.Instance?.AuthManager.ExchangeAuthCode(newAuthCode);
            
            if (result == GGWP.Impl.Result.Success)
            {
                Debug.Log("重新认证成功");
            }
            else
            {
                Debug.LogError("重新认证失败");
                ShowLoginScreen();
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"重新认证错误：{ex.Message}");
            ShowLoginScreen();
        }
    }

    async void MonitorSanctions()
    {
        // 在认证后订阅制裁，以确保 WebSocket 已连接
        sanctionsSubscriber = new Subscriber<ChannelSanctionsState>(
            GGWPSDK.Instance?.SanctionsAPI.SubscribeSanctionsState()
        );

        await foreach (var state in sanctionsSubscriber.GetStream())
        {
            // 检查用户是否在聊天中被禁言，并相应更新 UI
            if (state.chat.status == GGWP.Sanctions.Impl.MuteStatus.Muted)
            {
                Debug.Log("用户在聊天中被禁言");
                DisableChatInput();
                
                // 可选：显示禁言何时到期
                if (state.chat.expiryAt != null)
                {
                    ShowMuteExpiryNotification(state.chat.expiryAt.Value);
                }
            }
            else
            {
                EnableChatInput();
            }
        }
    }

    async void MonitorSanitization()
    {
        // 订阅所有净化事件，用于日志记录或分析
        sanitizationSubscriber = new Subscriber<SanitizationResponse>(
            GGWPSDK.Instance?.ChatAPI.SubscribeSanitizedMessages()
        );

        await foreach (var sanitized in sanitizationSubscriber.GetStream())
        {
            LogMessageSanitization(sanitized);
        }
    }

    public async Task<bool> SendChatMessage(string message)
    {
        // ReplaceMessage 使用配置的替换策略（此处为 UseRecommended）
        var replaced = await GGWPSDK.Instance?.ChatAPI.ReplaceMessage(
            new ChatMessage { message = message }
        );

        if (replaced == null)
        {
            Debug.Log("消息被拦截 - 用户可能受到了制裁");
            ShowMessageBlockedNotification();
            return false;
        }

        // 返回的消息取决于你配置的 ReplacementStrategy
        // UseFiltered：用星号替换脏词
        // UseReplaced：用替代词替换脏词
        // UseRecommended：AI 根据上下文选择最佳版本
        // UseOriginal：原始消息保持不变
        SendToChat(replaced.messageDetails.replacedMessage);
        return true;
    }

    private string GetAuthCodeFromBackend() 
    { 
        /* 你的实现 - 调用后端从 GGWP 服务获取 auth code */ 
        return ""; 
    }
    
    private void DisableChatInput() 
    { 
        /* 你的实现 - 禁用聊天输入 UI */ 
    }
    
    private void EnableChatInput() 
    { 
        /* 你的实现 - 启用聊天输入 UI */ 
    }
    
    private void LogMessageSanitization(SanitizationResponse response) 
    { 
        /* 你的实现 - 记录净化事件用于分析 */ 
    }
    
    private void SendToChat(string message) 
    { 
        /* 你的实现 - 将消息发送到你的聊天系统 */ 
    }
    
    private void ShowLoginScreen() 
    { 
        /* 你的实现 - 向用户显示登录界面 */ 
    }
    
    private void ShowMuteExpiryNotification(DateTime expiryAt) 
    { 
        /* 你的实现 - 显示禁言何时结束 */ 
    }
    
    private void ShowMessageBlockedNotification() 
    { 
        /* 你的实现 - 通知用户其消息已被拦截 */ 
    }

    void OnDestroy()
    {
        // 清理所有订阅者以防止内存泄漏
        authSubscriber?.Dispose();
        sanctionsSubscriber?.Dispose();
        sanitizationSubscriber?.Dispose();
    }
}

```

{% endcode %}

}
