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!
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
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
Rate Limiting
💬
💥
🏎️
Example of filtering out a "naughtyword" as defined by a moderation function