Unity Integration Guide

Real-Time Chat Moderation

Unity Chat Filter Integration: Developer's Complete GuideBuild Safe Multiplayer Chat Systems with AI Moderation

Alan Agon
Alan Agon
January 19, 2025 · 9 min read

Implementing effective chat moderation in Unity requires more than just API calls: it demands careful consideration of performance, user experience, and network architecture. This comprehensive guide walks you through building a production-ready chat system with AI-powered moderation that scales with your player base.

Setup Requirements and Dependencies

Before diving into implementation, ensure your Unity project meets these requirements:

Project Requirements:

  • • Unity 2021.3 LTS or newer
  • • .NET Framework 4.x or Unity's IL2CPP
  • • Newtonsoft JSON package (via Package Manager)
  • • Unity Networking (if building multiplayer)
  • • Paxmod API key (get one at paxmod.com)

Basic API Integration

Let's start with a simple moderation client that makes direct HTTPS calls to the Paxmod API using Unity's UnityWebRequest:

PaxmodClient.cs

using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using Newtonsoft.Json;

public class PaxmodClient : MonoBehaviour
{
    private const string API_URL = "https://www.paxmod.com/api/v1/text";
    private string apiKey = "YOUR_API_KEY_HERE";
    
    [System.Serializable]
    public class ModerationRequest
    {
        public string message;
    }
    
    [System.Serializable]
    public class ModerationResponse
    {
        public bool flagged;
        public string reason;
        public float confidence;
        public string[] categories;
    }
    
    public void CheckMessage(string message, System.Action<ModerationResponse> callback)
    {
        StartCoroutine(CheckMessageCoroutine(message, callback));
    }
    
    private IEnumerator CheckMessageCoroutine(string message, System.Action<ModerationResponse> callback)
    {
        var request = new ModerationRequest { message = message };
        string jsonData = JsonConvert.SerializeObject(request);
        
        using (UnityWebRequest www = new UnityWebRequest(API_URL, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);
            www.uploadHandler = new UploadHandlerRaw(bodyRaw);
            www.downloadHandler = new DownloadHandlerBuffer();
            www.SetRequestHeader("Content-Type", "application/json");
            www.SetRequestHeader("Authorization", "Bearer " + apiKey);
            
            yield return www.SendWebRequest();
            
            if (www.result == UnityWebRequest.Result.Success)
            {
                var response = JsonConvert.DeserializeObject<ModerationResponse>(www.downloadHandler.text);
                callback?.Invoke(response);
            }
            else
            {
                Debug.LogError("Moderation API Error: " + www.error);
                callback?.Invoke(null);
            }
        }
    }
}

Building the Complete Chat System

Now let's create a full chat system that integrates seamlessly with our moderation client:

ChatManager.cs

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class ChatManager : MonoBehaviour
{
    [Header("UI References")]
    public TMP_InputField chatInput;
    public TMP_Text chatDisplay;
    public ScrollRect chatScrollRect;
    public Button sendButton;
    
    [Header("Moderation Settings")]
    public PaxmodClient moderationClient;
    public bool enableRealTimeModeration = true;
    public float moderationTimeout = 5f;
    
    private List<string> chatHistory = new List<string>();
    private Queue<string> pendingMessages = new Queue<string>();
    
    void Start()
    {
        sendButton.onClick.AddListener(SendMessage);
        chatInput.onEndEdit.AddListener(OnInputEndEdit);
    }
    
    void OnInputEndEdit(string input)
    {
        if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter))
        {
            SendMessage();
        }
    }
    
    public void SendMessage()
    {
        string message = chatInput.text.Trim();
        if (string.IsNullOrEmpty(message)) return;
        
        chatInput.text = "";
        chatInput.ActivateInputField();
        
        if (enableRealTimeModeration)
        {
            // Show "sending..." state
            AddSystemMessage("Sending message...");
            moderationClient.CheckMessage(message, OnModerationResult);
        }
        else
        {
            // Send immediately without moderation
            BroadcastMessage(message);
        }
    }
    
    private void OnModerationResult(PaxmodClient.ModerationResponse response)
    {
        if (response == null)
        {
            AddSystemMessage("Failed to send message. Please try again.");
            return;
        }
        
        if (response.flagged)
        {
            AddSystemMessage($"Message blocked: {response.reason}");
        }
        else
        {
            BroadcastMessage(pendingMessages.Dequeue());
        }
    }
    
    private void BroadcastMessage(string message)
    {
        string playerName = "Player"; // Get from player data
        string formattedMessage = $"[{System.DateTime.Now:HH:mm}] {playerName}: {message}";
        
        AddChatMessage(formattedMessage);
        
        // Send to other players via networking
        // NetworkManager.instance.SendChatMessage(message);
    }
    
    private void AddChatMessage(string message)
    {
        chatHistory.Add(message);
        UpdateChatDisplay();
    }
    
    private void AddSystemMessage(string message)
    {
        string systemMessage = $"[{System.DateTime.Now:HH:mm}] System: {message}";
        chatHistory.Add(systemMessage);
        UpdateChatDisplay();
    }
    
    private void UpdateChatDisplay()
    {
        chatDisplay.text = string.Join("
", chatHistory);
        Canvas.ForceUpdateCanvases();
        chatScrollRect.verticalNormalizedPosition = 0f;
    }
}

Performance Optimization Strategies

Real-time moderation can impact game performance if not implemented carefully. Here are key optimization techniques:

Request Batching

Batch multiple messages to reduce API calls and improve performance.

// Batch messages every 100ms or when queue reaches 5 messages private void Update() { if (messageQueue.Count >= 5 || (messageQueue.Count > 0 && Time.time - lastBatchTime > 0.1f)) { ProcessMessageBatch(); } }

Local Caching

Cache moderation results to avoid repeated API calls for similar content.

private Dictionary<string, ModerationResponse> moderationCache = new Dictionary<string, ModerationResponse>(); private bool TryGetCachedResult(string message, out ModerationResponse result) { string messageHash = message.GetHashCode().ToString(); return moderationCache.TryGetValue(messageHash, out result); }

Multiplayer Networking Considerations

When building multiplayer games, decide where moderation happens: client-side, server-side, or hybrid.

Architecture Options:

Client-Side Moderation:

Fast response, but can be bypassed by modified clients

Server-Side Moderation:

Secure and authoritative, but requires dedicated server infrastructure

Hybrid Approach:

Client pre-filtering + server verification for optimal UX and security

Testing and Deployment Best Practices

Pre-Launch Checklist:

  • ✅ Test with various message types and languages
  • ✅ Verify API key security (never expose in client builds)
  • ✅ Implement fallback behavior for API failures
  • ✅ Test under high-latency network conditions
  • ✅ Validate chat history persistence
  • ✅ Test moderation accuracy with edge cases

Production Environment Variables

// Use Unity's StreamingAssets or external config
public class Config : MonoBehaviour
{
    public static string GetAPIKey()
    {
        #if UNITY_EDITOR
            return "dev_api_key_here";
        #else
            return Environment.GetEnvironmentVariable("PAXMOD_API_KEY") ?? "fallback_key";
        #endif
    }
}

Ready to Implement Safe Chat in Unity?

Start building your Unity chat system with Paxmod's AI moderation today. Our developer-friendly API integrates seamlessly with Unity's networking stack and provides the real-time protection your multiplayer game needs.