Real-Time Chat Filtering
In live environments like Twitch streams or multiplayer games, every millisecond counts. This example demonstrates how to perform synchronous moderation on a WebSocket stream, ensuring no toxic content ever reaches the end-users.
01. ARCHITECTURE
The typical flow for real-time moderation is:
User Client→ [WS] →Server (SafeComms)→ [WS] →Broadcast
02. SERVER SETUP
Install dependencies:
npm install ws @safecomms/sdk03. IMPLEMENTATION
Complete WebSocket server with inline moderation:
const WebSocket = require('ws');
const { SafeComms } = require('@safecomms/sdk');
const wss = new WebSocket.Server({ port: 8080 });
const safecomms = new SafeComms({ apiKey: process.env.SAFECOMMS_API_KEY });
// > CLIENT_CONNECTION_HANDLER
wss.on('connection', (ws) => {
console.log('> NEW_UPLINK_ESTABLISHED');
ws.on('message', async (message) => {
// 1. Parse incoming message
const data = JSON.parse(message);
// 2. > MODERATE_CONTENT
const analysis = await safecomms.text.analyze({
content: data.text
});
// 3. > DECISION_LOGIC
if (analysis.flagged) {
// Logic: Block the message and notify sender
ws.send(JSON.stringify({
type: 'SYSTEM_ALERT',
message: 'Message blocked: content policy violation.',
reason: analysis.primaryCategory
}));
console.log(`> THREAT_BLOCKED: ${analysis.primaryCategory}`);
} else {
// Logic: Broadcast to all other clients
const safePayload = JSON.stringify({
type: 'CHAT_MESSAGE',
user: data.user,
text: data.text,
timestamp: Date.now()
});
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(safePayload);
}
});
}
});
});
console.log('> SECURE_CHAT_SERVER_ONLINE_PORT_8080');> LATENCY_NOTE
SafeComms averages <500ms response times. For extremely high-frequency chat (e.g., 100+ msg/sec), consider using our Async Batch API or optimistically showing messages to the sender while moderating in the background.