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!
💥 Creating a New Moderation Function
For more information on how Pubnub functions operate, we recommend looking their documentation.
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:
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.
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
exportdefault (request) => {console.log("Request received:", request);// Extract the message text and ensure it existsconstmessage=request.message;if (!message ||!message.text) {console.error("Invalid message format.");returnrequest.abort('No message content found in request. Aborting request.' ); }// You can set a list of prohibited words hereconstprohibitedWords= ["BadWord1","BadWord2","BadWord3","BadWord4"];// Check if the message contains any prohibited words, and if so abort// the requestconstfoundProhibitedWord=prohibitedWords.find((word) =>message.text.toLowerCase().includes(word) );if (foundProhibitedWord) {console.warn(`Blocked message containing prohibited word: ${foundProhibitedWord}` );returnrequest.abort(`Message contains prohibited content: "${foundProhibitedWord}"` ); }returnrequest.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).
🏎️ Rate Limiting
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
conststore=require('kvstore');constconsole=require('console');exportdefault (request) => {// Window, aggregation period - if time > aggregationWindow has elapsed, clear history and reset storeconstaggregationWindow=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)constduration=60; // Seconds// Maximum number of messages you can send in the durationconstnoOfMessages=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 storeconstuniqueId=request.meta?.uuid ||request.meta?.clientip ||'unknown_user';if (!uniqueId) {console.warn('Message dropped: Unable to identify the user.');request.status =400;returnrequest.abort('Message Dropped: User cannot be identified.'); }constcurrentTime=Math.round(Date.now() /1000);returnstore.get('anti_spam').then((value) => {let antiSpamData = value || {};constaggregationStart=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 storelet userMessages = antiSpamData[uniqueId] || [];constoldestMessageTime= userMessages[0];// You can define what counts as allowed for the purposes of your rate limiting. For example:constisAllowed=!oldestMessageTime ||// No previous messages currentTime - oldestMessageTime > duration ||// Old messages are outside the duration windowuserMessages.length< noOfMessages; // Messages are within the allowed countif (!isAllowed) {console.warn(`Message dropped: User ${uniqueId} exceeded rate limit.`);request.status =400;returnrequest.abort('Message Dropped: Rate limit exceeded.'); }// Maintain sliding window: Remove oldest message if max limit reached,// in preparation to add new message timestampif (userMessages.length=== noOfMessages) {userMessages.shift(); }// Add current message timestampuserMessages.push(currentTime); antiSpamData[uniqueId] = userMessages;// Update the KV Storestore.set('anti_spam', {...antiSpamData, aggregation_start: currentTime, });console.log(`Message allowed for user ${uniqueId}`);returnrequest.ok(); }).catch((error) => {console.error('Error in anti-spam function:', error);request.status =500;returnrequest.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
conststore=require('kvstore');constconsole=require('console');exportdefault (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 existsconstmessage=request.message;if (!message ||!message.text) {console.error("Invalid message format.");returnrequest.abort('No message content found in request. Aborting request.' ); }// List of prohibited wordsconstprohibitedWords= ["somethingrude","badword","naughtyword","fuck","shit"];// Check if the message contains any prohibited wordsconstfoundProhibitedWord=prohibitedWords.find((word) =>message.text.toLowerCase().includes(word) );if (foundProhibitedWord) {console.warn(`Blocked message containing prohibited word: ${foundProhibitedWord}` );returnrequest.abort(`Message contains prohibited content: "${foundProhibitedWord}"` ); }/* RATE LIMIT/SPAM DETECTION */// Window, aggregation period - if time > aggregationWindow has elapsed, clear history and reset storeconstaggregationWindow=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)constduration=60; // Seconds// Maximum number of messages you can send in the durationconstnoOfMessages=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 storeconstuniqueId=request.meta?.uuid ||request.meta?.clientip ||'unknown_user';if (!uniqueId) {console.warn('Message dropped: Unable to identify the user.');request.status =400;returnrequest.abort('Message Dropped: User cannot be identified.'); }constcurrentTime=Math.round(Date.now() /1000);returnstore.get('anti_spam').then((value) => {let antiSpamData = value || {};constaggregationStart=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 storelet userMessages = antiSpamData[uniqueId] || [];constoldestMessageTime= userMessages[0];// You can define what counts as allowed for the purposes of your rate limiting. For example:constisAllowed=!oldestMessageTime ||// No previous messages currentTime - oldestMessageTime > duration ||// Old messages are outside the duration windowuserMessages.length< noOfMessages; // Messages are within the allowed countif (!isAllowed) {console.warn(`Message dropped: User ${uniqueId} exceeded rate limit.`);request.status =400;returnrequest.abort('Message Dropped: Rate limit exceeded.'); }// Maintain sliding window: Remove oldest message if max limit reached,// in preparation to add new message timestampif (userMessages.length=== noOfMessages) {userMessages.shift(); }// Add current message timestampuserMessages.push(currentTime); antiSpamData[uniqueId] = userMessages;// Update the KV Storestore.set('anti_spam', {...antiSpamData, aggregation_start: currentTime, });console.log(`Message allowed for user ${uniqueId}`);returnrequest.ok(); }).catch((error) => {console.error('Error in anti-spam function:', error);request.status =500;returnrequest.abort('Internal error: Unable to process the request.'); });};