LogoLogo
API Status
  • 👋Welcome
  • 🌐What is Morpheus Platform?
    • Interoperability
  • â„šī¸Help
    • 📗Glossary
    • 🆘Support
    • Firewall problems
    • EULA
  • CREATION
    • 🎮Unreal Development
      • ⚡Get Started
        • âš’ī¸Download the Editor
        • âĢUpload Content
        • 🌎Creating your own map
        • 📝Morpheus Base Project
        • ❓Differences from Unreal
          • 🧍Character Configuration
        • 📡Morpheus Networking
          • Introduction to Morpheus Networking
          • Network Levels
          • Replicated Properties
          • RPCs
          • Morpheus Render Targets
          • Morpheus Array
          • Networking FAQ
          • Replicating Sublevels
      • 📚Features & Guides
        • 📒Example Plugin
          • Nameplates
          • In-game roles
          • Resizing
        • 🏊Actor Pooling
        • 🔊Audio
        • 🎭Avatars
          • Creating an Avatar
          • Attachments
            • MML Attachments
          • Custom Animation Variables
          • Importing an NFT collection
          • Capsules and Mesh Transforms
        • 🤖Bots
        • đŸŽ™ī¸Chat
          • Unreal Text Chat
        • đŸŽ›ī¸Control Panels
          • Control Panel Configuration
          • DJ booth mission control
          • Observer Controls
        • 🔉Crowd Audio
        • đŸ¤ŧCrowd Rendering
          • Legacy Animated Crowd
            • Animated Crowd Console Commands
            • Attaching static meshes to crowd members
          • Crowd Materials
          • Performance Parameters
          • Live Config Settings
          • Crowd Animation
            • Crowd Anim Blueprint
              • User Guide - Crowd Anim Blueprint
              • Reference Guide - ABP Nodes
                • Animation Playback
                • States and State Machines
                • Variables
                • Transitions
                • Special
                • Blends
                • Additional Notes
        • 🍱Helpers & Extras
          • "Instanced Objects" in Blueprints
          • Objects with "world context"
          • Making DataAsset classes
          • Duplicate Objects
          • The Bootflow Subsystem
          • The "Wait For Condition" System
          • Advanced Graphics settings
          • Listening to inputs on UObjects
          • Morpheus UserID
          • World Services
          • M2Extras: Skins System
        • đŸ–Ĩī¸Loading Screen
        • ⚡Live Config
          • Editing for a World
          • Editing Locally
          • Default Settings
          • Accessing via Blueprint
          • Adding New Settings
          • Overriding Defaults
          • Using Arrays
        • 🧊MML
        • đŸ•ēMotion Capture
        • 📡Networking
        • đŸ“ĸNotifications
        • Raycastable Crowd
        • 🌐Singletons
        • 📱Streaming & Multiplatform
          • GFN on mobile
        • đŸ–Ĩī¸UI
          • "UI Mode"
        • đŸ—ƒī¸User Collections
          • Creating a New Object Definition
          • Accessing from Unreal
            • Creating Objects Definitions
            • Transfer Objects
            • User Collection Views
            • Receiving Updates
        • đŸ“ēVideo Players
          • Embedded Video Player
          • Millicast video streaming
            • How to Setup an In-Game Video Stream
            • Picture-in-Picture mode
          • Streaming Video Player
            • How to Setup a URL Video Player
            • Picture-in-Picture mode
        • 🐞Visual Debugging
          • Inspector
        • đŸĒŸWeb UI
        • Online Services
          • KV Store Service
        • 💠Web Requests
          • Http Requests
            • Legacy HTTP Nodes
          • JSON Handling
          • WebSockets
          • Identity Validation
          • Allowed External URLs
          • Walkthrough Example
            • Example Counter Service
        • âœˆī¸World Travel
          • World Travel in the editor
        • Avatar Physics Assets
        • Action Gameplay Helper Components
      • 🔑Workflows
        • â†—ī¸Upgrade the Editor
          • đŸ–Ĩī¸Version History
        • âš™ī¸Editing Project Settings
        • 📈Profiling
        • đŸ§ēMarketplace Importing
        • đŸ› ī¸Extra Workflows
          • Setup Play-in-Editor
          • Setup Local Asset Validation
          • Adding Gameplay Tags
          • Validating Game Assets
          • Custom Connection Modes
          • Connect Editor to a World
          • Common Issues
      • 📚Useful Reading
        • ⭐Best Practices
    • 🌎Worlds
      • 📩Invite Players
        • Setting Role Groups
      • Persistent Worlds
      • Always on Worlds
    • 📅Running events
      • ✅Large scale events - Checklist
      • 👾Anti-Cheat (EAC)
      • 🎮Player Entry
        • 📱React Native
        • Steam
        • đŸ’ģHardware Reqs
      • đŸŽĨBroadcast
        • 📹OBS Integration
      • Failover
      • 🏁Capacity And Queue Management
  • ADMINS
    • đŸ‘ĒAccess Control
      • Adding metaverse contributors
      • Creating a new project
    • 💲Pricing
      • Development Support
      • Included Usage & Overages
      • Cloud Streaming
      • Access Modes
      • War Room Support
      • Platform SLA
    • âš™ī¸Settings
      • đŸ—ƒī¸Projects
  • APIs and Tooling
    • đŸ–Ĩī¸API Reference
      • Accounts
      • Events
      • Key/Value Store
      • Organizations
      • Realtime
      • User Profile
      • World Builder
      • Worlds
    • đŸ’ģTemplate Web App
      • đŸ’ĸModeration
    • Pixel Streaming
    • 🚀Launcher
  • Integrations
    • 📊Analytics
      • Sending events from web
      • 🎮Sending Events from Unreal
    • đŸ’ŦChat
      • 🎮Integrating Pubnub with your Unreal Project
      • Adding Moderation to Chat
Powered by GitBook
On this page
  • Introduction
  • Creating a New Moderation Function
  • Rate Limiting
  • Full Function Including Moderation and Rate Limiting

Was this helpful?

  1. Integrations
  2. Chat

Adding Moderation to Chat

How to monitor and manage your in-game chat using Pubnub function modules

PreviousIntegrating Pubnub with your Unreal Project

Last updated 4 months ago

Was this helpful?

Introduction

For your event, you may want to control and moderate chat that's sent to your pubnub channel. This can be done by creating a new moderation function on your application's keyset.

Pubnub functions can be configured to manage different rules you want to enforce. In this guide, we will look at setting up a basic moderation function, and also a rate limiter to prevent spam.

Pubnub function modules on free tier automatically pause after running for 7 days. If you notice moderation failing, please check that you have restarted your function module in Pubnub!

To get started, first create a new module in the "Functions" section of your Pubnub application:

In your new function module, click on " Create New Function", at which point you will be presented with the following modal:

Set the name to an appropriate value, and set the following:

  1. Select an event type: this must be set to Before Publish or Fire , in order to catch messages before they are published to your channel.

  2. Channel name: set this to * to apply it to all channels for your keyset.

Once done, you will be able to define some custom javascript to handle how your function responds to certain requests. An example with some basic filtering from a list of banned words can be seen below, but you can customise this however you like to suit your moderation purposes.

Example Moderation Script
export default (request) => {
  console.log("Request received:", request);

  // Extract the message text and ensure it exists
  const message = request.message;
  if (!message || !message.text) {
    console.error("Invalid message format.");
    return request.abort(
      'No message content found in request. Aborting request.'
    );
  }

  // You can set a list of prohibited words here
  const prohibitedWords = ["BadWord1", "BadWord2", "BadWord3", "BadWord4"];

  // Check if the message contains any prohibited words, and if so abort
  // the request
  const foundProhibitedWord = prohibitedWords.find((word) =>
    message.text.toLowerCase().includes(word)
  );

  if (foundProhibitedWord) {
    console.warn(
      `Blocked message containing prohibited word: ${foundProhibitedWord}`
    );
    return request.abort(
      `Message contains prohibited content: "${foundProhibitedWord}"`
    );
  }

  return request.ok();
};

Once done, you can test your moderation module immediately by sending a test payload. Start your module (in the top right), and click publish on a test message payload on the bottom left of the page. If functioning correctly, you should see something like this:

You can test your moderation is correctly blocking messages by testing the in-game chat when playing in editor (see an example at the top of this guide).

You may also want to control the rate in which users can send messages to your application's channels. This can be done by adding a rate limiter function to your existing moderation function (or creating a new function just for rate limiting if you don't want moderation).

If you want to set up rate limiting for your keyset, you can use this example script below. You can configure both the maximum number of messages a user can send, as well as the duration period in which they can be sent.

Example Rate Limiting Script
const store = require('kvstore');
const console = require('console');

export default (request) => {
  // Window, aggregation period - if time > aggregationWindow has elapsed, clear history and reset store
  const aggregationWindow = 120; // Seconds

  // Set this to a desired rate limit (e.g. if you want to cap 
  // msgs sent within 10 second window, set duration to 10)
  const duration = 60; // Seconds

  // Maximum number of messages you can send in the duration
  const noOfMessages = 5;

  let messageAllowed = false;
  // Extract a unique identifier for the user (use `uuid` or fallback to `clientip`)
  // This is used to retrieve all messages sent by this particular user in the KV store
  const uniqueId = request.meta?.uuid || request.meta?.clientip || 'unknown_user';

  if (!uniqueId) {
      console.warn('Message dropped: Unable to identify the user.');
      request.status = 400;
      return request.abort('Message Dropped: User cannot be identified.');
  }

  const currentTime = Math.round(Date.now() / 1000);

  return store.get('anti_spam').then((value) => {
      let antiSpamData = value || {};
      const aggregationStart = antiSpamData.aggregation_start || 0;

      if (currentTime - aggregationStart > aggregationWindow) {
          antiSpamData = {}; // if over 120s has elapsed, clear the store
      }

      // Get or initialize message history for the user from store
      let userMessages = antiSpamData[uniqueId] || [];
      const oldestMessageTime = userMessages[0];

      // You can define what counts as allowed for the purposes of your rate limiting. For example:
      const isAllowed =
          !oldestMessageTime || // No previous messages
          currentTime - oldestMessageTime > duration || // Old messages are outside the duration window
          userMessages.length < noOfMessages; // Messages are within the allowed count

      if (!isAllowed) {
          console.warn(`Message dropped: User ${uniqueId} exceeded rate limit.`);
          request.status = 400;
          return request.abort('Message Dropped: Rate limit exceeded.');
      }

      // Maintain sliding window: Remove oldest message if max limit reached,
      // in preparation to add new message timestamp
      if (userMessages.length === noOfMessages) {
          userMessages.shift();
      }

      // Add current message timestamp
      userMessages.push(currentTime);
      antiSpamData[uniqueId] = userMessages;

      // Update the KV Store
      store.set('anti_spam', {
          ...antiSpamData,
          aggregation_start: currentTime,
      });

      console.log(`Message allowed for user ${uniqueId}`);
      return request.ok();
  }).catch((error) => {
      console.error('Error in anti-spam function:', error);
      request.status = 500;
      return request.abort('Internal error: Unable to process the request.');
  });
};

Full Function Including Moderation and Rate Limiting

You can copy and paste the full script below into your newly created Pubnub function to set up some initial moderation and rate limiting for your application.

Full Script
const store = require('kvstore');
const console = require('console');

export default (request) => {
  /* AS BOTH RATE LIMIT AND MODERATION HAPPEN AS A BEFORE PUBLISH EVENT,
   * MANAGE BOTH RULES IN THE SAME FUNCTION
  */

  /* MODERATION FUNCTION */
  console.log("Request received:", request);

  // Extract the message text and ensure it exists
  const message = request.message;
  if (!message || !message.text) {
    console.error("Invalid message format.");
    return request.abort(
      'No message content found in request. Aborting request.'
    );
  }

  // List of prohibited words
  const prohibitedWords = ["somethingrude", "badword", "naughtyword", "fuck", "shit"];

  // Check if the message contains any prohibited words
  const foundProhibitedWord = prohibitedWords.find((word) =>
    message.text.toLowerCase().includes(word)
  );

  if (foundProhibitedWord) {
    console.warn(
      `Blocked message containing prohibited word: ${foundProhibitedWord}`
    );
    return request.abort(
      `Message contains prohibited content: "${foundProhibitedWord}"`
    );
  }

  /* RATE LIMIT/SPAM DETECTION */

  // Window, aggregation period - if time > aggregationWindow has elapsed, clear history and reset store
  const aggregationWindow = 120; // Seconds

  // Set this to a desired rate limit (e.g. if you want to cap 
  // msgs sent within 10 second window, set duration to 10)
  const duration = 60; // Seconds

  // Maximum number of messages you can send in the duration
  const noOfMessages = 5;

  let messageAllowed = false;
  // Extract a unique identifier for the user (use `uuid` or fallback to `clientip`)
  // This is used to retrieve all messages sent by this particular user in the KV store
  const uniqueId = request.meta?.uuid || request.meta?.clientip || 'unknown_user';

  if (!uniqueId) {
      console.warn('Message dropped: Unable to identify the user.');
      request.status = 400;
      return request.abort('Message Dropped: User cannot be identified.');
  }

  const currentTime = Math.round(Date.now() / 1000);

  return store.get('anti_spam').then((value) => {
      let antiSpamData = value || {};
      const aggregationStart = antiSpamData.aggregation_start || 0;

      if (currentTime - aggregationStart > aggregationWindow) {
          antiSpamData = {}; // if over 120s has elapsed, clear the store
      }

      // Get or initialize message history for the user from store
      let userMessages = antiSpamData[uniqueId] || [];
      const oldestMessageTime = userMessages[0];

      // You can define what counts as allowed for the purposes of your rate limiting. For example:
      const isAllowed =
          !oldestMessageTime || // No previous messages
          currentTime - oldestMessageTime > duration || // Old messages are outside the duration window
          userMessages.length < noOfMessages; // Messages are within the allowed count

      if (!isAllowed) {
          console.warn(`Message dropped: User ${uniqueId} exceeded rate limit.`);
          request.status = 400;
          return request.abort('Message Dropped: Rate limit exceeded.');
      }

      // Maintain sliding window: Remove oldest message if max limit reached,
      // in preparation to add new message timestamp
      if (userMessages.length === noOfMessages) {
          userMessages.shift();
      }

      // Add current message timestamp
      userMessages.push(currentTime);
      antiSpamData[uniqueId] = userMessages;

      // Update the KV Store
      store.set('anti_spam', {
          ...antiSpamData,
          aggregation_start: currentTime,
      });

      console.log(`Message allowed for user ${uniqueId}`);
      return request.ok();
  }).catch((error) => {
      console.error('Error in anti-spam function:', error);
      request.status = 500;
      return request.abort('Internal error: Unable to process the request.');
  });
};

Creating a New Moderation Function

For more information on how Pubnub functions operate, we recommend looking their .

Rate Limiting

đŸ’Ŧ
đŸ’Ĩ
đŸŽī¸
documentation
Example of filtering out a "naughtyword" as defined by a moderation function